Skip to content

Commit

Permalink
fix(eval): fallback in async mode (#325)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Oct 7, 2024
1 parent c469748 commit 650cc6c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 23 deletions.
1 change: 1 addition & 0 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export type EvalModuleOptions = Partial<{
ext: string;
cache: ModuleCache;
async: boolean;
forceTranspile: boolean;
}>;

export interface TransformOptions {
Expand Down
56 changes: 33 additions & 23 deletions src/eval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ export function evalModule(
(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));
evalOptions.forceTranspile ??
(!isCommonJS && // CommonJS skips transpile
!(isESM && evalOptions.async) && // In async mode, we can skip native ESM as well
// prettier-ignore
(isTypescript || isESM || ctx.isTransformRe.test(filename) || hasESMSyntax(source)));
const start = performance.now();
if (needsTranspile) {
source = transform(ctx, {
Expand All @@ -62,24 +61,35 @@ export function evalModule(
`(${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,
debug(
ctx,
"[native]",
evalOptions.async ? "[import]" : "[require]",
filename,
);

if (evalOptions.async) {
return Promise.resolve(
nativeImportOrRequire(ctx, filename, evalOptions.async),
).catch((error: any) => {
debug(ctx, "Native import error:", error);
debug(ctx, "[fallback]", filename);
evalModule(ctx, source, { ...evalOptions, forceTranspile: true });
});
} else {
try {
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,
});
}
}
}

Expand Down

0 comments on commit 650cc6c

Please # to comment.