Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions src/js/builtins.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,10 @@ declare function $ERR_HTTP2_PING_CANCEL(): Error;
declare function $toClass(fn: Function, name: string, base?: Function | undefined | null);

declare function $min(a: number, b: number): number;
/** The engine's own `String.prototype.substring`; user changes to the prototype do not reach it. */
declare var $stringSubstring: typeof String.prototype.substring;
/** The engine's own `String.prototype.indexOf`; user changes to the prototype do not reach it. */
declare var $stringIndexOfInternal: typeof String.prototype.indexOf;

interface Map<K, V> {
$get: typeof Map.prototype.get;
Expand Down
15 changes: 9 additions & 6 deletions src/js/builtins/CommonJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ $overriddenName = "require";
$visibility = "Private";
export function overridableRequire(this: JSCommonJSModule, originalId: string, options?: { paths?: string[] }) {
const id = $resolveSync(originalId, this.filename, false, false, options ? options.paths : undefined, this, options);
if (id.startsWith("node:")) {
// $stringSubstring / $stringIndexOfInternal are the engine's own String
// methods; a user-patched String.prototype must not pick the loader.
Comment thread
robobun marked this conversation as resolved.
Resolved
if ($stringSubstring.$call(id, 0, 5) === "node:") {
if (id !== originalId) {
// A terrible special case where Node.js allows non-prefixed built-ins to
// read the require cache. Though they never write to it, which is so silly.
Expand Down Expand Up @@ -62,8 +64,9 @@ export function overridableRequire(this: JSCommonJSModule, originalId: string, o

// A resolved id may carry a `?query` suffix (part of the module cache key);
// match the native-addon extension against the path portion only.
const queryIndex = id.indexOf("?");
if (queryIndex === -1 ? id.endsWith(".node") : id.endsWith(".node", queryIndex)) {
const queryIndex = $stringIndexOfInternal.$call(id, "?");
const pathEnd = queryIndex === -1 ? id.length : queryIndex;
if (pathEnd >= 5 && $stringSubstring.$call(id, pathEnd - 5, pathEnd) === ".node") {
return $internalRequire(id, this);
}

Expand Down Expand Up @@ -156,9 +159,9 @@ export function internalRequire(id: string, parent: JSCommonJSModule) {
$assert($requireMap.$get(id) === undefined, "Module " + JSON.stringify(id) + " should not be in the map");
// `id` keys the module cache and may carry a `?query` suffix;
// `process.dlopen` needs the on-disk path.
const queryIndex = id.indexOf("?");
const filename = queryIndex === -1 ? id : id.substring(0, queryIndex);
$assert(filename.endsWith(".node"));
const queryIndex = $stringIndexOfInternal.$call(id, "?");
const filename = queryIndex === -1 ? id : $stringSubstring.$call(id, 0, queryIndex);
$assert($stringSubstring.$call(filename, filename.length - 5) === ".node");

const module = $createCommonJSModule(id, {}, true, parent);
process.dlopen(module, filename);
Expand Down
5 changes: 3 additions & 2 deletions src/js/internal/fs/cp-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,9 @@ function mkDirAndCopy(srcMode, src, dest, opts) {
}

function copyDir(src, dest, opts) {
for (const dirent of readdirSync(src, { withFileTypes: true })) {
const { name } = dirent;
const dirents = readdirSync(src, { withFileTypes: true });
for (let i = 0; i < dirents.length; i++) {
const { name } = dirents[i];
const srcItem = join(src, name);
const destItem = join(dest, name);
const { destStat, skipped } = checkPathsSync(srcItem, destItem, opts);
Expand Down
16 changes: 8 additions & 8 deletions src/js/internal/fs/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,11 +562,11 @@ function _write(data, encoding, cb) {
const maybePromise = fileSink.write(data);
if ($isPromise(maybePromise)) {
maybePromise
.then(() => {
.$then(() => {
this.emit("drain"); // Emit drain event
cb(null);
})
.catch(cb);
.$then(undefined, cb);
return false; // Indicate backpressure
} else {
cb(null);
Expand Down Expand Up @@ -606,7 +606,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any)

const maybePromise = fileSink.write(data);
if ($isPromise(maybePromise)) {
maybePromise.then(
maybePromise.$then(
() => {
if (cb) cb(null);
this.emit("drain");
Expand Down Expand Up @@ -655,7 +655,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) {
if ($isPromise(maybePromise)) {
// Two-arg then(): a throw from the fulfillment handler must not be
// mistaken for a write failure.
maybePromise.then(
maybePromise.$then(
() => {
this.emit("drain"); // Emit drain event
cb(null);
Expand Down Expand Up @@ -699,11 +699,11 @@ writeStreamPrototype._writev = function (data, cb) {
const maybePromise = fileSink.write(Buffer.concat(chunks));
if ($isPromise(maybePromise)) {
maybePromise
.then(() => {
.$then(() => {
this.emit("drain");
cb(null);
})
.catch(cb);
.$then(undefined, cb);
return false;
} else {
cb(null);
Expand Down Expand Up @@ -731,7 +731,7 @@ writeStreamPrototype._destroy = function (err, cb) {
if (sink && sink !== true) {
const end = sink.end(err);
if ($isPromise(end)) {
end.then(() => cb(err), cb);
end.$then(() => cb(err), cb);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
return;
}
}
Expand Down Expand Up @@ -790,7 +790,7 @@ Object.defineProperty(writeStreamPrototype, "pending", {
function thenIfPromise<T>(maybePromise: Promise<T> | T, cb: any) {
$assert(typeof cb === "function", "cb is not a function");
if ($isPromise(maybePromise)) {
maybePromise.then(() => cb(null), cb);
maybePromise.$then(() => cb(null), cb);
} else {
process.nextTick(cb, null);
}
Expand Down
33 changes: 20 additions & 13 deletions src/js/internal/net/isIP.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const RegExpPrototypeExec = RegExp.prototype.exec;

const v4Seg = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";
const v4Str = `(?:${v4Seg}\\.){3}${v4Seg}`;
var IPv4Reg: RegExp | undefined;
Expand All @@ -6,22 +8,27 @@ const v6Seg = "(?:[0-9a-fA-F]{1,4})";
var IPv6Reg: RegExp | undefined;

function isIPv4(s) {
return (IPv4Reg ??= new RegExp(`^${v4Str}$`)).test(s);
return RegExpPrototypeExec.$call((IPv4Reg ??= new RegExp(`^${v4Str}$`)), s) !== null;
}

function isIPv6(s) {
return (IPv6Reg ??= new RegExp(
"^(?:" +
`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
`(?:${v6Seg}:){5}(?::${v4Str}|(?::${v6Seg}){1,2}|:)|` +
`(?:${v6Seg}:){4}(?:(?::${v6Seg}){0,1}:${v4Str}|(?::${v6Seg}){1,3}|:)|` +
`(?:${v6Seg}:){3}(?:(?::${v6Seg}){0,2}:${v4Str}|(?::${v6Seg}){1,4}|:)|` +
`(?:${v6Seg}:){2}(?:(?::${v6Seg}){0,3}:${v4Str}|(?::${v6Seg}){1,5}|:)|` +
`(?:${v6Seg}:){1}(?:(?::${v6Seg}){0,4}:${v4Str}|(?::${v6Seg}){1,6}|:)|` +
`(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
")(?:%[0-9a-zA-Z-.:]{1,})?$",
)).test(s);
return (
RegExpPrototypeExec.$call(
(IPv6Reg ??= new RegExp(
"^(?:" +
`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
`(?:${v6Seg}:){5}(?::${v4Str}|(?::${v6Seg}){1,2}|:)|` +
`(?:${v6Seg}:){4}(?:(?::${v6Seg}){0,1}:${v4Str}|(?::${v6Seg}){1,3}|:)|` +
`(?:${v6Seg}:){3}(?:(?::${v6Seg}){0,2}:${v4Str}|(?::${v6Seg}){1,4}|:)|` +
`(?:${v6Seg}:){2}(?:(?::${v6Seg}){0,3}:${v4Str}|(?::${v6Seg}){1,5}|:)|` +
`(?:${v6Seg}:){1}(?:(?::${v6Seg}){0,4}:${v4Str}|(?::${v6Seg}){1,6}|:)|` +
`(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
")(?:%[0-9a-zA-Z-.:]{1,})?$",
)),
s,
) !== null
);
}

function isIP(s) {
Expand Down
24 changes: 19 additions & 5 deletions src/js/node/child_process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@
// normalizeSpawnargs has already prepended argv0 to the spawnargs array
// Bun.spawn() expects cmd[0] to be the command to run, and argv0 to replace the first arg when running the command,
// so we have to set argv0 to spawnargs[0] and cmd[0] to file
cmd: [options.file, ...Array.prototype.slice.$call(options.args, 1)],
cmd: spawnCommand(options.file, options.args),
// The normalized env (kBunEnv) is built from the live process.env when
// options.env is not given, so runtime mutations of process.env reach
// the child like in Node.js.
Expand Down Expand Up @@ -797,7 +797,12 @@
}
}

args = [...execArgv, modulePath, ...args];
const forkArgs = ArrayPrototypeSlice.$call(execArgv);
ArrayPrototypePush.$call(forkArgs, modulePath);
for (let i = 0; i < args.length; i++) {
ArrayPrototypePush.$call(forkArgs, args[i]);
}
args = forkArgs;
Comment thread
robobun marked this conversation as resolved.
Resolved

if (typeof options.stdio === "string") {
options.stdio = stdioStringToArray(options.stdio, "ipc");
Expand Down Expand Up @@ -908,6 +913,14 @@
};
}

// spawnargs carries argv0 at index 0 (normalizeSpawnArguments prepends it);
// Bun.spawn() wants the program in cmd[0] and takes argv0 separately.
Comment thread
robobun marked this conversation as resolved.
Resolved
function spawnCommand(file, spawnargs) {
const cmd = ArrayPrototypeSlice.$call(spawnargs);
cmd[0] = file;
Comment thread
robobun marked this conversation as resolved.
Resolved
return cmd;
}

const kBunEnv = Symbol("bunEnv");
function normalizeSpawnArguments(file, args, options) {
validateString(file, "file");
Expand Down Expand Up @@ -985,7 +998,7 @@
// Handle shell
if (shell) {
validateArgumentNullCheck(shell, "options.shell");
const command = ArrayPrototypeJoin.$call([file, ...args], " ");
const command = args.length === 0 ? file : file + " " + ArrayPrototypeJoin.$call(args, " ");
// Set the shell, switches, and commands.
if (process.platform === "win32") {
if (typeof shell === "string") file = shell;
Expand Down Expand Up @@ -1044,7 +1057,8 @@
});
}

for (const key of envKeys) {
for (let i = 0; i < envKeys.length; i++) {
const key = envKeys[i];
const value = env[key];
if (value !== undefined) {
validateArgumentNullCheck(key, `options.env['${key}']`);
Expand Down Expand Up @@ -1410,7 +1424,7 @@

try {
this.#handle = Bun.spawn({
cmd: [file, ...Array.prototype.slice.$call(spawnargs, 1)],
cmd: spawnCommand(file, spawnargs),

Check warning on line 1427 in src/js/node/child_process.ts

View check run for this annotation

Claude / Claude Code Review

child_process error path still reads Array.prototype.slice live

The catch handler in `ChildProcess#spawn` still does `ex.spawnargs = Array.prototype.slice.$call(this.spawnargs, 1)` — a live read of `Array.prototype.slice` — while the two `cmd:` sites this PR converted and every other `.spawnargs =` assignment in the file already use the module-level captured `ArrayPrototypeSlice`. Under the patched `slice` this PR's own new test installs, an ENOENT/EACCES spawn error would carry a corrupted `spawnargs`. Swap it to `ArrayPrototypeSlice.$call(this.spawnarg
Comment thread
robobun marked this conversation as resolved.
Resolved
stdio: bunStdio,
cwd: options.cwd || undefined,
env: env,
Expand Down
23 changes: 11 additions & 12 deletions src/js/node/fs.promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@ async function* glob(pattern, options) {

const exports = {
access: asyncWrap(fs.access, "access"),
appendFile: async function (fileHandleOrFdOrPath, ...args) {
appendFile: async function (fileHandleOrFdOrPath, data, options) {
fileHandleOrFdOrPath = fileHandleOrFdOrPath?.[kFd] ?? fileHandleOrFdOrPath;
return _appendFile(fileHandleOrFdOrPath, ...args);
return _appendFile(fileHandleOrFdOrPath, data, options);
},
close: asyncWrap(fs.close, "close"),
copyFile: asyncWrap(fs.copyFile, "copyFile"),
Expand Down Expand Up @@ -304,23 +304,22 @@ const exports = {
read: asyncWrap(fs.read, "read"),
write: asyncWrap(fs.write, "write"),
readdir: asyncWrap(fs.readdir, "readdir"),
readFile: async function (fileHandleOrFdOrPath, ...args) {
readFile: async function (fileHandleOrFdOrPath, options) {
fileHandleOrFdOrPath = fileHandleOrFdOrPath?.[kFd] ?? fileHandleOrFdOrPath;
return _readFile(fileHandleOrFdOrPath, ...args);
return _readFile(fileHandleOrFdOrPath, options);
},
writeFile: async function (fileHandleOrFdOrPath, ...args: any[]) {
writeFile: async function (fileHandleOrFdOrPath, data, options) {
fileHandleOrFdOrPath = fileHandleOrFdOrPath?.[kFd] ?? fileHandleOrFdOrPath;
if (
!$isTypedArrayView(args[0]) &&
typeof args[0] !== "string" &&
($isCallable(args[0]?.[Symbol.iterator]) || $isCallable(args[0]?.[Symbol.asyncIterator]))
!$isTypedArrayView(data) &&
typeof data !== "string" &&
($isCallable(data?.[Symbol.iterator]) || $isCallable(data?.[Symbol.asyncIterator]))
) {
$debug("fs.promises.writeFile async iterator slow path!");
// Node accepts an arbitrary async iterator here
// @ts-expect-error
return writeFileAsyncIterator(fileHandleOrFdOrPath, ...args);
return writeFileAsyncIterator(fileHandleOrFdOrPath, data, options);
}
return _writeFile(fileHandleOrFdOrPath, ...args);
return _writeFile(fileHandleOrFdOrPath, data, options);
},
readlink: asyncWrap(fs.readlink, "readlink"),
realpath: asyncWrap(fs.realpath, "realpath"),
Expand Down Expand Up @@ -1603,7 +1602,7 @@ function flagTruncates(flag): boolean {
return flag === "w" || flag === "w+" || flag === "wx" || flag === "wx+" || flag === "xw" || flag === "xw+";
}

async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, flag, mode) {
async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, flag?, mode?) {
let encoding;
let signal: AbortSignal | null = null;
if (typeof optionsOrEncoding === "object") {
Expand Down
Loading
Loading