|
| 1 | +import * as path from "path"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Normalize a path to the standard Humanloop API format. |
| 5 | + * |
| 6 | + * This function is primarily used when interacting with the Humanloop API to ensure paths |
| 7 | + * follow the standard format: 'path/to/resource' without leading/trailing slashes. |
| 8 | + * It's used when pulling files from Humanloop to local filesystem (see FileSyncer.pull) |
| 9 | + * |
| 10 | + * The function: |
| 11 | + * - Converts Windows backslashes to forward slashes |
| 12 | + * - Normalizes consecutive slashes |
| 13 | + * - Optionally strips file extensions (e.g. .prompt, .agent) |
| 14 | + * - Removes leading/trailing slashes to match API conventions |
| 15 | + * |
| 16 | + * Leading/trailing slashes are stripped because the Humanloop API expects paths in the |
| 17 | + * format 'path/to/resource' without them. This is consistent with how the API stores |
| 18 | + * and references files, and ensures paths work correctly in both API calls and local |
| 19 | + * filesystem operations. |
| 20 | + * |
| 21 | + * @param pathStr - The path to normalize. Can be a Windows or Unix-style path. |
| 22 | + * @param stripExtension - If true, removes the file extension (e.g. .prompt, .agent) |
| 23 | + * @returns Normalized path string in the format 'path/to/resource' |
| 24 | + * |
| 25 | + * @example |
| 26 | + * normalizePath("path/to/file.prompt") |
| 27 | + * // => 'path/to/file.prompt' |
| 28 | + * |
| 29 | + * @example |
| 30 | + * normalizePath("path/to/file.prompt", true) |
| 31 | + * // => 'path/to/file' |
| 32 | + * |
| 33 | + * @example |
| 34 | + * normalizePath("\\windows\\style\\path.prompt") |
| 35 | + * // => 'windows/style/path.prompt' |
| 36 | + * |
| 37 | + * @example |
| 38 | + * normalizePath("/leading/slash/path/") |
| 39 | + * // => 'leading/slash/path' |
| 40 | + * |
| 41 | + * @example |
| 42 | + * normalizePath("multiple//slashes//path") |
| 43 | + * // => 'multiple/slashes/path' |
| 44 | + */ |
| 45 | +export function normalizePath( |
| 46 | + pathStr: string, |
| 47 | + stripExtension: boolean = false, |
| 48 | +): string { |
| 49 | + // Convert Windows backslashes to forward slashes |
| 50 | + const normalizedSeparators = pathStr.replace(/\\/g, "/"); |
| 51 | + |
| 52 | + // Use path.posix to handle path normalization (handles consecutive slashes) |
| 53 | + // We use posix to ensure forward slashes are used consistently |
| 54 | + let normalizedPath = path.posix.normalize(normalizedSeparators); |
| 55 | + |
| 56 | + // Strip extension if requested |
| 57 | + if (stripExtension) { |
| 58 | + const ext = path.posix.extname(normalizedPath); |
| 59 | + normalizedPath = normalizedPath.slice(0, -ext.length); |
| 60 | + } |
| 61 | + |
| 62 | + // Remove leading/trailing slashes |
| 63 | + return normalizedPath.replace(/^\/+|\/+$/g, ""); |
| 64 | +} |
0 commit comments