@alchemy.run/node-utils 2.0.0-beta.76 → 2.0.0-beta.77
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD_PARTY_LICENSES.md +11 -11
- package/lib/dependency-watcher.d.ts +28 -0
- package/lib/dependency-watcher.d.ts.map +1 -0
- package/lib/dependency-watcher.js +114 -0
- package/lib/dependency-watcher.js.map +1 -0
- package/lib/import-loader.d.ts +54 -0
- package/lib/import-loader.d.ts.map +1 -0
- package/lib/import-loader.js +9 -0
- package/lib/import-loader.js.map +1 -0
- package/lib/register-oxc.d.ts +16 -0
- package/lib/register-oxc.d.ts.map +1 -0
- package/lib/register-oxc.js +257 -0
- package/lib/register-oxc.js.map +1 -0
- package/lib/resolve-specifier.d.ts +52 -0
- package/lib/resolve-specifier.d.ts.map +1 -0
- package/lib/resolve-specifier.js +139 -0
- package/lib/resolve-specifier.js.map +1 -0
- package/lib/transform-source.d.ts +19 -0
- package/lib/transform-source.d.ts.map +1 -0
- package/lib/transform-source.js +140 -0
- package/lib/transform-source.js.map +1 -0
- package/lib/watch-import-bun.d.ts +30 -0
- package/lib/watch-import-bun.d.ts.map +1 -0
- package/lib/watch-import-bun.js +68 -0
- package/lib/watch-import-bun.js.map +1 -0
- package/lib/watch-import.d.ts +27 -0
- package/lib/watch-import.d.ts.map +1 -0
- package/lib/watch-import.js +77 -0
- package/lib/watch-import.js.map +1 -0
- package/package.json +26 -2
- package/src/dependency-watcher.ts +130 -0
- package/src/import-loader.ts +75 -0
- package/src/register-oxc.ts +342 -0
- package/src/resolve-specifier.ts +179 -0
- package/src/transform-source.ts +170 -0
- package/src/watch-import-bun.ts +94 -0
- package/src/watch-import.ts +107 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { watch, type ChokidarOptions, type FSWatcher } from "chokidar";
|
|
5
|
+
|
|
6
|
+
export interface DependencyChange {
|
|
7
|
+
readonly paths: ReadonlySet<string>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type DependencyChangeListener = (change: DependencyChange) => void;
|
|
11
|
+
|
|
12
|
+
export interface DependencyWatcherOptions {
|
|
13
|
+
/** Chokidar options passed to the file watcher. */
|
|
14
|
+
readonly watch?: ChokidarOptions | undefined;
|
|
15
|
+
readonly debounceMs?: number | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Watches an explicit set of absolute file paths and delivers debounced
|
|
20
|
+
* batches only when their contents change. Chokidar follows editor atomic-save
|
|
21
|
+
* replacements without polling by default. The set is replaced wholesale
|
|
22
|
+
* with {@link set}, so the watcher always mirrors exactly the files the caller
|
|
23
|
+
* currently depends on.
|
|
24
|
+
*/
|
|
25
|
+
export class DependencyWatcher {
|
|
26
|
+
readonly #options: DependencyWatcherOptions;
|
|
27
|
+
readonly #listeners = new Set<DependencyChangeListener>();
|
|
28
|
+
readonly #watcher: FSWatcher;
|
|
29
|
+
#dependencies: ReadonlySet<string> = new Set();
|
|
30
|
+
#fingerprints = new Map<string, string | undefined>();
|
|
31
|
+
#pending = new Set<string>();
|
|
32
|
+
#timer: NodeJS.Timeout | undefined;
|
|
33
|
+
#closed = false;
|
|
34
|
+
|
|
35
|
+
constructor(options: DependencyWatcherOptions = {}) {
|
|
36
|
+
this.#options = options;
|
|
37
|
+
this.#watcher = watch([], {
|
|
38
|
+
...options.watch,
|
|
39
|
+
ignoreInitial: true,
|
|
40
|
+
});
|
|
41
|
+
this.#watcher.on("all", (_event, changed) => {
|
|
42
|
+
const absolute = path.resolve(this.#cwd(), changed);
|
|
43
|
+
if (this.#dependencies.has(absolute)) this.#queue(absolute);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get dependencies(): ReadonlySet<string> {
|
|
48
|
+
return this.#dependencies;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
subscribe(listener: DependencyChangeListener): () => void {
|
|
52
|
+
this.#listeners.add(listener);
|
|
53
|
+
return () => this.#listeners.delete(listener);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Replace the watched set with `dependencies` (absolute paths). */
|
|
57
|
+
set(dependencies: ReadonlySet<string>): void {
|
|
58
|
+
if (this.#closed) return;
|
|
59
|
+
const previous = this.#dependencies;
|
|
60
|
+
this.#dependencies = dependencies;
|
|
61
|
+
const removed = [...previous].filter(
|
|
62
|
+
(dependency) => !dependencies.has(dependency),
|
|
63
|
+
);
|
|
64
|
+
const added = [...dependencies].filter(
|
|
65
|
+
(dependency) => !previous.has(dependency),
|
|
66
|
+
);
|
|
67
|
+
if (removed.length > 0) {
|
|
68
|
+
for (const dependency of removed) {
|
|
69
|
+
this.#fingerprints.delete(dependency);
|
|
70
|
+
this.#pending.delete(dependency);
|
|
71
|
+
}
|
|
72
|
+
void this.#watcher.unwatch(removed);
|
|
73
|
+
}
|
|
74
|
+
if (added.length > 0) {
|
|
75
|
+
for (const dependency of added) {
|
|
76
|
+
this.#fingerprints.set(dependency, this.#fingerprint(dependency));
|
|
77
|
+
}
|
|
78
|
+
this.#watcher.add(added);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async close(): Promise<void> {
|
|
83
|
+
if (this.#closed) return;
|
|
84
|
+
this.#closed = true;
|
|
85
|
+
if (this.#timer !== undefined) clearTimeout(this.#timer);
|
|
86
|
+
await this.#watcher.close();
|
|
87
|
+
this.#listeners.clear();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
91
|
+
await this.close();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#cwd(): string {
|
|
95
|
+
return this.#options.watch?.cwd ?? process.cwd();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
#queue(changed: string): void {
|
|
99
|
+
this.#pending.add(changed);
|
|
100
|
+
if (this.#timer !== undefined) clearTimeout(this.#timer);
|
|
101
|
+
this.#timer = setTimeout(() => {
|
|
102
|
+
this.#timer = undefined;
|
|
103
|
+
const pending = this.#pending;
|
|
104
|
+
this.#pending = new Set();
|
|
105
|
+
const paths = new Set<string>();
|
|
106
|
+
for (const dependency of pending) {
|
|
107
|
+
const previous = this.#fingerprints.get(dependency);
|
|
108
|
+
const current = this.#fingerprint(dependency);
|
|
109
|
+
if (current === previous) continue;
|
|
110
|
+
this.#fingerprints.set(dependency, current);
|
|
111
|
+
paths.add(dependency);
|
|
112
|
+
}
|
|
113
|
+
if (paths.size === 0) return;
|
|
114
|
+
for (const listener of this.#listeners) listener({ paths });
|
|
115
|
+
}, this.#options.debounceMs ?? 50);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
#fingerprint(file: string): string | undefined {
|
|
119
|
+
try {
|
|
120
|
+
return createHash("sha256")
|
|
121
|
+
.update(readFileSync(file))
|
|
122
|
+
.digest("base64url");
|
|
123
|
+
} catch {
|
|
124
|
+
// Missing and unreadable are both materially different from the last
|
|
125
|
+
// successfully read contents, while repeated missing-file events fold
|
|
126
|
+
// onto the same value.
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { TransformOptions } from "rolldown/utils";
|
|
2
|
+
|
|
3
|
+
export interface TransformContext {
|
|
4
|
+
readonly url: string;
|
|
5
|
+
readonly path: string;
|
|
6
|
+
readonly format: "module" | "commonjs";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface SourceTransformResult {
|
|
10
|
+
readonly code: string;
|
|
11
|
+
readonly map?: string | object | undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type SourceTransform = (
|
|
15
|
+
code: string,
|
|
16
|
+
context: TransformContext,
|
|
17
|
+
) => string | SourceTransformResult | undefined;
|
|
18
|
+
|
|
19
|
+
export interface ImportLoaderOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Additional package export conditions used during module resolution.
|
|
22
|
+
* They are made available alongside Node's ambient conditions to both the
|
|
23
|
+
* TypeScript-aware resolver and Node's package exports resolver.
|
|
24
|
+
*/
|
|
25
|
+
readonly conditions?: ReadonlyArray<string> | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Oxc transform configuration, layered over the nearest `tsconfig.json`
|
|
28
|
+
* of each transformed file (`jsx`, decorators, …).
|
|
29
|
+
*/
|
|
30
|
+
readonly transform?: TransformOptions | undefined;
|
|
31
|
+
/** Additional synchronous source transforms, applied after Oxc. */
|
|
32
|
+
readonly transforms?: ReadonlyArray<SourceTransform> | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Honour `tsconfig.json` discovered upward from each file: compiler
|
|
35
|
+
* options for the transform, `paths`/`baseUrl` aliases for resolution.
|
|
36
|
+
* @default true
|
|
37
|
+
*/
|
|
38
|
+
readonly tsconfig?: boolean | undefined;
|
|
39
|
+
/** Controls which file URLs belong to the fresh import graph. */
|
|
40
|
+
readonly shouldInvalidate?:
|
|
41
|
+
| ((url: string, parentURL: string | undefined) => boolean)
|
|
42
|
+
| undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Limits transformation to matching absolute file paths; everything else
|
|
45
|
+
* loads through Node untouched. Lets a published install transpile only
|
|
46
|
+
* the user's own TypeScript while alchemy and its dependencies run their
|
|
47
|
+
* built JavaScript.
|
|
48
|
+
*/
|
|
49
|
+
readonly filter?: ((path: string) => boolean) | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ImportLoaderRegistrationOptions extends ImportLoaderOptions {
|
|
53
|
+
/** Isolates one import graph in the runtime's module cache. */
|
|
54
|
+
readonly namespace?: string | undefined;
|
|
55
|
+
/** Called once the runtime loads a file in this registration's graph. */
|
|
56
|
+
readonly onImport?: ((url: string) => void) | undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ImportLoader {
|
|
60
|
+
import<T = unknown>(specifier: string, parentURL: string): Promise<T>;
|
|
61
|
+
unregister(): void | Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Creates a Node import loader using synchronous module hooks backed by Oxc. */
|
|
65
|
+
export const createImportLoader = async (
|
|
66
|
+
options: ImportLoaderRegistrationOptions = {},
|
|
67
|
+
): Promise<ImportLoader> => {
|
|
68
|
+
if (process.versions.bun !== undefined) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
"The import-aware loader is only available in Node; use Bun's process-level watcher instead.",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
const { registerOxc } = await import("./register-oxc.ts");
|
|
74
|
+
return registerOxc(options);
|
|
75
|
+
};
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
registerHooks,
|
|
4
|
+
type LoadFnOutput,
|
|
5
|
+
type LoadHookContext,
|
|
6
|
+
type ResolveFnOutput,
|
|
7
|
+
type ResolveHookContext,
|
|
8
|
+
} from "node:module";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import type {
|
|
11
|
+
ImportLoader,
|
|
12
|
+
ImportLoaderRegistrationOptions,
|
|
13
|
+
} from "./import-loader.ts";
|
|
14
|
+
import {
|
|
15
|
+
filePathOfUrl,
|
|
16
|
+
isFileLikeSpecifier,
|
|
17
|
+
isProjectPath,
|
|
18
|
+
SpecifierResolver,
|
|
19
|
+
splitSpecifierMetadata,
|
|
20
|
+
} from "./resolve-specifier.ts";
|
|
21
|
+
import { SourceTransformer } from "./transform-source.ts";
|
|
22
|
+
|
|
23
|
+
export type {
|
|
24
|
+
ImportLoader as RegisteredOxcImporter,
|
|
25
|
+
ImportLoaderRegistrationOptions as RegisterOxcOptions,
|
|
26
|
+
SourceTransform,
|
|
27
|
+
SourceTransformResult,
|
|
28
|
+
TransformContext,
|
|
29
|
+
} from "./import-loader.ts";
|
|
30
|
+
|
|
31
|
+
const protocol = "alchemy-import:";
|
|
32
|
+
const namespaceParameter = "alchemy-import-namespace";
|
|
33
|
+
const globalRegistrationKey = Symbol.for(
|
|
34
|
+
"@alchemy.run/node-utils/register-oxc",
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
interface ImportRequest {
|
|
38
|
+
readonly namespace?: string | undefined;
|
|
39
|
+
readonly parentURL: string;
|
|
40
|
+
readonly specifier: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type NextResolve = (
|
|
44
|
+
specifier: string,
|
|
45
|
+
context?: Partial<ResolveHookContext>,
|
|
46
|
+
) => ResolveFnOutput;
|
|
47
|
+
|
|
48
|
+
const namespaceOf = (url: string | undefined) => {
|
|
49
|
+
if (url === undefined || !url.startsWith("file:")) return undefined;
|
|
50
|
+
return new URL(url).searchParams.get(namespaceParameter) ?? undefined;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const withoutNamespace = (url: string) => {
|
|
54
|
+
if (!url.startsWith("file:")) return url;
|
|
55
|
+
const parsed = new URL(url);
|
|
56
|
+
parsed.searchParams.delete(namespaceParameter);
|
|
57
|
+
return parsed.href;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const withNamespace = (url: string, namespace: string) => {
|
|
61
|
+
const parsed = new URL(url);
|
|
62
|
+
parsed.searchParams.set(namespaceParameter, namespace);
|
|
63
|
+
return parsed.href;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const parseRequest = (specifier: string): ImportRequest | undefined => {
|
|
67
|
+
if (!specifier.startsWith(protocol)) return undefined;
|
|
68
|
+
return JSON.parse(decodeURIComponent(specifier.slice(protocol.length)));
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Specifiers Node owns outright: builtins, data URLs, remote schemes. */
|
|
72
|
+
const isForeignSpecifier = (specifier: string) =>
|
|
73
|
+
/^(?:node:|data:|[a-z][a-z\d+.-]*:\/\/)/i.test(specifier) &&
|
|
74
|
+
!specifier.startsWith("file:");
|
|
75
|
+
|
|
76
|
+
const notFoundCodes = new Set([
|
|
77
|
+
"ERR_MODULE_NOT_FOUND",
|
|
78
|
+
"MODULE_NOT_FOUND",
|
|
79
|
+
"ERR_UNSUPPORTED_DIR_IMPORT",
|
|
80
|
+
"ERR_PACKAGE_PATH_NOT_EXPORTED",
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
const isNotFound = (error: unknown): error is Error & { url?: string } =>
|
|
84
|
+
error instanceof Error &&
|
|
85
|
+
notFoundCodes.has((error as { code?: string }).code ?? "");
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The file Node could not find, from the error it raised. Node names the
|
|
89
|
+
* resolved target (`url` on ESM errors, the message on CommonJS ones) —
|
|
90
|
+
* for a package `exports` entry pointing at emitted JavaScript that was
|
|
91
|
+
* never built, that is the `.js` path whose `.ts` source we can substitute.
|
|
92
|
+
*/
|
|
93
|
+
const missingPathOf = (error: Error & { url?: string }) => {
|
|
94
|
+
if (error.url !== undefined) return filePathOfUrl(error.url);
|
|
95
|
+
const match = error.message.match(/^Cannot find module '([^']+)'/);
|
|
96
|
+
if (match === null) return undefined;
|
|
97
|
+
const [, target] = match;
|
|
98
|
+
if (target === undefined) return undefined;
|
|
99
|
+
if (target.startsWith("file:")) return filePathOfUrl(target);
|
|
100
|
+
return target.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(target)
|
|
101
|
+
? target
|
|
102
|
+
: undefined;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** A `require()` reaching the hooks: Node's CommonJS resolver wants paths, not URLs. */
|
|
106
|
+
const isRequireContext = (context: ResolveHookContext) =>
|
|
107
|
+
context.conditions?.includes("require") === true &&
|
|
108
|
+
!context.conditions.includes("import");
|
|
109
|
+
|
|
110
|
+
const resolveWithCandidate = (
|
|
111
|
+
candidate: string,
|
|
112
|
+
metadata: string,
|
|
113
|
+
context: ResolveHookContext,
|
|
114
|
+
nextResolve: NextResolve,
|
|
115
|
+
): ResolveFnOutput | undefined => {
|
|
116
|
+
const specifier = isRequireContext(context)
|
|
117
|
+
? candidate + metadata
|
|
118
|
+
: pathToFileURL(candidate).href + metadata;
|
|
119
|
+
try {
|
|
120
|
+
return nextResolve(specifier, context);
|
|
121
|
+
} catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* tsx-compatible resolution. Node's resolver decides in the end; Oxc's
|
|
128
|
+
* resolver supplies the TypeScript-aware candidate (tsconfig `paths`,
|
|
129
|
+
* `.js` → `.ts` substitution, extensionless and directory imports) that
|
|
130
|
+
* Node would not find on its own.
|
|
131
|
+
*/
|
|
132
|
+
const resolveSpecifier = (
|
|
133
|
+
resolver: SpecifierResolver,
|
|
134
|
+
specifier: string,
|
|
135
|
+
context: ResolveHookContext,
|
|
136
|
+
nextResolve: NextResolve,
|
|
137
|
+
): ResolveFnOutput => {
|
|
138
|
+
if (isForeignSpecifier(specifier)) return nextResolve(specifier, context);
|
|
139
|
+
|
|
140
|
+
const parentPath = filePathOfUrl(context.parentURL);
|
|
141
|
+
const { specifier: clean, metadata } = splitSpecifierMetadata(specifier);
|
|
142
|
+
const conditions = context.conditions ?? [];
|
|
143
|
+
|
|
144
|
+
// TypeScript's rules apply to project code. Dependencies keep Node's plain
|
|
145
|
+
// resolution so published packages behave exactly as they would without us.
|
|
146
|
+
if (parentPath !== undefined && isProjectPath(parentPath)) {
|
|
147
|
+
const candidate = resolver.resolve(parentPath, clean, conditions);
|
|
148
|
+
if (candidate !== undefined) {
|
|
149
|
+
const resolved = resolveWithCandidate(
|
|
150
|
+
candidate,
|
|
151
|
+
metadata,
|
|
152
|
+
context,
|
|
153
|
+
nextResolve,
|
|
154
|
+
);
|
|
155
|
+
if (resolved !== undefined) return resolved;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
return nextResolve(specifier, context);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (!isNotFound(error)) throw error;
|
|
163
|
+
// A package `exports`/`main` target naming emitted JavaScript that only
|
|
164
|
+
// exists as TypeScript source (workspace packages in a checkout).
|
|
165
|
+
const missing = missingPathOf(error);
|
|
166
|
+
if (missing !== undefined && isFileLikeSpecifier(missing)) {
|
|
167
|
+
const candidate = resolver.resolveMissing(missing, conditions);
|
|
168
|
+
if (candidate !== undefined && candidate !== missing) {
|
|
169
|
+
const resolved = resolveWithCandidate(
|
|
170
|
+
candidate,
|
|
171
|
+
metadata,
|
|
172
|
+
context,
|
|
173
|
+
nextResolve,
|
|
174
|
+
);
|
|
175
|
+
if (resolved !== undefined) return resolved;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `import data from "./x.json"` without an import attribute is how
|
|
184
|
+
* TypeScript projects import JSON (`resolveJsonModule`); Node insists on
|
|
185
|
+
* `with { type: "json" }` for ESM. Supply it, as tsx does.
|
|
186
|
+
*/
|
|
187
|
+
const withJsonAttribute = (url: string, context: LoadHookContext) => {
|
|
188
|
+
if (!/\.json(?:[?#]|$)/.test(url) || context.importAttributes?.type) {
|
|
189
|
+
return context;
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
...context,
|
|
193
|
+
importAttributes: { ...context.importAttributes, type: "json" },
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Registers synchronous Node module hooks that transpile TypeScript with
|
|
199
|
+
* Rolldown's Oxc transformer and resolve it the way TypeScript (and tsx)
|
|
200
|
+
* does. A namespaced registration also provides a scoped import whose
|
|
201
|
+
* namespace propagates through the complete ESM graph.
|
|
202
|
+
*/
|
|
203
|
+
export const registerOxc = (
|
|
204
|
+
options: ImportLoaderRegistrationOptions = {},
|
|
205
|
+
): ImportLoader => {
|
|
206
|
+
// One global (un-namespaced) registration per process. Alchemy starts every
|
|
207
|
+
// Node process with `--import` of a file that calls this, and in-process
|
|
208
|
+
// callers (the dev exec child, tests) may call it again; a second copy of
|
|
209
|
+
// the hooks would only re-run the resolve chain. The marker lives on
|
|
210
|
+
// globalThis because a checkout can load this module twice (src/ and lib/).
|
|
211
|
+
const globalRegistration = globalThis as typeof globalThis & {
|
|
212
|
+
[globalRegistrationKey]?: ImportLoader;
|
|
213
|
+
};
|
|
214
|
+
if (options.namespace === undefined) {
|
|
215
|
+
const existing = globalRegistration[globalRegistrationKey];
|
|
216
|
+
if (existing !== undefined) return existing;
|
|
217
|
+
}
|
|
218
|
+
const transformer = new SourceTransformer(options);
|
|
219
|
+
const resolver = new SpecifierResolver({
|
|
220
|
+
tsconfig: options.tsconfig ?? true,
|
|
221
|
+
});
|
|
222
|
+
const shouldInvalidate = options.shouldInvalidate ?? (() => true);
|
|
223
|
+
|
|
224
|
+
// Transformed sources carry inline source maps; Node only applies them to
|
|
225
|
+
// stack traces once source-map support is on.
|
|
226
|
+
const sourceMapsWereEnabled = process.sourceMapsEnabled;
|
|
227
|
+
process.setSourceMapsEnabled(true);
|
|
228
|
+
|
|
229
|
+
const hooks = registerHooks({
|
|
230
|
+
resolve(specifier, context, nextResolve) {
|
|
231
|
+
const request = parseRequest(specifier);
|
|
232
|
+
const inheritedNamespace = namespaceOf(context.parentURL);
|
|
233
|
+
const namespace =
|
|
234
|
+
options.namespace === undefined
|
|
235
|
+
? undefined
|
|
236
|
+
: (request?.namespace ?? inheritedNamespace);
|
|
237
|
+
|
|
238
|
+
if (options.namespace !== undefined && namespace !== options.namespace) {
|
|
239
|
+
return nextResolve(specifier, context);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const resolutionContext =
|
|
243
|
+
options.conditions === undefined || options.conditions.length === 0
|
|
244
|
+
? context
|
|
245
|
+
: {
|
|
246
|
+
...context,
|
|
247
|
+
conditions: [
|
|
248
|
+
...new Set([...options.conditions, ...context.conditions]),
|
|
249
|
+
],
|
|
250
|
+
};
|
|
251
|
+
const resolved = request
|
|
252
|
+
? resolveSpecifier(
|
|
253
|
+
resolver,
|
|
254
|
+
request.specifier,
|
|
255
|
+
{ ...resolutionContext, parentURL: request.parentURL },
|
|
256
|
+
nextResolve,
|
|
257
|
+
)
|
|
258
|
+
: resolveSpecifier(resolver, specifier, resolutionContext, nextResolve);
|
|
259
|
+
if (
|
|
260
|
+
namespace !== undefined &&
|
|
261
|
+
resolved.url.startsWith("file:") &&
|
|
262
|
+
shouldInvalidate(
|
|
263
|
+
withoutNamespace(resolved.url),
|
|
264
|
+
context.parentURL === undefined
|
|
265
|
+
? undefined
|
|
266
|
+
: withoutNamespace(context.parentURL),
|
|
267
|
+
)
|
|
268
|
+
) {
|
|
269
|
+
return { ...resolved, url: withNamespace(resolved.url, namespace) };
|
|
270
|
+
}
|
|
271
|
+
return resolved;
|
|
272
|
+
},
|
|
273
|
+
load(url, context, nextLoad): LoadFnOutput {
|
|
274
|
+
const namespace = namespaceOf(url);
|
|
275
|
+
if (options.namespace !== undefined && namespace !== options.namespace) {
|
|
276
|
+
return nextLoad(url, context);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const cleanUrl = withoutNamespace(url);
|
|
280
|
+
const filePath = filePathOfUrl(cleanUrl);
|
|
281
|
+
if (filePath === undefined) return nextLoad(cleanUrl, context);
|
|
282
|
+
options.onImport?.(cleanUrl);
|
|
283
|
+
|
|
284
|
+
if (options.filter !== undefined && !options.filter(filePath)) {
|
|
285
|
+
return nextLoad(cleanUrl, withJsonAttribute(cleanUrl, context));
|
|
286
|
+
}
|
|
287
|
+
const transformed = transformer.transform(
|
|
288
|
+
filePath,
|
|
289
|
+
cleanUrl,
|
|
290
|
+
context.format,
|
|
291
|
+
);
|
|
292
|
+
if (transformed === undefined) {
|
|
293
|
+
return nextLoad(cleanUrl, withJsonAttribute(cleanUrl, context));
|
|
294
|
+
}
|
|
295
|
+
return { ...transformed, shortCircuit: true };
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
const loader: ImportLoader = {
|
|
300
|
+
import<T>(specifier: string, parentURL: string) {
|
|
301
|
+
const request: ImportRequest = {
|
|
302
|
+
namespace: options.namespace,
|
|
303
|
+
parentURL: parentURL.startsWith("file:")
|
|
304
|
+
? parentURL
|
|
305
|
+
: pathToFileURL(parentURL).href,
|
|
306
|
+
specifier,
|
|
307
|
+
};
|
|
308
|
+
return import(
|
|
309
|
+
`${protocol}${encodeURIComponent(JSON.stringify(request))}`
|
|
310
|
+
) as Promise<T>;
|
|
311
|
+
},
|
|
312
|
+
unregister() {
|
|
313
|
+
hooks.deregister();
|
|
314
|
+
if (globalRegistration[globalRegistrationKey] === loader) {
|
|
315
|
+
delete globalRegistration[globalRegistrationKey];
|
|
316
|
+
}
|
|
317
|
+
if (sourceMapsWereEnabled === false) process.setSourceMapsEnabled(false);
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
if (options.namespace === undefined) {
|
|
321
|
+
globalRegistration[globalRegistrationKey] = loader;
|
|
322
|
+
}
|
|
323
|
+
return loader;
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* One-shot TypeScript import that leaves the rest of the runtime untouched:
|
|
328
|
+
* a private namespace is registered for the call, so nothing is shared with
|
|
329
|
+
* other imports of the same files. Mirrors tsx's `tsImport`.
|
|
330
|
+
*/
|
|
331
|
+
export const tsImport = async <T = unknown>(
|
|
332
|
+
specifier: string,
|
|
333
|
+
parentURL: string,
|
|
334
|
+
options: Omit<ImportLoaderRegistrationOptions, "namespace"> = {},
|
|
335
|
+
): Promise<T> => {
|
|
336
|
+
const loader = registerOxc({ ...options, namespace: randomUUID() });
|
|
337
|
+
try {
|
|
338
|
+
return await loader.import<T>(specifier, parentURL);
|
|
339
|
+
} finally {
|
|
340
|
+
await loader.unregister();
|
|
341
|
+
}
|
|
342
|
+
};
|