@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 102 lines 4.04 KB
Raw
1 import { randomUUID } from "node:crypto";
2 // A namespace import: Bun has no `registerHooks`, and a named import of a
3 // missing builtin export is a SyntaxError at load time, not at call time.
4 import * as NodeModule from "node:module";
5 import { fileURLToPath } from "node:url";
6 import type { LoaderOptions } from "../loader/hooks.ts";
7 import type { NamespaceOptions } from "../loader/namespace.ts";
8 import { DependencyWatcher, type DependencyWatcherOptions } from "./dependency-watcher.ts";
9
10 export interface ImportGeneration<T> {
11 readonly value: T;
12 readonly namespace: string;
13 readonly dependencies: ReadonlySet<string>;
14 }
15
16 export interface ImportWatcherOptions
17 extends LoaderOptions, DependencyWatcherOptions, Pick<NamespaceOptions, "shouldInvalidate"> {
18 readonly parentURL: string;
19 }
20
21 /**
22 * Imports fresh generations of one module graph and watches exactly the
23 * files the current generation loaded. Each generation registers the Oxc
24 * loader hooks under a new namespace (see ../loader/namespace.ts), so Node
25 * evaluates the same files again as new modules; the previous generation's
26 * hooks are deregistered once the new one is in.
27 *
28 * CommonJS members of the graph live in Node's path-keyed `require` cache,
29 * which no namespace reaches; a new generation evicts the previous one's
30 * files from it so they are evaluated again too.
31 *
32 * Bun callers use `BunImportTracker` (./bun-import-tracker.ts): Bun cannot
33 * evict evaluated modules, so a change there restarts the process instead.
34 */
35 export class ImportWatcher<T = unknown> extends DependencyWatcher {
36 readonly #specifier: string;
37 readonly #options: ImportWatcherOptions;
38 readonly #require = NodeModule.createRequire(import.meta.url);
39 #registration: ReturnType<typeof NodeModule.registerHooks> | undefined;
40 #releaseSourceMaps: (() => void) | undefined;
41 #closed = false;
42
43 constructor(specifier: string, options: ImportWatcherOptions) {
44 super(options);
45 this.#specifier = specifier;
46 this.#options = options;
47 }
48
49 async import(): Promise<ImportGeneration<T>> {
50 if (this.#closed) throw new Error("ImportWatcher is closed");
51 // Loaded here, not at module scope: the exec child imports this file on
52 // both runtimes, and the loader's Node hooks do not exist under Bun.
53 const [{ createHooks }, { importNamespaced, namespaced }, { leaseSourceMapSupport }] =
54 await Promise.all([
55 import("../loader/hooks.ts"),
56 import("../loader/namespace.ts"),
57 import("../loader/source-map.ts"),
58 ]);
59 this.#releaseSourceMaps ??= leaseSourceMapSupport();
60 for (const file of this.dependencies) delete this.#require.cache[file];
61 const namespace = randomUUID();
62 const dependencies = new Set<string>();
63 let current = false;
64 const registration = NodeModule.registerHooks(
65 namespaced(createHooks(this.#options), {
66 namespace,
67 shouldInvalidate: this.#options.shouldInvalidate,
68 onImport: (url) => {
69 dependencies.add(fileURLToPath(url));
70 // A lazy import evaluated after this generation became current
71 // extends the watched set immediately.
72 if (current) this.set(new Set(dependencies));
73 },
74 }),
75 );
76 try {
77 const value = await importNamespaced<T>(this.#specifier, this.#options.parentURL, namespace);
78 this.#registration?.deregister();
79 this.#registration = registration;
80 current = true;
81 this.set(new Set(dependencies));
82 return { value, namespace, dependencies };
83 } catch (error) {
84 registration.deregister();
85 // Keep watching everything the failed import touched so the next save
86 // of any of those files retries.
87 this.set(new Set([...this.dependencies, ...dependencies]));
88 throw error;
89 }
90 }
91
92 override async close(): Promise<void> {
93 if (this.#closed) return;
94 this.#closed = true;
95 this.#registration?.deregister();
96 this.#releaseSourceMaps?.();
97 await super.close();
98 }
99 }
100
101 export const watchImport = <T = unknown>(specifier: string, options: ImportWatcherOptions) =>
102 new ImportWatcher<T>(specifier, options);