This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
loader.mjs
78 lines (74 loc) · 2.12 KB
/
loader.mjs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const {
process: { stdout },
Error,
undefined,
parseInt,
Reflect: { getOwnPropertyDescriptor },
Object: {
hasOwn = (object, key) =>
getOwnPropertyDescriptor(object, key) !== undefined,
},
} = globalThis;
const parseMajorVersion = (version) => {
const parts = /^v([0-9]+)\./u.exec(version);
if (parts === null) {
throw new Error("could not parse node version");
} else {
return parseInt(parts[1]);
}
};
let is_main = true;
const message =
"Treating main file as commonjs, this might not always be appropriate -- cf: https://github.com/nodejs/node/issues/41465\n";
export default (node_version, esm_hook_variable) => {
const major_node_version = parseMajorVersion(node_version);
return {
getFormat:
major_node_version >= 16
? undefined
: (url, context, next) => {
if (is_main) {
is_main = false;
try {
return next(url, context, next);
} catch {
stdout.write(message);
return { format: "commonjs" };
}
} else {
return next(url, context, next);
}
},
transformSource:
major_node_version >= 16
? undefined
: (content, context, next) => {
if (hasOwn(globalThis, esm_hook_variable)) {
return globalThis[esm_hook_variable].transformSource(
content,
context,
next,
);
} else {
return next(content, context, next);
}
},
load:
major_node_version < 16
? undefined
: (url, context, next) => {
if (is_main) {
is_main = false;
if (context.format === undefined) {
stdout.write(message);
context.format = "commonjs";
}
}
if (hasOwn(globalThis, esm_hook_variable)) {
return globalThis[esm_hook_variable].load(url, context, next);
} else {
return next(url, context, next);
}
},
};
};