|
| 1 | +import { existsSync, readFileSync } from 'node:fs'; |
| 2 | +import { dirname, join, relative, resolve, sep } from 'node:path'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Result of resolving a module specifier for a file. |
| 6 | + */ |
| 7 | +export interface ModuleSpecifierResult { |
| 8 | + /** |
| 9 | + * The module specifier to use for ID generation. |
| 10 | + * - For packages: "{name}@{version}" (e.g., "point@1.0.0", "@myorg/shared@2.0.0") |
| 11 | + * - For local files: undefined (plugin will use default "./relative/path" format) |
| 12 | + */ |
| 13 | + moduleSpecifier: string | undefined; |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Cache for package.json lookups to avoid repeated filesystem reads. |
| 18 | + * Maps directory path to parsed package.json or null if not found. |
| 19 | + */ |
| 20 | +const packageJsonCache = new Map< |
| 21 | + string, |
| 22 | + { name: string; version: string } | null |
| 23 | +>(); |
| 24 | + |
| 25 | +/** |
| 26 | + * Find and read the nearest package.json for a given file path. |
| 27 | + * Results are cached for performance. |
| 28 | + */ |
| 29 | +function findPackageJson( |
| 30 | + filePath: string |
| 31 | +): { name: string; version: string } | null { |
| 32 | + let dir = dirname(filePath); |
| 33 | + |
| 34 | + while (dir !== dirname(dir)) { |
| 35 | + // Check cache first |
| 36 | + const cached = packageJsonCache.get(dir); |
| 37 | + if (cached !== undefined) { |
| 38 | + return cached; |
| 39 | + } |
| 40 | + |
| 41 | + const packageJsonPath = join(dir, 'package.json'); |
| 42 | + if (existsSync(packageJsonPath)) { |
| 43 | + try { |
| 44 | + const content = readFileSync(packageJsonPath, 'utf-8'); |
| 45 | + const parsed = JSON.parse(content); |
| 46 | + if (parsed.name && parsed.version) { |
| 47 | + const result = { name: parsed.name, version: parsed.version }; |
| 48 | + packageJsonCache.set(dir, result); |
| 49 | + return result; |
| 50 | + } |
| 51 | + } catch { |
| 52 | + // Invalid JSON or missing fields, continue searching |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + packageJsonCache.set(dir, null); |
| 57 | + dir = dirname(dir); |
| 58 | + } |
| 59 | + |
| 60 | + return null; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Check if a file path is inside node_modules. |
| 65 | + */ |
| 66 | +function isInNodeModules(filePath: string): boolean { |
| 67 | + const normalizedPath = filePath.split(sep).join('/'); |
| 68 | + return normalizedPath.includes('/node_modules/'); |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Check if a file path is inside a workspace package. |
| 73 | + * This is a heuristic - we check if the file is in a directory with a package.json |
| 74 | + * that has a "name" field, but is NOT in node_modules. |
| 75 | + */ |
| 76 | +function isWorkspacePackage(filePath: string, projectRoot: string): boolean { |
| 77 | + if (isInNodeModules(filePath)) { |
| 78 | + return false; |
| 79 | + } |
| 80 | + |
| 81 | + const pkg = findPackageJson(filePath); |
| 82 | + if (!pkg) { |
| 83 | + return false; |
| 84 | + } |
| 85 | + |
| 86 | + // Check if the package.json is not the root package.json |
| 87 | + // Use resolve() to normalize paths for cross-platform comparison |
| 88 | + const rootPkgPath = resolve(projectRoot, 'package.json'); |
| 89 | + |
| 90 | + // Walk up to find the package.json directory |
| 91 | + let dir = dirname(filePath); |
| 92 | + while (dir !== dirname(dir)) { |
| 93 | + const pkgPath = join(dir, 'package.json'); |
| 94 | + if (existsSync(pkgPath)) { |
| 95 | + // If this is the root package.json, it's not a workspace package |
| 96 | + // Use resolve() to normalize both paths before comparison |
| 97 | + if (resolve(pkgPath) === rootPkgPath) { |
| 98 | + return false; |
| 99 | + } |
| 100 | + // Found a package.json that's not the root - it's a workspace package |
| 101 | + return true; |
| 102 | + } |
| 103 | + dir = dirname(dir); |
| 104 | + } |
| 105 | + |
| 106 | + return false; |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * Resolve the module specifier for a file. |
| 111 | + * |
| 112 | + * @param filePath - Absolute path to the file being transformed |
| 113 | + * @param projectRoot - Absolute path to the project root (usually process.cwd()) |
| 114 | + * @returns The module specifier result |
| 115 | + * |
| 116 | + * @example |
| 117 | + * // File in node_modules |
| 118 | + * resolveModuleSpecifier('/project/node_modules/point/dist/index.js', '/project') |
| 119 | + * // => { moduleSpecifier: 'point@1.0.0' } |
| 120 | + * |
| 121 | + * @example |
| 122 | + * // File in workspace package |
| 123 | + * resolveModuleSpecifier('/project/packages/shared/src/utils.ts', '/project') |
| 124 | + * // => { moduleSpecifier: '@myorg/shared@0.0.0' } |
| 125 | + * |
| 126 | + * @example |
| 127 | + * // Local app file |
| 128 | + * resolveModuleSpecifier('/project/src/workflows/order.ts', '/project') |
| 129 | + * // => { moduleSpecifier: undefined } |
| 130 | + */ |
| 131 | +export function resolveModuleSpecifier( |
| 132 | + filePath: string, |
| 133 | + projectRoot: string |
| 134 | +): ModuleSpecifierResult { |
| 135 | + // Check if file is in node_modules or a workspace package |
| 136 | + const inNodeModules = isInNodeModules(filePath); |
| 137 | + const inWorkspace = |
| 138 | + !inNodeModules && isWorkspacePackage(filePath, projectRoot); |
| 139 | + |
| 140 | + if (!inNodeModules && !inWorkspace) { |
| 141 | + // Local app file - use default relative path format |
| 142 | + return { moduleSpecifier: undefined }; |
| 143 | + } |
| 144 | + |
| 145 | + // Find the package.json for this file |
| 146 | + const pkg = findPackageJson(filePath); |
| 147 | + if (!pkg) { |
| 148 | + // Couldn't find package.json - fall back to default |
| 149 | + return { moduleSpecifier: undefined }; |
| 150 | + } |
| 151 | + |
| 152 | + // Return the module specifier as "name@version" |
| 153 | + return { |
| 154 | + moduleSpecifier: `${pkg.name}@${pkg.version}`, |
| 155 | + }; |
| 156 | +} |
| 157 | + |
| 158 | +/** |
| 159 | + * Clear the package.json cache. Useful for testing or when package.json files may have changed. |
| 160 | + */ |
| 161 | +export function clearModuleSpecifierCache(): void { |
| 162 | + packageJsonCache.clear(); |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * Result of resolving an import path for a file. |
| 167 | + */ |
| 168 | +export interface ImportPathResult { |
| 169 | + /** |
| 170 | + * The import path to use. |
| 171 | + * - For workspace packages: the package name (e.g., "@myorg/shared") |
| 172 | + * - For node_modules packages: the package name |
| 173 | + * - For local files: a relative path (e.g., "./src/workflows/order.ts") |
| 174 | + */ |
| 175 | + importPath: string; |
| 176 | + |
| 177 | + /** |
| 178 | + * Whether this file is from a package (workspace or node_modules). |
| 179 | + * When true, the import should go through package resolution which respects export conditions. |
| 180 | + */ |
| 181 | + isPackage: boolean; |
| 182 | +} |
| 183 | + |
| 184 | +/** |
| 185 | + * Get the import path to use for a file in a bundle's virtual entry. |
| 186 | + * |
| 187 | + * For workspace packages and node_modules packages, returns the package name |
| 188 | + * so that bundler resolution will respect package.json exports and conditions. |
| 189 | + * |
| 190 | + * For local app files, returns a relative path. |
| 191 | + * |
| 192 | + * @param filePath - Absolute path to the file |
| 193 | + * @param projectRoot - Absolute path to the project root |
| 194 | + * @returns The import path and whether it's a package |
| 195 | + * |
| 196 | + * @example |
| 197 | + * // Workspace package |
| 198 | + * getImportPath('/project/packages/shared/src/index.ts', '/project') |
| 199 | + * // => { importPath: '@myorg/shared', isPackage: true } |
| 200 | + * |
| 201 | + * @example |
| 202 | + * // Local app file |
| 203 | + * getImportPath('/project/src/workflows/order.ts', '/project') |
| 204 | + * // => { importPath: './src/workflows/order.ts', isPackage: false } |
| 205 | + */ |
| 206 | +export function getImportPath( |
| 207 | + filePath: string, |
| 208 | + projectRoot: string |
| 209 | +): ImportPathResult { |
| 210 | + // Check if file is in node_modules or a workspace package |
| 211 | + const inNodeModules = isInNodeModules(filePath); |
| 212 | + const inWorkspace = |
| 213 | + !inNodeModules && isWorkspacePackage(filePath, projectRoot); |
| 214 | + |
| 215 | + if (inNodeModules || inWorkspace) { |
| 216 | + // Find the package.json for this file |
| 217 | + const pkg = findPackageJson(filePath); |
| 218 | + if (pkg) { |
| 219 | + return { |
| 220 | + importPath: pkg.name, |
| 221 | + isPackage: true, |
| 222 | + }; |
| 223 | + } |
| 224 | + } |
| 225 | + |
| 226 | + // Local app file - use relative path |
| 227 | + const normalizedProjectRoot = projectRoot.replace(/\\/g, '/'); |
| 228 | + const normalizedFilePath = filePath.replace(/\\/g, '/'); |
| 229 | + |
| 230 | + let relativePath: string; |
| 231 | + if (normalizedFilePath.startsWith(normalizedProjectRoot + '/')) { |
| 232 | + relativePath = normalizedFilePath.substring( |
| 233 | + normalizedProjectRoot.length + 1 |
| 234 | + ); |
| 235 | + } else { |
| 236 | + // File is outside project root, use the full path segments after common ancestor |
| 237 | + relativePath = relative(projectRoot, filePath).replace(/\\/g, '/'); |
| 238 | + } |
| 239 | + |
| 240 | + // Ensure relative paths start with ./ |
| 241 | + if (!relativePath.startsWith('.')) { |
| 242 | + relativePath = `./${relativePath}`; |
| 243 | + } |
| 244 | + |
| 245 | + return { |
| 246 | + importPath: relativePath, |
| 247 | + isPackage: false, |
| 248 | + }; |
| 249 | +} |
0 commit comments