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 packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3057,6 +3057,7 @@ declare module "bun" {
* - Hoists all declarations as var for REPL persistence across vm.runInContext calls
* - Wraps last expression in { __proto__: null, value: expr } for result capture
* - Wraps code in sync/async IIFE to avoid parentheses around object literals
* - Leaves `__dirname` and `__filename` undeclared, so the context that runs the code has to define them
*
* @default false
*/
Expand Down
6 changes: 6 additions & 0 deletions src/js_parser/parse/parse_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,12 @@ impl<'a> Parser<'a> {
let mut uses_filename =
p.symbols.as_slice()[p.filename_ref.inner_index() as usize].use_count_estimate > 0;

// The REPL transform would turn the `var` below into an assignment to the host's global.
if p.options.repl_mode {
uses_dirname = false;
uses_filename = false;
}

// Handle dirname and filename at bundle-time
// We always inject it at the top of the module
//
Expand Down
55 changes: 54 additions & 1 deletion test/js/bun/repl/repl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,39 @@ describe.concurrent("Bun REPL", () => {
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});

test("__dirname and __filename are the globals that belong to `module`", async () => {
using dir = tempDir("repl-dirname", {
"local.js": `module.exports = { value: "from-local-file" };`,
});
const { outputs, stderr, exitCode } = await runRepl(
[
"__dirname === module.path",
"__filename === module.filename",
// An import statement makes the parser treat the input as ESM.
"import { basename } from 'path'; basename(__dirname)",
"require(require('path').join(__dirname, 'local.js')).value",
// An input that reads the identifiers leaves the globals as they were.
"globalThis.__dirname === module.path && globalThis.__filename === module.filename",
// They are ordinary globals, so an assignment lasts for the session.
"__dirname = 'assigned'",
"__dirname",
".exit",
],
{ cwd: String(dir) },
);
expect(outputs).toEqual([
"true",
"true",
JSON.stringify(path.basename(String(dir))),
'"from-local-file"',
"true",
'"assigned"',
'"assigned"',
]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});
});

describe("global objects", () => {
Expand Down Expand Up @@ -832,11 +865,12 @@ describe.concurrent("Bun REPL", () => {
});

describe("-e / --eval and -p / --print", () => {
async function runReplWith(args: string[]) {
async function runReplWith(args: string[], cwd?: string) {
await using proc = Bun.spawn({
cmd: [bunExe(), "repl", ...args],
stdout: "pipe",
stderr: "pipe",
cwd,
env: { ...bunEnv, NO_COLOR: "1" },
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
Expand Down Expand Up @@ -998,6 +1032,25 @@ describe.concurrent("Bun REPL", () => {
expect(exitCode).toBe(0);
});

test("-e reads __dirname and __filename from the globals that belong to `module`", async () => {
using dir = tempDir("repl-eval-dirname", {});
const { stdout, stderr, exitCode } = await runReplWith(
[
"-e",
`const { basename } = require("path");
console.log(JSON.stringify({
dirname: __dirname === module.path,
filename: __filename === module.filename,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
dir: basename(__dirname),
}))`,
],
String(dir),
);
expect(stdout).toBe(JSON.stringify({ dirname: true, filename: true, dir: path.basename(String(dir)) }) + "\n");
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});

// https://github.com/oven-sh/bun/issues/31225
test("bare top-level `this` does not throw (issue #31225)", async () => {
// Before the fix this threw `ReferenceError: exports is not defined`
Expand Down
15 changes: 15 additions & 0 deletions test/js/bun/transpiler/repl-transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,21 @@ describe("Bun.Transpiler replMode", () => {
const result = await vm.runInContext(code2, ctx);
expect(result).toEqual({ value: 20 });
});

test.each(["[__dirname, __filename]", "await 0; [__dirname, __filename]"])(
"__dirname and __filename are read from the context and not overwritten: %s",
async code => {
const ctx = vm.createContext({ __dirname: "/ctx", __filename: "/ctx/session.js" });
const result = await vm.runInContext(transpiler.transformSync(code), ctx);
expect(result).toEqual({ value: ["/ctx", "/ctx/session.js"] });
expect(ctx).toEqual({ __dirname: "/ctx", __filename: "/ctx/session.js" });
},
);

test("__dirname and __filename that the context does not define are not declared", async () => {
const result = await runRepl("[typeof __dirname, typeof __filename]", {});
expect(result).toEqual({ value: ["undefined", "undefined"] });
});
});

describe("variable persistence across lines", () => {
Expand Down
Loading