Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

register.ts

42 lines1.6 KB

1import * as NodeModule from "node:module";
2import { createHooks, type LoaderOptions } from "./hooks.ts";
3import { leaseSourceMapSupport } from "./source-map.ts";
4​
5export { createHooks, type LoaderHooks, type LoaderOptions } from "./hooks.ts";
6export { importNamespaced, namespaced, type NamespaceOptions } from "./namespace.ts";
7​
8export interface OxcLoader {
9 unregister(): void;
11​
12const registrationKey = Symbol.for("@alchemy.run/node-utils/register-oxc");
13​
14/**
15 * Installs the Oxc TypeScript loader process-wide. Alchemy starts every
16 * Node process with `--import` of a file that calls this; in-process
17 * callers (the dev exec child, tests) may call it again and get the same
18 * registration back — a second copy of the hooks would only re-run the
19 * chain. The marker lives on `globalThis` because a checkout can load this
20 * module twice (src/ and lib/).
21 *
22 * Reloading one import graph in place is `watchImport` (../watch), which
23 * layers a namespace over the same hooks.
24 */
25export const registerOxc = (options: LoaderOptions = {}): OxcLoader => {
26 const registrations = globalThis as typeof globalThis & { [registrationKey]?: OxcLoader };
27 const existing = registrations[registrationKey];
28 if (existing !== undefined) return existing;
29​
30 const releaseSourceMaps = leaseSourceMapSupport();
31 const hooks = NodeModule.registerHooks(createHooks(options));
32​
33 const loader: OxcLoader = {
34 unregister() {
35 hooks.deregister();
36 if (registrations[registrationKey] === loader) delete registrations[registrationKey];
37 releaseSourceMaps();
38 },
39 };
40 registrations[registrationKey] = loader;
41 return loader;
42};