|
| 1 | +import constants from '../constants.mts' |
| 2 | + |
| 3 | +/** |
| 4 | + * Sanitizes a name to comply with repository naming constraints. |
| 5 | + * Constraints: 100 or less A-Za-z0-9 characters only with non-repeating, |
| 6 | + * non-leading or trailing ., _ or - only. |
| 7 | + * |
| 8 | + * @param name - The name to sanitize |
| 9 | + * @returns Sanitized name that complies with repository naming rules, or empty string if no valid characters |
| 10 | + */ |
| 11 | +function sanitizeName(name: string): string { |
| 12 | + if (!name) { |
| 13 | + return '' |
| 14 | + } |
| 15 | + |
| 16 | + // Replace sequences of illegal characters with underscores. |
| 17 | + const sanitized = name |
| 18 | + // Replace any sequence of non-alphanumeric characters (except ., _, -) with underscore. |
| 19 | + .replace(/[^A-Za-z0-9._-]+/g, '_') |
| 20 | + // Replace sequences of multiple allowed special chars with single underscore. |
| 21 | + .replace(/[._-]{2,}/g, '_') |
| 22 | + // Remove leading special characters. |
| 23 | + .replace(/^[._-]+/, '') |
| 24 | + // Remove trailing special characters. |
| 25 | + .replace(/[._-]+$/, '') |
| 26 | + // Truncate to 100 characters max. |
| 27 | + .slice(0, 100) |
| 28 | + |
| 29 | + return sanitized |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Extracts and sanitizes a repository name. |
| 34 | + * |
| 35 | + * @param name - The repository name to extract and sanitize |
| 36 | + * @returns Sanitized repository name, or default repository name if empty |
| 37 | + */ |
| 38 | +export function extractName(name: string): string { |
| 39 | + const sanitized = sanitizeName(name) |
| 40 | + return sanitized || constants.SOCKET_DEFAULT_REPOSITORY |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Extracts and sanitizes a repository owner name. |
| 45 | + * |
| 46 | + * @param owner - The repository owner name to extract and sanitize |
| 47 | + * @returns Sanitized repository owner name, or undefined if input is empty |
| 48 | + */ |
| 49 | +export function extractOwner(owner: string): string | undefined { |
| 50 | + if (!owner) { |
| 51 | + return undefined |
| 52 | + } |
| 53 | + const sanitized = sanitizeName(owner) |
| 54 | + return sanitized || undefined |
| 55 | +} |
0 commit comments