Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/js/builtins/BunBuiltinNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ using namespace JSC;
macro(validated) \
macro(view) \
macro(vmErrorDecorated) \
macro(vmParseError) \
macro(warning) \
macro(webStreamClosedPromise) \
macro(webStreamControllerError) \
Expand Down
21 changes: 12 additions & 9 deletions src/jsc/bindings/FormatStackTraceForJS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,19 @@ WTF::String formatStackTrace(

String sourceURLForFrame = err->sourceURL();

// If it's not a Zig::GlobalObject, don't bother source-mapping it.
if (globalObject && !sourceURLForFrame.isEmpty()) {
// Tagged by NodeVM::createParseError(): the URL is the filename the caller
// compiled its own string under, so a source map found under that name
// describes some other file. The parser's position stands as is, including
// as err.line (hasSet keeps the frame loop below from replacing it).
if (err->getDirect(vm, builtinNames(vm).vmParseErrorPrivateName())) {
hasSet = true;
} else if (globalObject && !sourceURLForFrame.isEmpty()) {
// https://github.com/oven-sh/bun/issues/3595
if (!sourceURLForFrame.isEmpty()) {
remappedFrame.source_url = Bun::toStringRef(sourceURLForFrame);
// This ensures the lifetime of the sourceURL is accounted for correctly
Bun__remapStackFramePositions(getBunVM(), &remappedFrame, 1);
remappedFrame.source_url = Bun::toStringRef(sourceURLForFrame);
// This ensures the lifetime of the sourceURL is accounted for correctly
Bun__remapStackFramePositions(getBunVM(), &remappedFrame, 1);

sourceURLForFrame = remappedFrame.source_url.toWTFString();
}
sourceURLForFrame = remappedFrame.source_url.toWTFString();
}

// there is always a newline before each stack frame line, ensuring that the name + message
Expand All @@ -210,7 +213,7 @@ WTF::String formatStackTrace(

sb.append(" at <parse> ("_s);

sb.append(remappedFrame.source_url.toWTFString());
sb.append(sourceURLForFrame);

if (remappedFrame.remapped) {
errorInstance->putDirect(vm, builtinNames(vm).originalLinePublicName(), jsNumber(originalLine.oneBasedInt()), PropertyAttribute::DontEnum | 0);
Expand Down
20 changes: 19 additions & 1 deletion src/jsc/bindings/NodeVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ JSC::JSFunction* constructAnonymousFunction(JSC::JSGlobalObject* globalObject, c
}

if (actuallyValid) {
auto exception = error.toErrorObject(globalObject, sourceCode, -1);
auto exception = createParseError(globalObject, error, sourceCode);
// Building the error materializes its stack, running a user
// Error.prepareStackTrace that may throw; Node throws the
// SyntaxError anyway. Terminations survive tryClearException.
Expand Down Expand Up @@ -594,6 +594,24 @@ bool handleException(JSGlobalObject* globalObject, VM& vm, NakedPtr<JSC::Excepti
return false;
}

// ParserError::toErrorObject() with the error tagged as node:vm source first.
// addErrorInfo() formats the stack before returning, and all it gives the
// formatter is the URL the source was compiled under, which for node:vm is a
// caller-chosen filename; the tag is what stops the formatter from remapping
// the parse location through the source map of whatever file that name denotes.
JSObject* createParseError(JSGlobalObject* globalObject, JSC::ParserError& parseError, JSC::SourceCode source)
{
if (parseError.type() != JSC::ParserError::ErrorType::SyntaxError)
return parseError.toErrorObject(globalObject, source);

VM& vm = globalObject->vm();
auto* error = uncheckedDowncast<ErrorInstance>(createSyntaxError(globalObject, parseError.message()));
error->putDirect(vm, WebCore::builtinNames(vm).vmParseErrorPrivateName(), jsBoolean(true), JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::ReadOnly);
addErrorInfo(vm, error, parseError.line(), source);
error->setParseError();
return error;
}

// Compile-time counterpart of handleException: prepends Node's arrow header
// (`<url>:<line>\n<src>\n^\n\n`) using ParserError since there is no CodeBlock
// yet. Node applies this unconditionally at compile time (not displayErrors).
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/bindings/NodeVM.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ bool extractCachedData(JSValue cachedDataValue, WTF::Vector<uint8_t>& outCachedD
String stringifyAnonymousFunction(JSGlobalObject* globalObject, const ArgList& args, ThrowScope& scope, int* outOffset);
JSC::EncodedJSValue createCachedData(JSGlobalObject* globalObject, const JSC::SourceCode& source);
bool handleException(JSGlobalObject* globalObject, VM& vm, NakedPtr<JSC::Exception> exception, ThrowScope& throwScope);
// Every node:vm compile path turns its ParserError into an exception through
// this rather than ParserError::toErrorObject(); see the definition.
JSObject* createParseError(JSGlobalObject* globalObject, JSC::ParserError& parseError, JSC::SourceCode source);
// `url` must be caller-resolved: `new Script` falls back to evalmachine.<anonymous>
// when no filename was provided; compileFunction has no such default.
void decorateParseErrorStack(JSGlobalObject* globalObject, VM& vm, JSObject* error, StringView sourceString, const String& url, const JSC::ParserError& parseError, OrdinalNumber lineOffset);
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/bindings/NodeVMScript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ constructScript(JSGlobalObject* globalObject, CallFrame* callFrame, JSValue newT
// via JSC::evaluate); compile-once via m_cachedExecutable is the follow-up.
JSC::ParserError parseError;
if (!JSC::checkSyntax(vm, source, parseError)) {
auto exception = parseError.toErrorObject(globalObject, source, -1);
auto exception = createParseError(globalObject, parseError, source);
// Building the error materializes its stack, running a user
// Error.prepareStackTrace that may throw; Node throws the SyntaxError
// anyway. tryClearException leaves a termination for the check below.
Expand Down
9 changes: 8 additions & 1 deletion src/jsc/bindings/NodeVMSourceTextModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,14 @@ JSValue NodeVMSourceTextModule::createModuleRecord(JSGlobalObject* globalObject)
parserError);

if (parserError.isValid()) {
throwException(globalObject, scope, parserError.toErrorObject(globalObject, m_sourceCode));
JSObject* exception = createParseError(globalObject, parserError, m_sourceCode);
// Building the error materializes its stack, running a user
// Error.prepareStackTrace that may throw; Node throws the SyntaxError
// anyway. tryClearException leaves a termination for the check below.
if (exception)
(void)scope.tryClearException();
RETURN_IF_EXCEPTION(scope, {});
throwException(globalObject, scope, exception);
return {};
}

Expand Down
99 changes: 98 additions & 1 deletion test/js/node/vm/vm.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, normalizeBunSnapshot } from "harness";
import { bunEnv, bunExe, normalizeBunSnapshot, tempDir } from "harness";
import {
compileFunction,
constants,
Expand Down Expand Up @@ -1484,3 +1484,100 @@ test("node:vm Object.defineProperty on the context global when the sandbox is an
expect(stdout.trim()).toBe(JSON.stringify({ result: 1, sandboxArray: 1 }));
expect(exitCode).toBe(0);
});

describe("SyntaxError from compiling vm code under the filename of a file Bun transpiled", () => {
// Bun's source maps are keyed by filename, and the only thing a parser
// SyntaxError keeps of the source it came from is that filename, so the
// location it reports must not be looked up in the map of the file the vm
// code merely shares a name with. The fixture compiles vm code under its own
// path and under a name Bun never loaded; both must report the same thing.
// The fixture opens with a comment spanning PADDING lines that the transpiler
// strips, so every line its source map can produce is > PADDING, while the
// vm code's syntax error is on line 5: a remapped line can never pass for the
// physical one.
const PADDING = 20;
const padding = ["/*", ...Array.from({ length: PADDING - 2 }, () => " *"), " */"].join("\n") + "\n";
const body = String.raw`
const vm = require("node:vm");
const source = "\n\n\n\nlet let = 1;";
const names = { own: __filename, other: "not-a-loaded-file.js" };
const compile = {
script: name => new vm.Script(source, { filename: name }),
runInThisContext: name => vm.runInThisContext(source, { filename: name }),
runInContext: name => vm.runInContext(source, vm.createContext(), { filename: name }),
runInNewContext: name => vm.runInNewContext(source, {}, { filename: name }),
compileFunction: name => vm.compileFunction(source, [], { filename: name }),
sourceTextModule: name => new vm.SourceTextModule(source, { identifier: name }),
};

function thrown(fn) {
try {
fn();
} catch (e) {
return e;
}
throw new Error("did not throw");
}

function report(err) {
const lines = err.stack.split("\n");
return {
header: lines[0],
parseFrame: lines.find(line => line.includes("<parse>")) ?? null,
line: err.line,
originalLine: err.originalLine ?? null,
sourceURL: err.sourceURL ?? null,
};
}

const results = {};
for (const [api, make] of Object.entries(compile)) {
results[api] = { own: report(thrown(() => make(names.own))), other: report(thrown(() => make(names.other))) };
}
console.log(JSON.stringify({ filename: __filename, results, inspected: Bun.inspect(thrown(() => compile.script(names.own))) }));
`;

test("err.stack, err.line and Bun.inspect report the line in the vm code", async () => {
using dir = tempDir("vm-parse-error-own-filename", { "fixture.js": padding + body });
await using proc = Bun.spawn({
cmd: [bunExe(), "fixture.js"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
const { filename, results, inspected } = JSON.parse(stdout);

const asOther = (own: Record<string, unknown>) =>
Object.fromEntries(
Object.entries(own).map(([key, value]) => [
key,
typeof value === "string" ? value.replaceAll(filename, "not-a-loaded-file.js") : value,
]),
);

// err.originalLine records the line a source map was applied to, so nothing
// compiled by vm gets one, whatever its name.
const physical = {
header: "not-a-loaded-file.js:5",
parseFrame: " at <parse> (not-a-loaded-file.js:5)",
line: 5,
originalLine: null,
sourceURL: "not-a-loaded-file.js",
};
for (const api of ["script", "runInThisContext", "runInContext", "runInNewContext", "compileFunction"]) {
expect(asOther(results[api].own)).toEqual(physical);
expect(results[api].other).toEqual(physical);
}
// SourceTextModule does not yet compile under its identifier, so only the
// own/other equivalence is pinned for it.
expect(asOther(results.sourceTextModule.own)).toEqual(results.sourceTextModule.other);

// Bun.inspect (like the uncaught error printer) formats the frames of the
// already built stack string; it adds a column of its own, dropped here.
const inspectedParseFrame = inspected.split("\n").find((line: string) => line.includes("<parse>"));
expect(inspectedParseFrame.replace(/(:\d+)(:\d+)?\)$/, "$1)")).toEndWith(`at <parse> (${filename}:5)`);
});
});