|
| 1 | +const path = require("path"); |
| 2 | +const fs = require("fs"); |
| 3 | + |
| 4 | +/** |
| 5 | + * Custom jest resolver that handles: |
| 6 | + * 1. Package.json "imports" field (#/ subpath imports) — per-package resolution |
| 7 | + * 2. TypeScript .js → .ts extension mapping for ESM imports |
| 8 | + * |
| 9 | + * Replaces jest-ts-webcompat-resolver with full #/ import support. |
| 10 | + */ |
| 11 | +module.exports = (request, options) => { |
| 12 | + // Handle #/ subpath imports by reading the nearest package.json |
| 13 | + if (request.startsWith("#/")) { |
| 14 | + const packageRoot = findPackageRoot(options.basedir); |
| 15 | + if (packageRoot) { |
| 16 | + const pkgJson = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf-8")); |
| 17 | + if (pkgJson.imports) { |
| 18 | + const mapping = pkgJson.imports["#/*"]; |
| 19 | + if (mapping) { |
| 20 | + const base = typeof mapping === "string" ? mapping : mapping.source || mapping.default; |
| 21 | + if (base) { |
| 22 | + const prefix = base.replace("*", ""); |
| 23 | + const suffix = request.slice(2); |
| 24 | + const resolved = path.join(packageRoot, prefix, suffix); |
| 25 | + return resolveWithExtensions(resolved); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // Handle .js → .ts extension mapping for TypeScript ESM imports |
| 33 | + if (request.endsWith(".js")) { |
| 34 | + const tsRequest = request.slice(0, -3) + ".ts"; |
| 35 | + try { |
| 36 | + return options.defaultResolver(tsRequest, options); |
| 37 | + } catch { |
| 38 | + // Try .tsx |
| 39 | + } |
| 40 | + const tsxRequest = request.slice(0, -3) + ".tsx"; |
| 41 | + try { |
| 42 | + return options.defaultResolver(tsxRequest, options); |
| 43 | + } catch { |
| 44 | + // Fall through to default |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return options.defaultResolver(request, options); |
| 49 | +}; |
| 50 | + |
| 51 | +function findPackageRoot(dir) { |
| 52 | + let current = dir; |
| 53 | + while (current !== path.dirname(current)) { |
| 54 | + if (fs.existsSync(path.join(current, "package.json"))) { |
| 55 | + const pkg = path.join(current, "package.json"); |
| 56 | + const content = JSON.parse(fs.readFileSync(pkg, "utf-8")); |
| 57 | + if (content.imports) { |
| 58 | + return current; |
| 59 | + } |
| 60 | + } |
| 61 | + current = path.dirname(current); |
| 62 | + } |
| 63 | + return null; |
| 64 | +} |
| 65 | + |
| 66 | +function resolveWithExtensions(filePath) { |
| 67 | + const base = filePath.replace(/\.js$/, ""); |
| 68 | + for (const ext of [".ts", ".tsx", ".js"]) { |
| 69 | + const fullPath = base + ext; |
| 70 | + if (fs.existsSync(fullPath)) { |
| 71 | + return fullPath; |
| 72 | + } |
| 73 | + } |
| 74 | + if (fs.existsSync(filePath)) { |
| 75 | + return filePath; |
| 76 | + } |
| 77 | + throw new Error(`Cannot resolve: ${filePath}`); |
| 78 | +} |
0 commit comments