The best way to control Claude Code, Codex and more from any computer or phone

main
ts 140 lines 4.98 KB
Raw
1 import path from "node:path";
2 import { fileURLToPath } from "node:url";
3 import { ResolverFactory, type ResolveOptions } from "rolldown/experimental";
4
5 /**
6 * TypeScript-aware specifier resolution on top of Oxc's resolver, mirroring
7 * what tsx layers over Node's resolver:
8 *
9 * - `tsconfig.json` `paths` / `baseUrl` aliases, discovered per importing file
10 * - emitted-extension substitution (`./x.js` → `x.ts`/`x.tsx`, `.mjs` → `.mts`,
11 * `.cjs` → `.cts`, `.jsx` → `.tsx`), TypeScript source winning over an
12 * emitted sibling
13 * - extensionless specifiers and directory indexes, TypeScript first
14 *
15 * Node's own resolver stays the authority: every candidate this class
16 * produces is handed back to Node (`nextResolve`) so it decides the format,
17 * validates package exports, and reports the canonical error.
18 */
19 export interface SpecifierResolverOptions {
20 /** Discover `tsconfig.json` upward from each importing file. */
21 readonly tsconfig: boolean;
22 }
23
24 export const nodeModulesSegment = `${path.sep}node_modules${path.sep}`;
25
26 /** Local project code: a file path outside every `node_modules` directory. */
27 export const isProjectPath = (filePath: string) => !filePath.includes(nodeModulesSegment);
28
29 const typeScriptExtensions = /\.(?:[cm]?ts|[tj]sx)$/;
30
31 /** Whether TypeScript's extension substitution applies to this importer. */
32 export const isTypeScriptPath = (filePath: string) => typeScriptExtensions.test(filePath);
33
34 export const isFileLikeSpecifier = (specifier: string) =>
35 specifier.startsWith("./") ||
36 specifier.startsWith("../") ||
37 specifier === "." ||
38 specifier === ".." ||
39 specifier.startsWith("file:") ||
40 path.isAbsolute(specifier);
41
42 /**
43 * Splits `?query#fragment` metadata off a specifier. Bare specifiers never
44 * carry fragments in Node, so only `?` is honoured there.
45 */
46 export const splitSpecifierMetadata = (specifier: string) => {
47 const index = isFileLikeSpecifier(specifier) ? specifier.search(/[?#]/) : specifier.indexOf("?");
48 return index === -1
49 ? { specifier, metadata: "" }
50 : {
51 specifier: specifier.slice(0, index),
52 metadata: specifier.slice(index),
53 };
54 };
55
56 export const filePathOfUrl = (url: string | undefined) => {
57 if (url === undefined || !url.startsWith("file:")) return undefined;
58 try {
59 return fileURLToPath(new URL(url));
60 } catch {
61 return undefined;
62 }
63 };
64
65 export class SpecifierResolver {
66 readonly #options: ResolveOptions;
67 readonly #base: ResolverFactory;
68 readonly #byConditions = new Map<string, ResolverFactory>();
69
70 constructor(options: SpecifierResolverOptions) {
71 this.#options = {
72 tsconfig: options.tsconfig ? "auto" : undefined,
73 // TypeScript source first, then Node's implicit extensions.
74 extensions: [".ts", ".tsx", ".mts", ".cts", ".jsx", ".js", ".mjs", ".cjs", ".json", ".node"],
75 // TypeScript's emitted-extension substitution: `./x.js` may point at
76 // `x.ts` (source) or `x.js` (emitted); source wins when both exist.
77 extensionAlias: {
78 ".js": [".ts", ".tsx", ".js"],
79 ".jsx": [".tsx", ".jsx"],
80 ".mjs": [".mts", ".mjs"],
81 ".cjs": [".cts", ".cjs"],
82 },
83 mainFiles: ["index"],
84 builtinModules: true,
85 moduleType: true,
86 };
87 this.#base = new ResolverFactory(this.#options);
88 }
89
90 /**
91 * Bare specifiers are probed without following symlinks: a workspace
92 * package linked into `node_modules` must still read as a package (and be
93 * left to Node), not as the project file its real path points at.
94 */
95 #resolver(conditions: ReadonlyArray<string>, symlinks: boolean) {
96 const key = `${symlinks} ${conditions.join(" ")}`;
97 let resolver = this.#byConditions.get(key);
98 if (resolver === undefined) {
99 // `cloneWithOptions` replaces the option set (sharing only the cache),
100 // so each conditions variant restates the base options.
101 resolver = this.#base.cloneWithOptions({
102 ...this.#options,
103 symlinks,
104 conditionNames: [...conditions],
105 });
106 this.#byConditions.set(key, resolver);
107 }
108 return resolver;
109 }
110
111 /**
112 * Resolves `specifier` as imported from `parentPath` to an absolute file
113 * path, or `undefined` when Oxc cannot resolve it (Node then reports the
114 * error), when it is a builtin, or when a bare specifier lands inside
115 * `node_modules` — packages are Node's business, only `paths` aliases
116 * that map onto project files are ours.
117 */
118 resolve(
119 parentPath: string,
120 specifier: string,
121 conditions: ReadonlyArray<string>,
122 ): string | undefined {
123 const request = specifier.startsWith("file:") ? filePathOfUrl(specifier) : specifier;
124 if (request === undefined) return undefined;
125 let result;
126 try {
127 result = this.#resolver(conditions, isFileLikeSpecifier(request)).resolveFileSync(
128 parentPath,
129 request,
130 );
131 } catch {
132 return undefined;
133 }
134 if (result.path === undefined) return undefined;
135 if (!isFileLikeSpecifier(request) && !isProjectPath(result.path)) {
136 return undefined;
137 }
138 return result.path;
139 }
140 }