-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.ts
195 lines (179 loc) · 5.16 KB
/
eval.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { Module } from "node:module";
import { performance } from "node:perf_hooks";
import vm from "node:vm";
import { dirname, basename, extname } from "pathe";
import { hasESMSyntax } from "mlly";
import {
debug,
jitiInteropDefault,
readNearestPackageJSON,
wrapModule,
} from "./utils";
import type { ModuleCache, Context, EvalModuleOptions } from "./types";
import { jitiResolve } from "./resolve";
import { jitiRequire, nativeImportOrRequire } from "./require";
import createJiti from "./jiti";
import { transform } from "./transform";
export function evalModule(
ctx: Context,
source: string,
evalOptions: EvalModuleOptions = {},
) {
// Resolve options
const id =
evalOptions.id ||
(evalOptions.filename
? basename(evalOptions.filename)
: `_jitiEval.${evalOptions.ext || (evalOptions.async ? "mjs" : "js")}`);
const filename =
evalOptions.filename || jitiResolve(ctx, id, { async: evalOptions.async });
const ext = evalOptions.ext || extname(filename);
const cache = (evalOptions.cache || ctx.parentCache || {}) as ModuleCache;
// Transpile
const isTypescript = /\.[cm]?tsx?$/.test(ext);
const isESM =
ext === ".mjs" ||
(ext === ".js" && readNearestPackageJSON(filename)?.type === "module");
const isCommonJS = ext === ".cjs";
const needsTranspile =
!isCommonJS && // CommonJS skips transpile
!(isESM && evalOptions.async) && // In async mode, we can skip native ESM as well
(isTypescript ||
isESM ||
ctx.isTransformRe.test(filename) ||
hasESMSyntax(source));
const start = performance.now();
if (needsTranspile) {
source = transform(ctx, {
filename,
source,
ts: isTypescript,
async: evalOptions.async ?? false,
jsx: ctx.opts.jsx,
});
const time = Math.round((performance.now() - start) * 1000) / 1000;
debug(
ctx,
"[transpile]",
evalOptions.async ? "[esm]" : "[cjs]",
filename,
`(${time}ms)`,
);
} else {
try {
debug(
ctx,
"[native]",
evalOptions.async ? "[import]" : "[require]",
filename,
);
return nativeImportOrRequire(ctx, filename, evalOptions.async);
} catch (error: any) {
debug(ctx, "Native require error:", error);
debug(ctx, "[fallback]", filename);
source = transform(ctx, {
filename,
source,
ts: isTypescript,
async: evalOptions.async ?? false,
jsx: ctx.opts.jsx,
});
}
}
// Compile module
const mod = new Module(filename);
mod.filename = filename;
if (ctx.parentModule) {
mod.parent = ctx.parentModule;
if (
Array.isArray(ctx.parentModule.children) &&
!ctx.parentModule.children.includes(mod)
) {
ctx.parentModule.children.push(mod);
}
}
const _jiti = createJiti(
filename,
ctx.opts,
{
parentModule: mod,
parentCache: cache,
nativeImport: ctx.nativeImport,
onError: ctx.onError,
createRequire: ctx.createRequire,
},
true /* isNested */,
);
mod.require = _jiti;
// @ts-ignore
mod.path = dirname(filename);
// @ts-ignore
mod.paths = Module._nodeModulePaths(mod.path);
// Set CJS cache before eval
cache[filename] = mod;
if (ctx.opts.moduleCache) {
ctx.nativeRequire.cache[filename] = mod;
}
// Compile wrapped script
let compiled;
const wrapped = wrapModule(source, { async: evalOptions.async });
try {
compiled = vm.runInThisContext(wrapped, {
filename,
lineOffset: 0,
displayErrors: false,
});
} catch (error: any) {
if (error.name === "SyntaxError" && evalOptions.async && ctx.nativeImport) {
// Support cases such as import.meta.[custom]
debug(ctx, "[esm]", "[import]", "[fallback]", filename);
compiled = esmEval(wrapped, ctx.nativeImport!);
} else {
if (ctx.opts.moduleCache) {
delete ctx.nativeRequire.cache[filename];
}
ctx.onError!(error);
}
}
// Evaluate module
let evalResult;
try {
evalResult = compiled(
mod.exports,
mod.require,
mod,
mod.filename,
dirname(mod.filename),
_jiti.import,
_jiti.esmResolve,
);
} catch (error: any) {
if (ctx.opts.moduleCache) {
delete ctx.nativeRequire.cache[filename];
}
ctx.onError!(error);
}
function next() {
// Check for parse errors
if (mod.exports && mod.exports.__JITI_ERROR__) {
const { filename, line, column, code, message } =
mod.exports.__JITI_ERROR__;
const loc = `${filename}:${line}:${column}`;
const err = new Error(`${code}: ${message} \n ${loc}`);
Error.captureStackTrace(err, jitiRequire);
ctx.onError!(err);
}
// Set as loaded
mod.loaded = true;
// interopDefault
const _exports = jitiInteropDefault(ctx, mod.exports);
// Return exports
return _exports;
}
return evalOptions.async ? Promise.resolve(evalResult).then(next) : next();
}
function esmEval(code: string, nativeImport: (id: string) => Promise<any>) {
const uri = `data:text/javascript;base64,${Buffer.from(`export default ${code}`).toString("base64")}`;
return (...args: any[]) =>
nativeImport(uri).then((mod) => mod.default(...args));
}