-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtransform-loader.ts
44 lines (38 loc) · 1.21 KB
/
transform-loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import type { LoadFnOutput, LoadHookContext } from "node:module";
import type { Options } from "../lib/wasm";
import { transformSync } from "./index.js";
type NextLoad = (
url: string,
context?: LoadHookContext,
) => LoadFnOutput | Promise<LoadFnOutput>;
export async function load(
url: string,
context: LoadHookContext,
nextLoad: NextLoad,
) {
const { format } = context;
if (format.endsWith("-typescript")) {
// Use format 'module' so it returns the source as-is, without stripping the types.
// Format 'commonjs' would not return the source for historical reasons.
const { source } = await nextLoad(url, {
...context,
format: "module",
});
// biome-ignore lint/style/noNonNullAssertion: If module exists, it will have a source
const { code, map } = transformSync(source!.toString(), {
mode: "transform",
sourceMap: true,
filename: url,
} as Options);
let output = code;
if (map) {
const base64SourceMap = Buffer.from(map).toString("base64");
output = `${code}\n\n//# sourceMappingURL=data:application/json;base64,${base64SourceMap}`;
}
return {
format: format.replace("-typescript", ""),
source: `${output}\n\n//# sourceURL=${url}`,
};
}
return nextLoad(url, context);
}