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

main
ts 240 lines 9.96 KB
Raw
1 import { readFileSync } from "node:fs";
2 import * as NodeModule from "node:module";
3 import type {
4 LoadFnOutput,
5 LoadHookContext,
6 LoadHookSync,
7 ResolveFnOutput,
8 ResolveHookContext,
9 ResolveHookSync,
10 } from "node:module";
11 import { pathToFileURL } from "node:url";
12 import {
13 filePathOfUrl,
14 isProjectPath,
15 SpecifierResolver,
16 splitSpecifierMetadata,
17 } from "./resolve.ts";
18 import { SourceTransformer } from "./transform.ts";
19
20 export interface LoaderOptions {
21 /**
22 * Additional package export conditions used during module resolution.
23 * They are made available alongside Node's ambient conditions to both the
24 * TypeScript-aware resolver and Node's package exports resolver.
25 */
26 readonly conditions?: ReadonlyArray<string> | undefined;
27 /**
28 * Honour `tsconfig.json` discovered upward from each file: compiler
29 * options for the transform, `paths`/`baseUrl` aliases for resolution.
30 * @default true
31 */
32 readonly tsconfig?: boolean | undefined;
33 /**
34 * Limits transformation to matching absolute file paths; everything else
35 * loads through Node untouched. Lets a published install transpile only
36 * the user's own TypeScript while alchemy and its dependencies run their
37 * built JavaScript.
38 */
39 readonly filter?: ((path: string) => boolean) | undefined;
40 /**
41 * On-disk cache of Oxc output shared by every process on the machine, so
42 * the CLI, its dev exec child and the local-provider sidecars transpile
43 * each source file once between them rather than once each. `false`
44 * disables it, a string names the directory.
45 * @default `$ALCHEMY_TRANSFORM_CACHE` (`0` disables), else a per-user
46 * directory under the OS temp directory
47 */
48 readonly cache?: boolean | string | undefined;
49 }
50
51 /** Synchronous Node module hooks, as `module.registerHooks` takes them. */
52 export interface LoaderHooks {
53 readonly resolve: ResolveHookSync;
54 readonly load: LoadHookSync;
55 }
56
57 type NextResolve = Parameters<ResolveHookSync>[2];
58
59 /**
60 * Node's module compile cache (`module.enableCompileCache`) keeps V8 code
61 * cache for compiled modules — transformed TypeScript included, since it is
62 * keyed by the compiled source — but Node only persists it once after the
63 * entry module evaluated and again on a clean exit. Alchemy processes load
64 * most of their graph lazily after that point (commands, the user's stack,
65 * provider layers) and usually stop on a signal, so without an explicit
66 * flush that code never reaches the cache. Flush once module loading has
67 * gone quiet; a no-op when the cache is off or this Node predates it.
68 */
69 const scheduleCompileCacheFlush = (() => {
70 let timer: NodeJS.Timeout | undefined;
71 return () => {
72 if (NodeModule.getCompileCacheDir?.() === undefined) return;
73 if (timer !== undefined) clearTimeout(timer);
74 timer = setTimeout(() => {
75 timer = undefined;
76 NodeModule.flushCompileCache?.();
77 }, 1000);
78 timer.unref();
79 };
80 })();
81
82 /**
83 * Whether `require()` breaks inside an imported CommonJS module whose source
84 * the load hook supplied (nodejs/node#62920, fixed in 24.18 and 26.2, never
85 * in 25.x): Node evaluates it with a stand-in `require` that cannot load ES
86 * modules, so a `.cts` requiring TypeScript fails. On these versions the
87 * hook leaves imported CommonJS to Node's default load, which defers it to
88 * the real CommonJS loader without reading it; that loader's `require()`
89 * calls reach the hook again, now in a require context, and are transpiled
90 * there. Returning `source: null` directly is rejected by synchronous hooks
91 * on older 24.x; Node's default load defers from 24.11.1 and 25.1
92 * (nodejs/node#59929), alchemy's minimums. A namespaced (reloaded) graph
93 * keeps such files fresh by evicting them from the path-keyed CommonJS
94 * cache between generations (see ../watch/import-watcher.ts).
95 */
96 const importedCommonJsNeedsNodeLoader = (() => {
97 const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
98 return major < 24 || (major === 24 && minor < 18) || major === 25 || (major === 26 && minor < 2);
99 })();
100
101 /** Specifiers Node owns outright: builtins, data URLs, remote schemes. */
102 const isForeignSpecifier = (specifier: string) =>
103 /^(?:node:|data:|[a-z][a-z\d+.-]*:\/\/)/i.test(specifier) && !specifier.startsWith("file:");
104
105 /**
106 * tsx-compatible resolution. Oxc's resolver handles project code the way
107 * TypeScript does (tsconfig `paths`, `.js` → `.ts` substitution,
108 * extensionless and directory imports); a file it finds is final, as in
109 * nub, rather than handed back to Node to resolve a second time. Packages
110 * and everything Oxc cannot place stay with Node, which also reports the
111 * canonical errors. The format is left to the load step.
112 */
113 const resolveSpecifier = (
114 resolver: SpecifierResolver,
115 specifier: string,
116 context: ResolveHookContext,
117 nextResolve: NextResolve,
118 ): ResolveFnOutput => {
119 if (isForeignSpecifier(specifier)) return nextResolve(specifier, context);
120
121 const parentPath = filePathOfUrl(context.parentURL);
122 const { specifier: clean, metadata } = splitSpecifierMetadata(specifier);
123
124 // TypeScript's rules apply to project code. Dependencies keep Node's plain
125 // resolution so published packages behave exactly as they would without us.
126 if (parentPath !== undefined && isProjectPath(parentPath)) {
127 const candidate = resolver.resolve(parentPath, clean, context.conditions);
128 if (candidate !== undefined) {
129 return { url: pathToFileURL(candidate).href + metadata, shortCircuit: true };
130 }
131 }
132
133 return nextResolve(specifier, context);
134 };
135
136 /**
137 * Key for memoizing a resolution, or `undefined` when it must not be. Inside
138 * `node_modules` the result of resolving a specifier depends on the
139 * importing module's directory, not the module itself (package scope,
140 * node_modules lookup and relative paths are all per directory), and on the
141 * conditions; a graph of thousands of modules repeats the same handful of
142 * specifiers per directory, so each is resolved once. Project files are
143 * keyed individually: a solution-style tsconfig can assign two files of one
144 * directory to different referenced projects with different `paths`.
145 */
146 const resolutionKey = (specifier: string, context: ResolveHookContext) => {
147 const { parentURL } = context;
148 if (parentURL === undefined || isForeignSpecifier(specifier)) return undefined;
149 const queryIndex = parentURL.search(/[?#]/);
150 const parent = queryIndex === -1 ? parentURL : parentURL.slice(0, queryIndex);
151 const scope = parent.includes("/node_modules/")
152 ? parent.slice(0, parent.lastIndexOf("/") + 1)
153 : parent;
154 return `${scope}\0${specifier}\0${context.conditions.join(",")}`;
155 };
156
157 /**
158 * `import data from "./x.json"` without an import attribute is how
159 * TypeScript projects import JSON (`resolveJsonModule`); Node insists on
160 * `with { type: "json" }` for ESM. Supply it, as tsx does.
161 */
162 const withJsonAttribute = (url: string, context: LoadHookContext) => {
163 if (!/\.json(?:[?#]|$)/.test(url) || context.importAttributes?.type) {
164 return context;
165 }
166 return {
167 ...context,
168 importAttributes: { ...context.importAttributes, type: "json" },
169 };
170 };
171
172 /**
173 * `import text from "./x.txt" with { type: "text" }` — the TC39 Import Text
174 * proposal (stage 3), which Bun and Deno already implement. The module's
175 * default export is the file decoded as UTF-8 exactly as `TextDecoder`
176 * does it (BOM stripped, invalid sequences replaced). Node keys its module
177 * map by attributes too, so the same file imported as text and as code are
178 * two modules.
179 */
180 const textModule = (filePath: string): LoadFnOutput => ({
181 format: "module",
182 source: `export default ${JSON.stringify(new TextDecoder().decode(readFileSync(filePath)))};`,
183 shortCircuit: true,
184 });
185
186 /**
187 * The loader itself: synchronous `resolve` and `load` hooks that transpile
188 * TypeScript with Rolldown's Oxc transformer and resolve it the way
189 * TypeScript (and tsx) does. Register them process-wide with
190 * `registerOxc` (./register.ts), or scoped to one import graph through
191 * `namespaced` (./namespace.ts). Each call creates its own resolver,
192 * transformer and resolution memo.
193 */
194 export const createHooks = (options: LoaderOptions = {}): LoaderHooks => {
195 const transformer = new SourceTransformer(options);
196 const resolver = new SpecifierResolver({ tsconfig: options.tsconfig ?? true });
197 const resolutions = new Map<string, ResolveFnOutput>();
198 const conditions = options.conditions ?? [];
199
200 return {
201 resolve(specifier, context, nextResolve) {
202 if (conditions.length > 0) {
203 context = { ...context, conditions: [...new Set([...conditions, ...context.conditions])] };
204 }
205 const key = resolutionKey(specifier, context);
206 const memoized = key === undefined ? undefined : resolutions.get(key);
207 if (memoized !== undefined) return memoized;
208 const resolved = resolveSpecifier(resolver, specifier, context, nextResolve);
209 // A memoized result skips the rest of the hook chain, which Node only
210 // accepts when it says so.
211 if (key !== undefined) resolutions.set(key, { ...resolved, shortCircuit: true });
212 return resolved;
213 },
214
215 load(url, context, nextLoad) {
216 scheduleCompileCacheFlush();
217 const filePath = filePathOfUrl(url);
218 if (filePath === undefined) return nextLoad(url, context);
219
220 // An attribute, not a transpile: applies to any file, filtered or not.
221 if (context.importAttributes?.type === "text") return textModule(filePath);
222
223 if (options.filter !== undefined && !options.filter(filePath)) {
224 return nextLoad(url, withJsonAttribute(url, context));
225 }
226 const transformed = transformer.transform(filePath, context.format);
227 if (transformed === undefined) return nextLoad(url, withJsonAttribute(url, context));
228
229 // `importAttributes` is present on every import and absent on require().
230 if (
231 importedCommonJsNeedsNodeLoader &&
232 transformed.format === "commonjs" &&
233 context.importAttributes !== undefined
234 ) {
235 return nextLoad(url, { ...context, format: "commonjs" });
236 }
237 return { ...transformed, shortCircuit: true };
238 },
239 };
240 };