From 90c17ba5b306890543ff70048cd5d41bb91617b9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:10:07 +0000 Subject: [PATCH] util.inspect: print the state of Response, Request, Headers, Blob and six more classes node:util printed Response, Request, Headers, FormData, Blob, AbortSignal, AbortController, Event, TextDecoder and Timeout as `Name {}`, because their state is in native fields. Each prototype now has node's own `[Symbol.for("nodejs.util.inspect.custom")]` method. util.inspect, util.format and the node:console Console find it through the lookup they already do. - The native half of a method finds the instance and copies its state into a plain object. It reads native fields and runs no code of the program: no getter of the class, no Proxy trap. - The rest of node's method for each class is a case in the new internal module internal/util/inspect_hooks: the names it reads from `this`, the depth rule, the options, the name of the constructor, and the answer for a receiver of another class. Where node's depth does not count down, a value that holds itself in a field that its method prints is `[Circular]`: the methods hand on which values they print in an option of the `inspect` that they start. - Headers, FormData, AbortSignal, AbortController and Event have a host function next to their prototype. `inspectCustom: true` in a *.classes.ts file installs the method for Response, Request, Blob, TextDecoder and Timeout, with readers in Rust. - A print changes nothing. The Response and Request readers do not attach a header list: `default_headers` and `default_fetch_headers` build the list that the `headers` getter would attach. They read what a cached getter gave before, keep no URL and no signal, and give the state of a body stream, not the stream. A Blob shows a size only when it has one. - Bun's native formatter (console.log, Bun.inspect, bun:test) keeps its own text for these classes. It looks for a method as if the ten host functions were not there, and does not list them under the method's key. It knows them by their address. - util.inspect rethrows an error that a nested value's method throws, as node does. It wrapped every such error in an AssertionError. Co-authored-by: Ciro Spaciari <6379399+cirospaciari@users.noreply.github.com> --- src/codegen/class-definitions.ts | 6 +- src/codegen/generate-classes.ts | 63 +- src/js/internal/util/inspect.js | 7 +- src/js/internal/util/inspect_hooks.ts | 300 +++++ src/jsc/ConsoleObject.rs | 35 +- .../bindings/webcore/JSAbortController.cpp | 20 + src/jsc/bindings/webcore/JSAbortSignal.cpp | 18 + src/jsc/bindings/webcore/JSDOMFormData.cpp | 30 + src/jsc/bindings/webcore/JSEvent.cpp | 25 + src/jsc/bindings/webcore/JSFetchHeaders.cpp | 37 + .../webcore/streams/JSReadableStream.cpp | 30 +- .../streams/WebStreamsInspectCustom.cpp | 129 +- .../webcore/streams/WebStreamsInspectCustom.h | 17 + src/runtime/generated_classes.rs | 2 + src/runtime/node/node.classes.ts | 1 + src/runtime/socket/SocketAddress.rs | 1 - src/runtime/test_runner/pretty_format.rs | 4 +- src/runtime/timer/TimeoutObject.rs | 33 + src/runtime/webcore.rs | 3 + src/runtime/webcore/Blob.rs | 53 +- src/runtime/webcore/Request.rs | 25 +- src/runtime/webcore/Response.rs | 37 +- src/runtime/webcore/TextDecoder.rs | 14 + src/runtime/webcore/encoding.classes.ts | 1 + src/runtime/webcore/node_inspect.rs | 188 +++ src/runtime/webcore/response.classes.ts | 3 + .../source-lints/redis-client-types.test.ts | 3 +- .../test/parallel/test-events-customevent.js | 9 +- .../js/node/test/parallel/test-eventtarget.js | 6 +- test/js/node/util/custom-inspect.test.js | 634 ++++++++++ test/js/node/util/inspect-web-classes.test.ts | 1099 +++++++++++++++++ 31 files changed, 2749 insertions(+), 84 deletions(-) create mode 100644 src/js/internal/util/inspect_hooks.ts create mode 100644 src/runtime/webcore/node_inspect.rs create mode 100644 test/js/node/util/inspect-web-classes.test.ts diff --git a/src/codegen/class-definitions.ts b/src/codegen/class-definitions.ts index 52c6e12d6237..38003a21d93a 100644 --- a/src/codegen/class-definitions.ts +++ b/src/codegen/class-definitions.ts @@ -7,7 +7,6 @@ interface PropertyAttribute { * from the prototype hash table, instead setting it using `putDirect()`. */ privateSymbol?: string; - publicSymbol?: string; name?: string; } @@ -215,6 +214,7 @@ export class ClassDefinition { configurable?: boolean; enumerable?: boolean; structuredClone?: { transferable: boolean; tag: number; storable: boolean }; + /** Installs node's `[nodejs.util.inspect.custom]` method, with `inspect_custom` of the struct as its native half. */ inspectCustom?: boolean; constructor(options: Partial) { @@ -248,11 +248,11 @@ export function define( proto.inspectCustom = { fn: "inspectCustom", length: 2, - publicSymbol: "inspectCustom", - name: "[nodejs.util.inspect.custom]", + passThis: true, }; } return new ClassDefinition({ + inspectCustom, ...rest, // `refCounted` is a kind of finalize as far as the C++ wrapper is concerned. finalize: rest.finalize || rest.refCounted, diff --git a/src/codegen/generate-classes.ts b/src/codegen/generate-classes.ts index 428cc8b0e992..723da27fc77c 100644 --- a/src/codegen/generate-classes.ts +++ b/src/codegen/generate-classes.ts @@ -55,6 +55,11 @@ function constructorName(typeName) { return `JS${typeName}Constructor`; } +/** The proto field that `inspectCustom: true` adds: node's `[nodejs.util.inspect.custom]` method. */ +function isInspectCustomHook(obj, name) { + return !!obj.inspectCustom && name === "inspectCustom"; +} + function zigExportName(to: Map, symbolName: (name: string) => string, prop) { var { getter, setter, fn } = prop; const exportNames = { @@ -178,7 +183,7 @@ export function generateHashTable(nameToUse, symbolName, typeName, obj, props = for (const name in props) { if ("privateSymbol" in props[name] || "internal" in props[name] || "value" in props[name]) continue; - if (name.startsWith("@@")) continue; + if (name.startsWith("@@") || isInspectCustomHook(obj, name)) continue; rows.push(propRow(symbolName, typeName, name, props[name], wrapped, defaultPropertyAttributes, !!obj.forBind)); } @@ -260,19 +265,11 @@ JSC_DECLARE_CUSTOM_GETTER(js${typeName}Constructor); continue; } - if (protoFields[name].publicSymbol !== undefined) { - const publicSymbol = protoFields[name].publicSymbol; - const fn = protoFields[name].fn; - if (!fn) throw Error(`(field: ${name}) public field needs 'fn' key `); - const observable_name = protoFields[name].name ?? fn; - + if (isInspectCustomHook(obj, name)) { + // A prototype class that derives from this one (the S3 file) inherits the method. specialSymbols += ` - this->putDirect(vm, WebCore::clientData(vm)->builtinNames().${publicSymbol}PublicName(), JSFunction::create(vm, globalObject, ${ - protoFields[name].length || 0 - }, String("${observable_name}"_s), ${protoSymbolName( - typeName, - fn, - )}Callback, ImplementationVisibility::Public), PropertyAttribute::Function | 0);`; + if (classInfo() == info()) + Bun::WebStreams::installInspectCustom(vm, this, ${protoSymbolName(typeName, name)}Callback);`; continue; } @@ -814,7 +811,24 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObjec ); } - if ("fn" in proto[name]) { + if (isInspectCustomHook(obj, name)) { + // The receiver can be a Proxy or inherit from an instance. The JS half answers for one that holds none. + rows.push(` +JSC_DEFINE_HOST_FUNCTION(${symbolName(typeName, name)}Callback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + ${className(typeName)}* thisObject = Bun::WebStreams::inspectInstance<${className(typeName)}>(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "${typeName}"_s, nullptr, nullptr)); + + JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); + RELEASE_AND_RETURN(scope, ${symbolName(typeName, proto[name].fn)}(thisObject->wrapped(), lexicalGlobalObject, callFrame, JSValue::encode(thisObject))); +} + + `); + } else if ("fn" in proto[name]) { const fn = proto[name].fn; const invalidThisBehavior = proto[name].invalidThisBehavior ?? InvalidThisBehavior.Throw; rows.push(` @@ -2164,6 +2178,7 @@ const GENERATED_CLASSES_IMPL_HEADER_PRE = ` #include "WebCoreJSBuiltins.h" #include "ErrorCode+List.h" #include "ErrorCode.h" +#include "streams/WebStreamsInspectCustom.h" #include #if !OS(WINDOWS) @@ -2237,6 +2252,23 @@ const GENERATED_CLASSES_IMPL_FOOTER = ` `; +/** The table behind `Bun::WebStreams::generatedNodeOnlyInspectHooks` (WebStreamsInspectCustom.h). */ +function nodeOnlyInspectHooksCppImpl(classes: ClassDefinition[]) { + const hooks = classes + .filter(a => a.inspectCustom) + .map(a => ` WebCore::${protoSymbolName(a.name, "inspectCustom")}Callback,`); + return ` +namespace Bun { +namespace WebStreams { +const JSC::NativeFunction generatedNodeOnlyInspectHooks[] = { +${hooks.join("\n")} +}; +const size_t generatedNodeOnlyInspectHookCount = ${hooks.length}; +} // namespace WebStreams +} // namespace Bun +`; +} + function jsInheritsCppImpl() { return ` ${jsclasses @@ -2499,6 +2531,7 @@ function writeCppSerializers() { allImpls.join("\n"), writeCppSerializers(classes), GENERATED_CLASSES_IMPL_FOOTER, + nodeOnlyInspectHooksCppImpl(classes), jsInheritsCppImpl(), isTransferableCppImpl(), ]); @@ -2551,7 +2584,7 @@ function getPropertySignatureWithComment( } // --- Skip internal/private properties --- - if ("internal" in propDef) { + if ("internal" in propDef || isInspectCustomHook(classDef, propName)) { return null; } diff --git a/src/js/internal/util/inspect.js b/src/js/internal/util/inspect.js index 728b576090d8..e20bcdc571bb 100644 --- a/src/js/internal/util/inspect.js +++ b/src/js/internal/util/inspect.js @@ -1509,7 +1509,7 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { "special", ); } - throw new AssertionError("handleMaxCallStackSize assertion failed: " + String(err), true); + throw err; } const circular = ctx.circular; if (circular !== undefined) { @@ -2403,7 +2403,8 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc, original = va } ctx.indentationLvl -= 2; } catch (err) { - const message = ``; + // A nested method can throw null or undefined. + const message = ``; str = `${s(`[${label}:`, sp)} ${message}${s("]", sp)}`; } } else { @@ -2827,4 +2828,6 @@ export default { formatWithOptions, getStringWidth, stripVTControlCharacters, + // For internal/util/inspect_hooks. node:util reads the names above only. + getCtxStyle, }; diff --git a/src/js/internal/util/inspect_hooks.ts b/src/js/internal/util/inspect_hooks.ts new file mode 100644 index 000000000000..54290fff0109 --- /dev/null +++ b/src/js/internal/util/inspect_hooks.ts @@ -0,0 +1,300 @@ +// The JS half of node's `[nodejs.util.inspect.custom]` methods. WebStreamsInspectCustom.cpp calls it with native state. + +const { inspect, formatWithOptions, getCtxStyle } = require("internal/util/inspect"); +const { uncurryThis, SafeWeakMap } = require("internal/primordials"); + +const NumberIsFinite = Number.isFinite; +const NumberIsInteger = Number.isInteger; +const ObjectCreate = Object.create; +const ObjectDefineProperty = Object.defineProperty; +const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +const ObjectGetPrototypeOf = Object.getPrototypeOf; +const ObjectKeys = Object.keys; +const ObjectPrototypeHasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); +const ObjectPrototypePropertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); +const ObjectSetPrototypeOf = Object.setPrototypeOf; +const ReflectOwnKeys = Reflect.ownKeys; +const StringPrototypeIncludes = uncurryThis(String.prototype.includes); +const StringPrototypeIndexOf = uncurryThis(String.prototype.indexOf); +const StringPrototypeSlice = uncurryThis(String.prototype.slice); +const SymbolToStringTag = Symbol.toStringTag; +const customInspectSymbol = Symbol.for("nodejs.util.inspect.custom"); + +// The names that node's method reads from `this`, in its order. +const kResponse = ["status", "statusText", "headers", "body", "bodyUsed", "ok", "redirected", "type", "url"]; +const kRequest = [ + "method", + "url", + "headers", + "destination", + "referrer", + "referrerPolicy", + "mode", + "credentials", + "cache", + "redirect", + "integrity", + "keepalive", + "isReloadNavigation", + "isHistoryNavigation", + "signal", +]; +const kBlob = ["size", "type"]; +const kAbortSignal = ["aborted"]; +const kAbortController = ["signal"]; +const kTextDecoder = ["encoding", "fatal", "ignoreBOM"]; + +// A data property with one of `names` between the receiver and the class is the field. An accessor is not called. +function stateOf(names: string[], holder, fields: object) { + const state = {}; + for (let i = 0; i < names.length; i++) { + const name = names[i]; + let own; + for (let object = holder; object && !$isProxyObject(object); object = ObjectGetPrototypeOf(object)) { + own = ObjectGetOwnPropertyDescriptor(object, name); + if (own !== undefined) break; + } + if (own !== undefined && ObjectPrototypeHasOwnProperty(own, "value")) { + $putByValDirect(state, name, own.value); + } else if (ObjectPrototypeHasOwnProperty(fields, name)) { + $putByValDirect(state, name, fields[name]); + } + } + const rest = ObjectKeys(fields); + for (let i = 0; i < rest.length; i++) { + if (!ObjectPrototypeHasOwnProperty(state, rest[i])) $putByValDirect(state, rest[i], fields[rest[i]]); + } + return state; +} + +// Each method starts a new `inspect`, so the values being printed travel in an option that `inspect` passes on. +const kPrinting = "[[inspect_hooks.printing]]"; +const numbers = new SafeWeakMap(); +let lastNumber = 0; +function numberOf(instance: object): string { + let number = numbers.get(instance); + if (number === undefined) numbers.set(instance, (number = ++lastNumber)); + return `,${number},`; +} +function isPrinting(options, instance: object) { + const printing = options?.[kPrinting]; + return typeof printing === "string" && StringPrototypeIncludes(printing, numberOf(instance)); +} +function printingWith(options, instance: object) { + const printing = options?.[kPrinting]; + const number = numberOf(instance); + return typeof printing === "string" ? `${printing}${StringPrototypeSlice(number, 1)}` : number; +} + +function special(options, text: string) { + return typeof options?.stylize === "function" ? options.stylize(text, "special") : text; +} + +// node's getConstructorOf (lib/internal/util.js), ending at a Proxy. +function getConstructorOf(object) { + while (object && !$isProxyObject(object)) { + const descriptor = ObjectGetOwnPropertyDescriptor(object, "constructor"); + if (descriptor !== undefined && typeof descriptor.value === "function" && descriptor.value.name !== "") { + return descriptor.value; + } + object = ObjectGetPrototypeOf(object); + } + return null; +} + +function isInstanceof(object, constructor) { + try { + return object instanceof constructor; + } catch { + return false; + } +} + +// formatRaw's `[Name]`. node returns `this` there, and its value has own keys where Bun's has none. +function pastDepthLimit(self, options, holder, instance, tag: string, method) { + if (holder !== instance) return self; + let constructor: Function | null = null; + let constructorOwner; + let tagOwner; + // The prototype that has the method: Blob.prototype, for a Blob and for a File. + let methodOwner; + let object = holder; + for (; object && !$isProxyObject(object); object = ObjectGetPrototypeOf(object)) { + tagOwner ??= ObjectPrototypeHasOwnProperty(object, SymbolToStringTag) ? object : undefined; + if (constructor === null) { + const descriptor = ObjectGetOwnPropertyDescriptor(object, "constructor"); + const value = descriptor !== undefined ? descriptor.value : undefined; + if (typeof value === "function" && value.name !== "" && isInstanceof(holder, value)) { + constructor = value; + constructorOwner = object; + } + } + if (tag === "File" && methodOwner === undefined) { + const descriptor = ObjectGetOwnPropertyDescriptor(object, customInspectSymbol); + if (descriptor !== undefined && descriptor.value === method) methodOwner = object; + } else if (constructor !== null && tagOwner !== undefined) { + break; + } + } + let toStringTag = holder[SymbolToStringTag]; + if ( + typeof toStringTag !== "string" || + (tagOwner === holder && (options?.showHidden || ObjectPrototypePropertyIsEnumerable(holder, SymbolToStringTag))) + ) { + toStringTag = ""; + } + // The search does not look behind a Proxy: a value with such a prototype is an Object. + let name = constructor !== null ? String(constructor.name) : object ? "Object" : null; + // A File has Blob.prototype, whose constructor and tag say Blob. + if (tag === "File" && methodOwner !== undefined) { + if (constructorOwner === methodOwner) name = tag; + if (toStringTag === "Blob" && tagOwner === methodOwner) toStringTag = tag; + } + const text = StringPrototypeSlice(getCtxStyle(holder, name, toStringTag), 0, -1); + return special(options, name === null ? text : `[${text}]`); +} + +// node's method for a ReadableStream (lib/internal/webstreams/util.js), over the state of a Response's body. +function bodyStream(fields: object) { + return { + [customInspectSymbol](depth, options) { + // What the stream's own method gives there. node's gives `undefined`. + if (depth < 0) return "ReadableStream {}"; + return `ReadableStream ${inspect(fields, { + ...options, + depth: options.depth == null ? null : options.depth - 1, + })}`; + }, + }; +} + +function withoutInstance(tag: string, self, options) { + switch (tag) { + // node's method has no check of its receiver: it prints it one level deep. + case "Timeout": + return inspect(self, { ...options, depth: 0, customInspect: false }); + case "Headers": + case "FormData": + case "Event": + case "TextDecoder": + throw $ERR_INVALID_THIS(tag); + } + // node prints undefined fields or throws here. The receiver comes back and prints as the object it is. + if (self == null) throw $ERR_INVALID_THIS(tag); + return self; +} + +function inspectHook(tag: string, self, depth, options, fields, holder, instance, method) { + // node's method for a timer prints own properties, so an object that inherits from a timer is not the timer. + if (fields === undefined || (tag === "Timeout" && holder !== instance)) return withoutInstance(tag, self, options); + + switch (tag) { + // undici v8.3.0 lib/web/fetch/response.js#L255 and request.js#L797: the depth that it got is kept. + case "Response": + case "Request": { + if (isPrinting(options, instance)) return special(options, "[Circular]"); + if (options.depth === null) options.depth = 2; + options.colors ??= true; + if (ObjectPrototypeHasOwnProperty(fields, "body") && fields.body !== null) { + $putByValDirect(fields, "body", bodyStream(fields.body)); + } + const state = stateOf(tag === "Response" ? kResponse : kRequest, holder, fields); + // formatWithOptions has undici's error for options that are a function. + if (typeof options === "function") return `${tag} ${formatWithOptions(options, state)}`; + const childOptions = { ...options, [kPrinting]: printingWith(options, instance) }; + // With colors, `inspect` makes its own `stylize`. The one in the options must not reach the nested methods. + if (childOptions.colors) delete childOptions.stylize; + return `${tag} ${formatWithOptions(childOptions, state)}`; + } + + // undici v8.3.0 lib/web/fetch/headers.js#L627 + case "Headers": + options.depth ??= depth; + return `Headers ${formatWithOptions(options, fields)}`; + + // undici v8.3.0 lib/web/fetch/formdata.js#L163. `fields` is the flat list name, value, name, value. + case "FormData": { + const state = { __proto__: null }; + for (let i = 0; i < fields.length; i += 2) { + const name = fields[i]; + const value = fields[i + 1]; + const held = state[name]; + if (!held) { + state[name] = value; + } else if ($isJSArray(held)) { + $putByValDirect(held, held.length, value); + } else { + state[name] = [held, value]; + } + } + options.depth ??= depth; + options.colors ??= true; + // The prefix of an object with no prototype takes part in the line breaks, then goes. + const output = formatWithOptions(options, state); + return `FormData ${StringPrototypeSlice(output, StringPrototypeIndexOf(output, "]") + 2)}`; + } + + // node v26.3.0 lib/internal/blob.js#L182 and file.js#L99 + case "Blob": + case "File": { + if (depth < 0) return pastDepthLimit(self, options, holder, instance, tag, method); + if (isPrinting(options, instance)) return special(options, "[Circular]"); + const childOptions = { ...options, depth: options.depth == null ? null : options.depth - 1 }; + if (!NumberIsFinite(childOptions.depth)) childOptions[kPrinting] = printingWith(options, instance); + return `${tag} ${inspect(stateOf(kBlob, holder, fields), childOptions)}`; + } + + // node v26.3.0 lib/internal/abort_controller.js#L124 + case "AbortSignal": + case "AbortController": { + if (depth < 0) { + // node returns `this`. Its AbortController has no own key and prints as `AbortController {}`. + return tag === "AbortSignal" ? pastDepthLimit(self, options, holder, instance, tag, method) : self; + } + if (isPrinting(options, instance)) return special(options, "[Circular]"); + const childOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + if (!NumberIsFinite(childOptions.depth)) childOptions[kPrinting] = printingWith(options, instance); + const names = tag === "AbortSignal" ? kAbortSignal : kAbortController; + return `${holder.constructor.name} ${inspect(stateOf(names, holder, fields), childOptions)}`; + } + + // node v26.3.0 lib/internal/event_target.js#L151 + case "Event": { + const name = holder.constructor.name; + if (depth < 0) return name; + return `${name} ${inspect(fields, { + ...options, + depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth, + })}`; + } + + // node v26.3.0 lib/internal/encoding.js#L581: the fields print with the default options. + case "TextDecoder": { + if (typeof depth === "number" && depth < 0) return pastDepthLimit(self, options, holder, instance, tag, method); + if (isPrinting(options, instance)) return special(options, "[Circular]"); + const constructor = getConstructorOf(holder); + return `${constructor === null ? tag : constructor.name} ${inspect(stateOf(kTextDecoder, holder, fields), { + [kPrinting]: printingWith(options, instance), + })}`; + } + + // node v26.3.0 lib/internal/timers.js#L224 prints the timer. This prints a stand-in with its prototype and properties. + case "Timeout": { + const state = ObjectCreate(ObjectGetPrototypeOf(instance)); + const names = ObjectKeys(fields); + for (let i = 0; i < names.length; i++) $putByValDirect(state, names[i], fields[names[i]]); + const keys = ReflectOwnKeys(instance); + for (let i = 0; i < keys.length; i++) { + const own = ObjectSetPrototypeOf(ObjectGetOwnPropertyDescriptor(instance, keys[i]), null); + if (own.value === instance) own.value = state; + // With `getters: true`, a getter of the timer runs on the timer. + const get = own.get; + if (get !== undefined) own.get = () => get.$call(instance); + ObjectDefineProperty(state, keys[i], own); + } + return inspect(state, { ...options, depth: 0, customInspect: false }); + } + } +} + +export default inspectHook; diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 54c1e9bea13f..3ae248f944f7 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -2143,13 +2143,17 @@ pub mod formatter { }); } Ok(Some(callback_value)) if callback_value.is_callable() => { - return Ok(TagResult { - tag: TagPayload::CustomFormattedObject(CustomFormattedObject { - function: callback_value, - this: value, - }), - cell: js_type, - }); + let callback_value = + inspect_custom_for_formatter(global_this, value, callback_value); + if !callback_value.is_empty() && callback_value.is_callable() { + return Ok(TagResult { + tag: TagPayload::CustomFormattedObject(CustomFormattedObject { + function: callback_value, + this: value, + }), + cell: js_type, + }); + } } _ => {} } @@ -3071,7 +3075,7 @@ pub mod formatter { ) -> Option { // SAFETY: caller passes a valid `*EncodedSlice`. let key = unsafe { &*key }; - if key.eq_ascii(b"constructor") { + if key.eq_ascii(b"constructor") || is_unlisted_inspect_method(key, is_symbol, value) { return None; } if ctx.formatter.failed { @@ -3203,6 +3207,21 @@ pub mod formatter { max_depth: u32, colors: bool, ) -> JSValue; + /// True for node's `[nodejs.util.inspect.custom]` method of a class with native state, which this formatter skips. + #[link_name = "Bun__isNodeOnlyInspectHook"] + pub safe fn is_node_only_inspect_hook(value: JSValue) -> bool; + /// `method`, or the method that `value` has without the node-only ones (empty when there is none). + #[link_name = "Bun__inspectCustomForFormatter"] + safe fn inspect_custom_for_formatter( + global: &JSGlobalObject, + value: JSValue, + method: JSValue, + ) -> JSValue; + } + + /// True for the one property that this formatter does not list: a node-only method under its symbol. + pub fn is_unlisted_inspect_method(key: &EncodedSlice, is_symbol: bool, value: JSValue) -> bool { + is_symbol && key.eq_ascii(b"nodejs.util.inspect.custom") && is_node_only_inspect_hook(value) } // ─────────────────────────────────────────────────────────────────────── diff --git a/src/jsc/bindings/webcore/JSAbortController.cpp b/src/jsc/bindings/webcore/JSAbortController.cpp index 20991d597aae..ae56b0bdf0f7 100644 --- a/src/jsc/bindings/webcore/JSAbortController.cpp +++ b/src/jsc/bindings/webcore/JSAbortController.cpp @@ -48,6 +48,7 @@ #include #include #include +#include "streams/WebStreamsInspectCustom.h" namespace WebCore { using namespace JSC; @@ -55,6 +56,7 @@ using namespace JSC; // Functions static JSC_DECLARE_HOST_FUNCTION(jsAbortControllerPrototypeFunction_abort); +JSC_DECLARE_HOST_FUNCTION(jsAbortControllerPrototypeFunction_inspectCustom); // Attributes @@ -144,6 +146,7 @@ void JSAbortControllerPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); Bun::reifyStaticPropertyTable(vm, JSAbortController::info(), JSAbortControllerPrototypeTableValues, *this); + Bun::WebStreams::installInspectCustom(vm, this, jsAbortControllerPrototypeFunction_inspectCustom); Bun::putToStringTagWithoutTransition(vm, this, info()); } @@ -189,6 +192,23 @@ JSC_DEFINE_CUSTOM_GETTER(jsAbortControllerConstructor, (JSGlobalObject * lexical return JSValue::encode(JSAbortController::getConstructor(vm, prototype->globalObject())); } +// Native half of node's `[nodejs.util.inspect.custom]` method. +JSC_DEFINE_HOST_FUNCTION(jsAbortControllerPrototypeFunction_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* thisObject = Bun::WebStreams::inspectInstance(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "AbortController"_s, nullptr, nullptr)); + + JSValue signal = toJS>(*lexicalGlobalObject, *thisObject->globalObject(), scope, thisObject->wrapped().signal()); + RETURN_IF_EXCEPTION(scope, {}); + JSObject* fields = constructEmptyObject(lexicalGlobalObject); + Bun::putDirectNamed(vm, fields, "signal"_s, signal); + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "AbortController"_s, fields, thisObject)); +} + static inline JSValue jsAbortController_signalGetter(JSGlobalObject& lexicalGlobalObject, JSAbortController& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); diff --git a/src/jsc/bindings/webcore/JSAbortSignal.cpp b/src/jsc/bindings/webcore/JSAbortSignal.cpp index 5996ca205c02..44896edc1e82 100644 --- a/src/jsc/bindings/webcore/JSAbortSignal.cpp +++ b/src/jsc/bindings/webcore/JSAbortSignal.cpp @@ -53,6 +53,7 @@ #include #include #include "ErrorCode.h" +#include "streams/WebStreamsInspectCustom.h" namespace WebCore { using namespace JSC; @@ -63,6 +64,7 @@ static JSC_DECLARE_HOST_FUNCTION(jsAbortSignalConstructorFunction_abort); static JSC_DECLARE_HOST_FUNCTION(jsAbortSignalConstructorFunction_timeout); static JSC_DECLARE_HOST_FUNCTION(jsAbortSignalConstructorFunction_any); static JSC_DECLARE_HOST_FUNCTION(jsAbortSignalPrototypeFunction_throwIfAborted); +JSC_DECLARE_HOST_FUNCTION(jsAbortSignalPrototypeFunction_inspectCustom); // Attributes @@ -143,6 +145,7 @@ void JSAbortSignalPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); Bun::reifyStaticPropertyTable(vm, JSAbortSignal::info(), JSAbortSignalPrototypeTableValues, *this); + Bun::WebStreams::installInspectCustom(vm, this, jsAbortSignalPrototypeFunction_inspectCustom); Bun::putToStringTagWithoutTransition(vm, this, info()); } @@ -191,6 +194,21 @@ JSC_DEFINE_CUSTOM_GETTER(jsAbortSignalConstructor, (JSGlobalObject * lexicalGlob return JSValue::encode(JSAbortSignal::getConstructor(vm, prototype->globalObject())); } +// Native half of node's `[nodejs.util.inspect.custom]` method. +JSC_DEFINE_HOST_FUNCTION(jsAbortSignalPrototypeFunction_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* thisObject = Bun::WebStreams::inspectInstance(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "AbortSignal"_s, nullptr, nullptr)); + + JSObject* fields = constructEmptyObject(lexicalGlobalObject); + Bun::putDirectNamed(vm, fields, "aborted"_s, jsBoolean(thisObject->wrapped().aborted())); + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "AbortSignal"_s, fields, thisObject)); +} + static inline JSValue jsAbortSignal_abortedGetter(JSGlobalObject& lexicalGlobalObject, JSAbortSignal& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); diff --git a/src/jsc/bindings/webcore/JSDOMFormData.cpp b/src/jsc/bindings/webcore/JSDOMFormData.cpp index 337065c2ae81..75eff110fb92 100644 --- a/src/jsc/bindings/webcore/JSDOMFormData.cpp +++ b/src/jsc/bindings/webcore/JSDOMFormData.cpp @@ -55,6 +55,7 @@ #include #include "ZigGeneratedClasses.h" #include "GCDefferalContext.h" +#include "streams/WebStreamsInspectCustom.h" namespace WebCore { using namespace JSC; @@ -102,6 +103,7 @@ static JSC_DECLARE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_forEach); // Non-standard functions static JSC_DECLARE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_toJSON); +JSC_DECLARE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_inspectCustom); // Attributes @@ -216,6 +218,7 @@ void JSDOMFormDataPrototype::finishCreation(VM& vm) Base::finishCreation(vm); Bun::reifyStaticPropertyTable(vm, JSDOMFormData::info(), JSDOMFormDataPrototypeTableValues, *this); putDirect(vm, vm.propertyNames->iteratorSymbol, getDirect(vm, vm.propertyNames->builtinNames().entriesPublicName()), static_cast(JSC::PropertyAttribute::DontEnum)); + Bun::WebStreams::installInspectCustom(vm, this, jsDOMFormDataPrototypeFunction_inspectCustom); Bun::putToStringTagWithoutTransition(vm, this, info()); } @@ -605,6 +608,33 @@ JSC_DEFINE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_forEach, (JSC::JSGlobalO return IDLOperation::call(*lexicalGlobalObject, *callFrame, "forEach"); } +// Native half of node's `[nodejs.util.inspect.custom]` method: the entries as a flat list, name, value, name, value. +JSC_DEFINE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* thisObject = Bun::WebStreams::inspectInstance(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "FormData"_s, nullptr, nullptr)); + + MarkedArgumentBuffer entries; + for (auto& entry : thisObject->wrapped().items()) { + entries.append(jsString(vm, entry.name)); + JSValue value = toJS>>>(*lexicalGlobalObject, *thisObject->globalObject(), scope, entry.data); + RETURN_IF_EXCEPTION(scope, {}); + entries.append(value); + } + if (entries.hasOverflowed()) [[unlikely]] { + throwOutOfMemoryError(lexicalGlobalObject, scope); + return {}; + } + JSArray* fields = constructArray(lexicalGlobalObject, static_cast(nullptr), entries); + RETURN_IF_EXCEPTION(scope, {}); + + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "FormData"_s, fields, thisObject)); +} + JSC::JSValue getInternalProperties(JSC::VM& vm, JSGlobalObject* lexicalGlobalObject, JSDOMFormData* castedThis) { auto throwScope = DECLARE_THROW_SCOPE(vm); diff --git a/src/jsc/bindings/webcore/JSEvent.cpp b/src/jsc/bindings/webcore/JSEvent.cpp index 51f12042b690..08ce9899d6ae 100644 --- a/src/jsc/bindings/webcore/JSEvent.cpp +++ b/src/jsc/bindings/webcore/JSEvent.cpp @@ -56,6 +56,7 @@ #include #include "ErrorCode.h" #include "NodeValidator.h" +#include "streams/WebStreamsInspectCustom.h" namespace WebCore { using namespace JSC; @@ -67,6 +68,7 @@ static JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_stopPropagation); static JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_stopImmediatePropagation); static JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_preventDefault); static JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_initEvent); +JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_inspectCustom); // Attributes @@ -229,6 +231,7 @@ void JSEventPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); Bun::reifyStaticPropertyTable(vm, JSEvent::info(), JSEventPrototypeTableValues, *this); + Bun::WebStreams::installInspectCustom(vm, this, jsEventPrototypeFunction_inspectCustom); Bun::putToStringTagWithoutTransition(vm, this, info()); } @@ -281,6 +284,28 @@ JSC_DEFINE_CUSTOM_GETTER(jsEventConstructor, (JSGlobalObject * lexicalGlobalObje return JSValue::encode(JSEvent::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); } +// Native half of node's `[nodejs.util.inspect.custom]` method: the four fields that node prints for any event. +JSC_DEFINE_HOST_FUNCTION(jsEventPrototypeFunction_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* thisObject = Bun::WebStreams::inspectInstance(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "Event"_s, nullptr, nullptr)); + + auto& impl = thisObject->wrapped(); + auto* context = thisObject->globalObject()->scriptExecutionContext(); + JSValue type = toJS(*lexicalGlobalObject, scope, impl.type()); + RETURN_IF_EXCEPTION(scope, {}); + JSObject* fields = constructEmptyObject(lexicalGlobalObject); + Bun::putDirectNamed(vm, fields, "type"_s, type); + Bun::putDirectNamed(vm, fields, "defaultPrevented"_s, jsBoolean(impl.defaultPrevented())); + Bun::putDirectNamed(vm, fields, "cancelable"_s, jsBoolean(impl.cancelable())); + Bun::putDirectNamed(vm, fields, "timeStamp"_s, context ? toJS(*lexicalGlobalObject, scope, impl.timeStampForBindings(*context)) : jsUndefined()); + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "Event"_s, fields, thisObject)); +} + static inline JSValue jsEvent_typeGetter(JSGlobalObject& lexicalGlobalObject, JSEvent& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); diff --git a/src/jsc/bindings/webcore/JSFetchHeaders.cpp b/src/jsc/bindings/webcore/JSFetchHeaders.cpp index 9ce9fd33a954..bec8ce6a36d4 100644 --- a/src/jsc/bindings/webcore/JSFetchHeaders.cpp +++ b/src/jsc/bindings/webcore/JSFetchHeaders.cpp @@ -42,6 +42,7 @@ #include "JavaScriptCore/JSCJSValue.h" #include "ScriptExecutionContext.h" #include "WebCoreJSClientData.h" +#include "streams/WebStreamsInspectCustom.h" #include #include #include @@ -75,6 +76,7 @@ static JSC_DECLARE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_forEach); // Non-standard functions static JSC_DECLARE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_toJSON); +JSC_DECLARE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_inspectCustom); static JSC_DECLARE_CUSTOM_GETTER(jsFetchHeadersPrototypeFunction_size); // Attributes @@ -320,6 +322,7 @@ void JSFetchHeadersPrototype::finishCreation(VM& vm) Base::finishCreation(vm); Bun::reifyStaticPropertyTable(vm, JSFetchHeaders::info(), JSFetchHeadersPrototypeTableValues, *this); putDirect(vm, vm.propertyNames->iteratorSymbol, getDirect(vm, vm.propertyNames->builtinNames().entriesPublicName()), static_cast(JSC::PropertyAttribute::DontEnum)); + Bun::WebStreams::installInspectCustom(vm, this, jsFetchHeadersPrototypeFunction_inspectCustom); Bun::putToStringTagWithoutTransition(vm, this, info()); } @@ -722,6 +725,40 @@ JSC::JSValue getInternalProperties(JSC::VM& vm, JSGlobalObject* lexicalGlobalObj RELEASE_AND_RETURN(throwScope, obj); } +// Native half of node's `[nodejs.util.inspect.custom]` method. As in undici, repeated values join with ", ", set-cookie too. +JSC_DEFINE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto* thisObject = Bun::WebStreams::inspectInstance(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame)); + if (!thisObject) + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "Headers"_s, nullptr, nullptr)); + + auto& internal = thisObject->wrapped().internalHeaders(); + JSObject* fields = constructEmptyObject(lexicalGlobalObject); + for (const auto& header : internal.commonHeaders()) + fields->putDirect(vm, Identifier::fromString(vm, WTF::httpHeaderNameStringImpl(header.key)), jsString(vm, header.value), 0); + + auto& cookies = internal.getSetCookieHeaders(); + if (!cookies.isEmpty()) { + StringBuilder joined; + for (size_t i = 0; i < cookies.size(); ++i) { + if (i) + joined.append(", "_s); + joined.append(cookies[i]); + } + fields->putDirect(vm, Identifier::fromString(vm, WTF::httpHeaderNameStringImpl(HTTPHeaderName::SetCookie)), jsString(vm, joined.toString()), 0); + } + + for (const auto& header : internal.uncommonHeaders()) { + fields->putDirectMayBeIndex(lexicalGlobalObject, Identifier::fromString(vm, lowercaseHeaderName(header.key)), jsString(vm, header.value)); + RETURN_IF_EXCEPTION(scope, {}); + } + + RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "Headers"_s, fields, thisObject)); +} + template void JSFetchHeaders::visitChildrenImpl(JSCell* cell, Visitor& visitor) { diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp index 7c954ba95d3a..9edc2356f39f 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp @@ -388,14 +388,9 @@ static const HashTableValue JSReadableStreamPrototypeTableValues[] = { const ClassInfo JSReadableStreamPrototype::s_info = { "ReadableStream"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSReadableStreamPrototype) }; -JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototype_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +// What node's method prints for a stream: `{ locked, state, supportsBYOB }`. +static JSObject* inspectState(VM& vm, JSGlobalObject* lexicalGlobalObject, JSReadableStream* thisObject) { - auto& vm = JSC::getVM(lexicalGlobalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - JSValue thisValue = callFrame->thisValue(); - auto* thisObject = dynamicDowncast(thisValue); - if (!thisObject) [[unlikely]] - return JSValue::encode(thisValue); JSObject* data = constructEmptyObject(lexicalGlobalObject); Bun::putDirectNamed(vm, data, "locked"_s, jsBoolean(isReadableStreamLocked(thisObject))); ASCIILiteral state; @@ -412,6 +407,27 @@ JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototype_inspectCustom, (JSGlobalObjec } Bun::putDirectNamed(vm, data, "state"_s, jsNontrivialString(vm, state)); Bun::putDirectNamed(vm, data, "supportsBYOB"_s, jsBoolean(thisObject->m_controllerKind == ControllerKind::Byte)); + return data; +} + +// For the method of a Response (node_inspect.rs). Empty for a value that is not a stream. +extern "C" EncodedJSValue Bun__ReadableStream__inspectState(JSGlobalObject* lexicalGlobalObject, EncodedJSValue encodedStream) +{ + auto* stream = dynamicDowncast(JSValue::decode(encodedStream)); + if (!stream) + return {}; + return JSValue::encode(inspectState(JSC::getVM(lexicalGlobalObject), lexicalGlobalObject, stream)); +} + +JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototype_inspectCustom, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue thisValue = callFrame->thisValue(); + auto* thisObject = dynamicDowncast(thisValue); + if (!thisObject) [[unlikely]] + return JSValue::encode(thisValue); + JSObject* data = inspectState(vm, lexicalGlobalObject, thisObject); RELEASE_AND_RETURN(scope, Bun::WebStreams::customInspect(lexicalGlobalObject, callFrame, thisValue, "ReadableStream"_s, data)); } diff --git a/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.cpp b/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.cpp index 3cb0d8daeebb..442aac4cf0fd 100644 --- a/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.cpp +++ b/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.cpp @@ -2,12 +2,22 @@ #include "WebStreamsInspectCustom.h" #include "BunClientData.h" +#include "InternalModuleRegistry.h" #include "ZigGlobalObject.h" #include #include #include +#include #include +namespace WebCore { +JSC_DECLARE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_inspectCustom); +JSC_DECLARE_HOST_FUNCTION(jsDOMFormDataPrototypeFunction_inspectCustom); +JSC_DECLARE_HOST_FUNCTION(jsAbortSignalPrototypeFunction_inspectCustom); +JSC_DECLARE_HOST_FUNCTION(jsAbortControllerPrototypeFunction_inspectCustom); +JSC_DECLARE_HOST_FUNCTION(jsEventPrototypeFunction_inspectCustom); +} + namespace Bun { namespace WebStreams { @@ -105,13 +115,126 @@ WTF::String constructorNameOf(JSGlobalObject* lexicalGlobalObject, JSValue thisV return fallback; } +// The methods that the native formatter does not call, known by the address of the host function. +static constexpr NativeFunction handWrittenNodeOnlyInspectHooks[] = { + WebCore::jsFetchHeadersPrototypeFunction_inspectCustom, + WebCore::jsDOMFormDataPrototypeFunction_inspectCustom, + WebCore::jsAbortSignalPrototypeFunction_inspectCustom, + WebCore::jsAbortControllerPrototypeFunction_inspectCustom, + WebCore::jsEventPrototypeFunction_inspectCustom, +}; + +static bool isNodeOnlyInspectHook(TaggedNativeFunction function) +{ + for (auto hook : handWrittenNodeOnlyInspectHooks) { + if (function == toTagged(hook)) + return true; + } + for (size_t i = 0; i < generatedNodeOnlyInspectHookCount; ++i) { + if (function == toTagged(generatedNodeOnlyInspectHooks[i])) + return true; + } + return false; +} + +static bool isNodeOnlyInspectHook(JSValue value) +{ + auto* function = dynamicDowncast(value); + return function && function->isHostFunction() && isNodeOnlyInspectHook(function->nativeFunction()); +} + +// For the native formatter: it does not list such a function under the method's key. +extern "C" bool Bun__isNodeOnlyInspectHook(EncodedJSValue encodedValue) +{ + return isNodeOnlyInspectHook(JSValue::decode(encodedValue)); +} + +// For the native formatter: `method`, or when that is node-only, the method that `value` has above it, or nothing. +extern "C" EncodedJSValue Bun__inspectCustomForFormatter(JSGlobalObject* globalObject, EncodedJSValue encodedValue, EncodedJSValue encodedMethod) +{ + JSValue method = JSValue::decode(encodedMethod); + if (!isNodeOnlyInspectHook(method)) + return encodedMethod; + auto& vm = JSC::getVM(globalObject); + auto& name = WebCore::builtinNames(vm).inspectCustomPublicName(); + // As the formatter's own lookup, this does not look at Object.prototype. + JSObject* objectPrototype = globalObject->objectPrototype(); + for (JSObject* object = JSValue::decode(encodedValue).getObject(); object && object != objectPrototype && object->type() != ProxyObjectType; object = object->getPrototypeDirect().getObject()) { + JSValue own = object->getDirect(vm, name); + if (own && !isNodeOnlyInspectHook(own)) + return JSValue::encode(own); + } + return {}; +} + void installInspectCustom(VM& vm, JSObject* prototype, NativeFunction nativeFunction) { auto* globalObject = prototype->globalObject(); + auto& inspectCustom = WebCore::builtinNames(vm).inspectCustomPublicName(); // Matches Node: { writable: true, enumerable: false, configurable: true }. - prototype->putDirectNativeFunction(vm, globalObject, WebCore::builtinNames(vm).inspectCustomPublicName(), 2, - nativeFunction, ImplementationVisibility::Public, NoIntrinsic, - static_cast(JSC::PropertyAttribute::DontEnum)); + auto attributes = static_cast(JSC::PropertyAttribute::DontEnum); + if (isNodeOnlyInspectHook(toTagged(nativeFunction))) { + prototype->putDirect(vm, inspectCustom, JSFunction::create(vm, globalObject, 2, "[nodejs.util.inspect.custom]"_s, nativeFunction, ImplementationVisibility::Public), attributes); + return; + } + prototype->putDirectNativeFunction(vm, globalObject, inspectCustom, 2, nativeFunction, ImplementationVisibility::Public, NoIntrinsic, attributes); +} + +JSObject* inspectHolder(JSGlobalObject* globalObject, CallFrame* callFrame) +{ + JSObject* object = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).getObject(); + while (object && object->type() == ProxyObjectType) { + auto* proxy = uncheckedDowncast(object); + if (proxy->isRevoked()) + return nullptr; + object = proxy->target(); + } + return object; +} + +JSObject* findInspectInstance(JSObject* holder, const ClassInfo* info) +{ + for (JSObject* object = holder; object && object->type() != ProxyObjectType; object = object->getPrototypeDirect().getObject()) { + if (object->inherits(info)) + return object; + } + return nullptr; +} + +EncodedJSValue inspectFields(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame, ASCIILiteral tag, JSObject* fields, JSObject* instance) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + + // A bare call passes a scope object as `this`. It must not reach script. + JSValue self = callFrame->thisValue().toThis(lexicalGlobalObject, ECMAMode::strict()); + RETURN_IF_EXCEPTION(scope, {}); + JSObject* holder = inspectHolder(lexicalGlobalObject, callFrame); + + auto* globalObject = defaultGlobalObject(lexicalGlobalObject); + JSValue inspectHook = globalObject->internalModuleRegistry()->requireId(globalObject, vm, InternalModuleRegistry::Field::InternalUtilInspectHooks); + RETURN_IF_EXCEPTION(scope, {}); + + MarkedArgumentBuffer arguments; + arguments.append(jsString(vm, WTF::String(tag))); + arguments.append(self); + arguments.append(callFrame->argument(0)); + arguments.append(callFrame->argument(1)); + arguments.append(fields ? JSValue(fields) : jsUndefined()); + arguments.append(holder ? JSValue(holder) : jsUndefined()); + arguments.append(instance ? JSValue(instance) : jsUndefined()); + arguments.append(callFrame->jsCallee()); + ASSERT(!arguments.hasOverflowed()); + + JSValue result = JSC::profiledCall(lexicalGlobalObject, ProfilingReason::API, inspectHook, JSC::getCallData(inspectHook), jsUndefined(), arguments); + RETURN_IF_EXCEPTION(scope, {}); + return JSValue::encode(result); +} + +// For the readers of the classes in *.classes.ts files (src/runtime/webcore/node_inspect.rs). +extern "C" EncodedJSValue Bun__inspectFields(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame, EncodedJSValue encodedInstance, EncodedJSValue encodedFields, const char* tag) +{ + return inspectFields(lexicalGlobalObject, callFrame, ASCIILiteral::fromLiteralUnsafe(tag), asObject(JSValue::decode(encodedFields)), asObject(JSValue::decode(encodedInstance))); } } // namespace WebStreams diff --git a/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.h b/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.h index 34f9a04d4de1..ce2e11fe8d48 100644 --- a/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.h +++ b/src/jsc/bindings/webcore/streams/WebStreamsInspectCustom.h @@ -22,5 +22,22 @@ WTF::String constructorNameOf(JSC::JSGlobalObject*, JSC::JSValue thisValue, ASCI // Installs the host function on a prototype under Symbol.for("nodejs.util.inspect.custom"). void installInspectCustom(JSC::VM&, JSC::JSObject* prototype, JSC::NativeFunction); +// Methods with a native half, which copies native state, and a JS half: internal/util/inspect_hooks. + +// The native formatter (ConsoleObject.rs) does not call or list them. These are the ones from *.classes.ts files. +extern const JSC::NativeFunction generatedNodeOnlyInspectHooks[]; +extern const size_t generatedNodeOnlyInspectHookCount; + +// `this` as a method sees it (undefined for a bare call), or the target when that is a Proxy. Null when not an object. +JSC::JSObject* inspectHolder(JSC::JSGlobalObject*, JSC::CallFrame*); +// The first instance of the class on the prototype chain of `holder`, found with no user code. A Proxy ends the search. +JSC::JSObject* findInspectInstance(JSC::JSObject* holder, const JSC::ClassInfo*); +template JSClass* inspectInstance(JSC::JSObject* holder) +{ + return static_cast(findInspectInstance(holder, JSClass::info())); +} +// Calls the JS half with `fields`, the state of `instance`. Both are null when the receiver holds no instance. +JSC::EncodedJSValue inspectFields(JSC::JSGlobalObject*, JSC::CallFrame*, ASCIILiteral tag, JSC::JSObject* fields, JSC::JSObject* instance); + } // namespace WebStreams } // namespace Bun diff --git a/src/runtime/generated_classes.rs b/src/runtime/generated_classes.rs index 69979de0cd28..f95c8d30c12d 100644 --- a/src/runtime/generated_classes.rs +++ b/src/runtime/generated_classes.rs @@ -46,5 +46,7 @@ use crate::webcore::body::BodyMixin; // emits `Blob::get_text(&mut *this, …)` UFCS, so the trait must be in scope // by name here for those calls to resolve. use crate::webcore::blob::BlobExt; +// And for `Blob::inspect_custom`, the reader behind `inspectCustom: true`. +use crate::webcore::node_inspect::BlobInspect; include!(concat!(env!("BUN_CODEGEN_DIR"), "/generated_classes.rs")); diff --git a/src/runtime/node/node.classes.ts b/src/runtime/node/node.classes.ts index 25729cccbac5..5b87448b2d7f 100644 --- a/src/runtime/node/node.classes.ts +++ b/src/runtime/node/node.classes.ts @@ -132,6 +132,7 @@ export default [ refCounted: true, sharedThis: true, configurable: false, + inspectCustom: true, klass: {}, JSType: "0b11101110", proto: { diff --git a/src/runtime/socket/SocketAddress.rs b/src/runtime/socket/SocketAddress.rs index c24337cd8e89..6f8b43453c91 100644 --- a/src/runtime/socket/SocketAddress.rs +++ b/src/runtime/socket/SocketAddress.rs @@ -3,7 +3,6 @@ //! JS getters are named `getFoo`, while native getters are named `foo`. //! //! TODO: add a inspect method (under `Symbol.for("nodejs.util.inspect.custom")`). -//! Requires updating bindgen. use core::ffi::{c_int, c_void}; use core::mem; diff --git a/src/runtime/test_runner/pretty_format.rs b/src/runtime/test_runner/pretty_format.rs index 9ba2de15ff60..db2a9400fb8b 100644 --- a/src/runtime/test_runner/pretty_format.rs +++ b/src/runtime/test_runner/pretty_format.rs @@ -908,7 +908,9 @@ impl<'a, 'f, W: bun_io::Write, const ENABLE_ANSI_COLORS: bool> // SAFETY: key_ is non-null per JSC contract for property iteration. let key = unsafe { *key_ }; - if key.eq_ascii(b"constructor") { + if key.eq_ascii(b"constructor") + || bun_jsc::console_object::formatter::is_unlisted_inspect_method(&key, is_symbol, value) + { return; } diff --git a/src/runtime/timer/TimeoutObject.rs b/src/runtime/timer/TimeoutObject.rs index ee70bde4217a..4e24b4901ea1 100644 --- a/src/runtime/timer/TimeoutObject.rs +++ b/src/runtime/timer/TimeoutObject.rs @@ -40,6 +40,39 @@ impl TimeoutObject { Ok(frame.this()) } + /// Native half of node's `[nodejs.util.inspect.custom]` method: what the getters give, in node's order. + pub(crate) fn inspect_custom( + this: &Self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult { + let slot = |value: Option| value.unwrap_or(JSValue::UNDEFINED); + let fields = JSValue::create_empty_object(global, 5); + fields.put( + global, + b"_idleTimeout", + slot(js::idle_timeout_get_cached(this_value)), + ); + fields.put( + global, + b"_idleStart", + slot(js::idle_start_get_cached(this_value)), + ); + fields.put( + global, + b"_onTimeout", + slot(js::callback_get_cached(this_value)), + ); + fields.put(global, b"_repeat", slot(js::repeat_get_cached(this_value))); + fields.put( + global, + b"_destroyed", + JSValue::from(this.internals.get_destroyed()), + ); + crate::webcore::node_inspect::print(global, callframe, this_value, fields, c"Timeout") + } + // Cached-property getters/setters — codegen passes `this_value` (the JS // wrapper) so the cached `WriteBarrier` slot on the C++ side can be read/written. // Signature does not match the standard `host_fn(getter/setter)` shape; the diff --git a/src/runtime/webcore.rs b/src/runtime/webcore.rs index b5fe603a2ab3..0a3867dd5c78 100644 --- a/src/runtime/webcore.rs +++ b/src/runtime/webcore.rs @@ -220,6 +220,9 @@ pub(crate) use response::Response; pub(crate) mod request; pub(crate) use request::Request; +#[path = "webcore/node_inspect.rs"] +pub(crate) mod node_inspect; + #[path = "webcore/ReadableStream.rs"] pub(crate) mod readable_stream; pub(crate) use readable_stream::ReadableStream; diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index 0481df6636cc..be51989a780a 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -1986,18 +1986,10 @@ impl BlobExt for Blob { if last_modified == jsc::INIT_TIMESTAMP && !self.is_s3() { resolve_file_stat(store); } - // Fresh borrow after possible mutation by `resolve_file_stat`. - return JSValue::js_number(JSValue::purify_nan( - Store::data_mut(store).as_file().last_modified as f64, - )); } } - if self.is_jsdom_file.get() { - return JSValue::js_number(JSValue::purify_nan(self.last_modified.get())); - } - - JSValue::js_number(jsc::INIT_TIMESTAMP as f64) + last_modified_if_known(self).unwrap_or(JSValue::js_number(jsc::INIT_TIMESTAMP as f64)) } fn get_size_for_bindings(&self) -> u64 { @@ -5793,6 +5785,49 @@ fn window_size(current: SizeType, available: SizeType) -> SizeType { } } +/// What the `size` getter gives, when that needs no `stat` and no request. For `inspect_custom`. +pub(crate) fn size_if_known(blob: &Blob) -> Option { + let size = blob.size.get(); + let Some(store) = blob.store.get() else { + return Some(if size == MAX_SIZE { 0 } else { size }); + }; + match Store::data_mut(store).tag() { + store::DataTag::Bytes => Some(if size == MAX_SIZE { + blob.resolved_size().1 + } else { + size + }), + store::DataTag::File => { + let file = Store::data_mut(store).as_file(); + if file.seekable.is_none() || file.max_size == MAX_SIZE { + return None; + } + if size == MAX_SIZE { + // `seekable` is known, so this does no `stat`. + Some(blob.resolved_size().1) + } else { + (size <= file.max_size).then_some(size) + } + } + store::DataTag::S3 => None, + } +} + +/// What the `lastModified` getter gives, when that needs no `stat`. For `inspect_custom`. +pub(crate) fn last_modified_if_known(blob: &Blob) -> Option { + if let Some(store) = blob.store.get() { + if matches!(store.data, store::Data::File(_)) { + let last_modified = Store::data_mut(store).as_file().last_modified; + return (last_modified != jsc::INIT_TIMESTAMP) + .then(|| JSValue::js_number(JSValue::purify_nan(last_modified as f64))); + } + } + + blob.is_jsdom_file + .get() + .then(|| JSValue::js_number(JSValue::purify_nan(blob.last_modified.get()))) +} + /// resolve file stat like size, last_modified fn resolve_file_stat(store: &RefPtr) { // `Store::data_mut` encapsulates the raw-pointer deref under the diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index ca3ae8efdc8f..756f7abb161d 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -243,19 +243,26 @@ impl Request { &self, global_this: &JSGlobalObject, ) -> JsResult<&mut HeadersRef> { - if self.headers.get().is_some() { - // headers is already set - return Ok(self.headers_mut().as_mut().unwrap()); + if self.headers.get().is_none() { + let headers = self.default_fetch_headers(global_this)?; + self.headers.set(Some(headers)); } + Ok(self.headers_mut().as_mut().unwrap()) + } + + /// What [`Self::ensure_fetch_headers`] attaches to a Request that has no header list, not attached. + pub(crate) fn default_fetch_headers( + &self, + global_this: &JSGlobalObject, + ) -> JsResult { + let mut headers; if let Some(req) = self.request_context.get_request() { // we have a request context, so we can get the headers from it - self.headers.set(Some(HeadersRef::create_from_uws( - req.cast::(), - ))); + headers = HeadersRef::create_from_uws(req.cast::()); } else { // we don't have a request context, so we need to create an empty headers object - self.headers.set(Some(HeadersRef::create_empty())); + headers = HeadersRef::create_empty(); // Snapshot the pointer first; it stays valid across the field borrow. let content_type: Option<*const [u8]> = match self.body_value() { BodyValue::Blob(blob) => { @@ -282,7 +289,7 @@ impl Request { // call; the bytes are copied into the header map below. let content_type_ = unsafe { &*content_type_ }; if !content_type_.is_empty() { - self.headers_mut().as_mut().unwrap().put( + headers.put( HTTPHeaderName::ContentType, &BunString::ascii(content_type_), global_this, @@ -291,7 +298,7 @@ impl Request { } } - Ok(self.headers_mut().as_mut().unwrap()) + Ok(headers) } pub(crate) fn get_fetch_headers_unless_empty(&self) -> Option<&mut HeadersRef> { diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index cfb5970bc8fd..ba4fe99e4d92 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -576,6 +576,24 @@ impl Response { JSValue::js_number(this.init.get().status_code as f64) } + /// What [`Self::get_or_create_headers`] attaches to a Response that has no header list, not attached. + pub(crate) fn default_headers(&self, global_this: &JSGlobalObject) -> JsResult { + let mut headers = HeadersRef::create_empty(); + + if let BodyValue::Blob(blob) = self.body.get().value.get() { + let content_type = blob.content_type_slice(); + if !content_type.is_empty() { + headers.put( + HTTPHeaderName::ContentType, + &BunString::ascii(content_type), + global_this, + )?; + } + } + + Ok(headers) + } + pub(crate) fn get_or_create_headers( &self, global_this: &JSGlobalObject, @@ -583,23 +601,12 @@ impl Response { // R-2 escape hatch via `init_mut()` — the returned `&mut HeadersRef` // borrows `self.init`; callers (`get_headers`, `construct_*`) do not // hold the borrow across calls that re-enter Response host-fns. - let init = self.init_mut(); - if init.headers.is_none() { - init.headers = Some(HeadersRef::create_empty()); - - if let BodyValue::Blob(blob) = self.body.get().value.get() { - let content_type = blob.content_type_slice(); - if !content_type.is_empty() { - init.headers.as_mut().unwrap().put( - HTTPHeaderName::ContentType, - &BunString::ascii(content_type), - global_this, - )?; - } - } + if self.init.get().headers.is_none() { + let headers = self.default_headers(global_this)?; + self.init_mut().headers = Some(headers); } - Ok(init.headers.as_mut().unwrap()) + Ok(self.init_mut().headers.as_mut().unwrap()) } pub(crate) fn get_headers(this: &Self, global_this: &JSGlobalObject) -> JsResult { diff --git a/src/runtime/webcore/TextDecoder.rs b/src/runtime/webcore/TextDecoder.rs index 0d51a10b1502..c65cbd5e5a46 100644 --- a/src/runtime/webcore/TextDecoder.rs +++ b/src/runtime/webcore/TextDecoder.rs @@ -100,6 +100,20 @@ impl TextDecoder { self.encoding.to_js(global_this) } + /// Native half of node's `[nodejs.util.inspect.custom]` method: the fields that node prints. + pub(crate) fn inspect_custom( + &self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult { + let fields = JSValue::create_empty_object(global, 3); + fields.put(global, b"encoding", self.encoding.to_js(global)); + fields.put(global, b"fatal", JSValue::js_boolean(self.fatal)); + fields.put(global, b"ignoreBOM", JSValue::js_boolean(self.ignore_bom)); + crate::webcore::node_inspect::print(global, callframe, this_value, fields, c"TextDecoder") + } + #[inline(always)] fn process_code_unit_utf16( &self, diff --git a/src/runtime/webcore/encoding.classes.ts b/src/runtime/webcore/encoding.classes.ts index 453caae67af0..a04ba205f125 100644 --- a/src/runtime/webcore/encoding.classes.ts +++ b/src/runtime/webcore/encoding.classes.ts @@ -7,6 +7,7 @@ export default [ finalize: true, JSType: "0b11101110", configurable: false, + inspectCustom: true, klass: {}, proto: { encoding: { diff --git a/src/runtime/webcore/node_inspect.rs b/src/runtime/webcore/node_inspect.rs new file mode 100644 index 000000000000..44aa4893de6b --- /dev/null +++ b/src/runtime/webcore/node_inspect.rs @@ -0,0 +1,188 @@ +//! Native halves of node's `[nodejs.util.inspect.custom]` method for `Response`, `Request` and `Blob`. + +use core::ffi::{CStr, c_char}; + +use bun_core::String as BunString; +use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult, StringJsc as _}; + +use super::blob::{Blob, BlobExt as _, last_modified_if_known, size_if_known}; +use super::body::{BodyMixin, Value as BodyValue}; +use super::{AbortSignal, Request, Response}; +use crate::generated_classes::{js_Blob, js_Request, js_Response}; + +unsafe extern "C" { + fn Bun__inspectFields( + global: &JSGlobalObject, + callframe: &CallFrame, + instance: JSValue, + fields: JSValue, + tag: *const c_char, + ) -> JSValue; + /// `{ locked, state, supportsBYOB }` of a ReadableStream. Empty for another value. + safe fn Bun__ReadableStream__inspectState(global: &JSGlobalObject, stream: JSValue) -> JSValue; +} + +/// Gives `fields`, the state of `instance`, to the `case` for `tag` in `inspect_hooks.ts`, which returns the text. +pub(crate) fn print( + global: &JSGlobalObject, + callframe: &CallFrame, + instance: JSValue, + fields: JSValue, + tag: &'static CStr, +) -> JsResult { + // SAFETY: `tag` is a NUL-terminated `'static` string. `instance` and `fields` are objects. + bun_jsc::from_js_host_call(global, || unsafe { + Bun__inspectFields(global, callframe, instance, fields, tag.as_ptr()) + }) +} + +/// The `body` that a reader can show without making a stream: `null`, or the state of a stream that exists. +fn existing_body( + global: &JSGlobalObject, + cached: Option, + owner: &Response, +) -> Option { + let stream = match cached { + Some(body) if body.is_null() => return Some(JSValue::NULL), + Some(body) => body, + None => match owner.get_body_readable_stream() { + Some(stream) => stream.value, + None => { + return matches!(owner.get_body_value(), BodyValue::Null).then_some(JSValue::NULL); + } + }, + }; + let state = Bun__ReadableStream__inspectState(global, stream); + (!state.is_empty()).then_some(state) +} + +impl Response { + /// undici: `{ status, statusText, headers, body, bodyUsed, ok, redirected, type, url }`. + pub(crate) fn inspect_custom( + &self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult { + let headers = match js_Response::headers_get_cached(this_value) { + Some(headers) => headers, + None => match self.get_init_headers_mut() { + Some(headers) => headers.to_js(global), + None => self.default_headers(global)?.to_js(global), + }, + }; + let status_text = match js_Response::status_text_get_cached(this_value) { + Some(status_text) => status_text, + None => Self::get_status_text(self, global)?, + }; + let url = match js_Response::url_get_cached(this_value) { + Some(url) => url, + None => Self::get_url(self, global)?, + }; + let fields = JSValue::create_empty_object(global, 9); + fields.put(global, b"status", Self::get_status(self, global)); + fields.put(global, b"statusText", status_text); + fields.put(global, b"headers", headers); + if let Some(body) = existing_body(global, js_Response::body_get_cached(this_value), self) { + fields.put(global, b"body", body); + } + fields.put(global, b"bodyUsed", self.get_body_used(global)); + fields.put(global, b"ok", JSValue::from(self.is_ok())); + fields.put(global, b"redirected", Self::get_redirected(self, global)); + fields.put(global, b"type", Self::get_response_type(self, global)?); + fields.put(global, b"url", url); + print(global, callframe, this_value, fields, c"Response") + } +} + +impl Request { + /// The fields that undici prints. A reader attaches no header list and keeps no URL and no signal. + pub(crate) fn inspect_custom( + &self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult { + let headers = match js_Request::headers_get_cached(this_value) { + Some(headers) => headers, + None if self.has_fetch_headers() => self.get_headers(global)?, + None => self.default_fetch_headers(global)?.to_js(global), + }; + // The `url` getter of a served Request builds the URL and keeps it. This builds it and takes it back. + let url = match js_Request::url_get_cached(this_value) { + Some(url) => url, + None if self.url.get().is_empty() => { + self.ensure_url()?; + self.url.replace(BunString::EMPTY).to_js(global)? + } + None => self.url.get().to_js(global)?, + }; + // `referrer` is a header lookup, and that call can throw without a sentinel value. + let referrer = bun_jsc::call_check_slow(global, || self.get_referrer(global))?; + // The `signal` getter makes a signal and keeps it. This one is not kept. + let signal = match self.abort_signal() { + Some(signal) => signal.to_js(global), + None => AbortSignal::create(global), + }; + let fields = JSValue::create_empty_object(global, 12); + fields.put(global, b"method", self.get_method(global)); + fields.put(global, b"url", url); + fields.put(global, b"headers", headers); + fields.put(global, b"destination", Self::get_destination(self, global)); + fields.put(global, b"referrer", referrer); + fields.put( + global, + b"referrerPolicy", + Self::get_referrer_policy(self, global), + ); + fields.put(global, b"mode", self.get_mode(global)); + fields.put(global, b"credentials", Self::get_credentials(self, global)); + fields.put(global, b"cache", self.get_cache(global)); + fields.put(global, b"redirect", self.get_redirect(global)); + fields.put(global, b"integrity", Self::get_integrity(self, global)); + fields.put(global, b"signal", signal); + print(global, callframe, this_value, fields, c"Request") + } +} + +/// `Blob` is a `bun_jsc` type, so its reader is a trait method, like the rest of [`BlobExt`]. +pub(crate) trait BlobInspect { + fn inspect_custom( + &self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult; +} + +impl BlobInspect for Blob { + /// A File shares this prototype. A size or a time that needs a `stat` or a request is left out. + fn inspect_custom( + &self, + global: &JSGlobalObject, + callframe: &CallFrame, + this_value: JSValue, + ) -> JsResult { + let is_file = self.is_jsdom_file.get(); + let fields = JSValue::create_empty_object(global, 4); + if let Some(size) = size_if_known(self) { + fields.put(global, b"size", JSValue::js_number(size as f64)); + } + fields.put(global, b"type", self.get_type(global)); + if is_file { + let name = match js_Blob::name_get_cached(this_value) { + Some(name) => name, + None => match self.get_name_string() { + Some(name) => name.to_js(global)?, + None => JSValue::UNDEFINED, + }, + }; + fields.put(global, b"name", name); + if let Some(last_modified) = last_modified_if_known(self) { + fields.put(global, b"lastModified", last_modified); + } + } + let tag = if is_file { c"File" } else { c"Blob" }; + print(global, callframe, this_value, fields, tag) + } +} diff --git a/src/runtime/webcore/response.classes.ts b/src/runtime/webcore/response.classes.ts index 420ca221087b..0c19510107d5 100644 --- a/src/runtime/webcore/response.classes.ts +++ b/src/runtime/webcore/response.classes.ts @@ -13,6 +13,7 @@ export default [ JSType: "0b11101110", estimatedSize: true, configurable: false, + inspectCustom: true, overridesToJS: true, memoryCost: true, values: ["stream"], @@ -80,6 +81,7 @@ export default [ final: false, JSType: "0b11101110", configurable: false, + inspectCustom: true, estimatedSize: true, overridesToJS: true, klass: { @@ -146,6 +148,7 @@ export default [ JSType: "0b11101110", klass: {}, configurable: false, + inspectCustom: true, structuredClone: { transferable: false, tag: 254, diff --git a/test/internal/source-lints/redis-client-types.test.ts b/test/internal/source-lints/redis-client-types.test.ts index a320d8f5f6fd..91b0ddc95b55 100644 --- a/test/internal/source-lints/redis-client-types.test.ts +++ b/test/internal/source-lints/redis-client-types.test.ts @@ -42,7 +42,8 @@ for (const [table, prefix] of [ for (const [name, field] of Object.entries(table)) { // Installed under a private name or a Symbol.for() symbol, or (internal) // not installed at all; none of these has a declaration to mirror. - if ("internal" in field || "privateSymbol" in field || "publicSymbol" in field) continue; + if ("internal" in field || "privateSymbol" in field) continue; + if (name === "inspectCustom" && definition.inspectCustom) continue; registered.add(prefix + name); } } diff --git a/test/js/node/test/parallel/test-events-customevent.js b/test/js/node/test/parallel/test-events-customevent.js index 0cf36aa91cc5..53af44cb20c8 100644 --- a/test/js/node/test/parallel/test-events-customevent.js +++ b/test/js/node/test/parallel/test-events-customevent.js @@ -310,11 +310,10 @@ const { inspect } = require('node:util'); { const ev = new CustomEvent('test'); - // TODO: unskip - // const evConstructorName = inspect(ev, { - // depth: -1, - // }); - // strictEqual(evConstructorName, 'CustomEvent'); + const evConstructorName = inspect(ev, { + depth: -1, + }); + strictEqual(evConstructorName, 'CustomEvent'); const inspectResult = inspect(ev, { depth: 1, diff --git a/test/js/node/test/parallel/test-eventtarget.js b/test/js/node/test/parallel/test-eventtarget.js index 6dac98e29ce5..dadd2b846321 100644 --- a/test/js/node/test/parallel/test-eventtarget.js +++ b/test/js/node/test/parallel/test-eventtarget.js @@ -649,11 +649,7 @@ if (typeof Bun === "undefined") { // Node internal const evConstructorName = inspect(ev, { depth: -1, }); - if (typeof Bun === "undefined") { - strictEqual(evConstructorName, 'Event'); - } else { - strictEqual(evConstructorName, '[Event]'); - } + strictEqual(evConstructorName, 'Event'); const inspectResult = inspect(ev, { depth: 1, diff --git a/test/js/node/util/custom-inspect.test.js b/test/js/node/util/custom-inspect.test.js index f39d2e0a6d39..5e6991962d71 100644 --- a/test/js/node/util/custom-inspect.test.js +++ b/test/js/node/util/custom-inspect.test.js @@ -1,6 +1,8 @@ // this file is compatible with jest to test node.js' util.inspect as well as bun's const util = require("util"); +const { join } = require("node:path"); +const { bunEnv, bunExe, tempDir } = process.versions.bun ? require("harness") : {}; test("util.inspect.custom exists", () => { expect(util.inspect.custom).toEqual(Symbol.for("nodejs.util.inspect.custom")); @@ -331,3 +333,635 @@ describe("Web Streams [nodejs.util.inspect.custom]", () => { expect(inspect(globalThis[className].prototype)).toContain("encoding: [Getter]"); }); }); + +// What is Bun's own about node's method on the web classes. inspect-web-classes.test.ts has the text that node prints. +(process.versions.bun ? describe : describe.skip)("web classes [nodejs.util.inspect.custom]", () => { + const inspect = util.inspect; + const flat = value => inspect(value, { breakLength: Infinity }); + function onTimeout() {} + const make = { + Headers: () => new Headers({ "x-request-id": "abc123" }), + Response: () => new Response("nope", { status: 404, headers: { "x-request-id": "abc123" } }), + Request: () => new Request("http://127.0.0.1:1/users?id=7", { method: "POST", body: "x" }), + Blob: () => new Blob(["hello"], { type: "text/csv" }), + File: () => new File(["hello"], "report.csv", { type: "text/csv", lastModified: 5 }), + FormData: () => { + const form = new FormData(); + form.append("user", "ada"); + return form; + }, + AbortSignal: () => AbortSignal.abort("why"), + AbortController: () => new AbortController(), + Event: () => new Event("ping"), + TextDecoder: () => new TextDecoder("utf-16le"), + Timeout: () => setTimeout(onTimeout, 50), + }; + const rows = Object.entries(make); + const withValue = (create, use) => { + const value = create(); + try { + return use(value); + } finally { + if (create === make.Timeout) clearTimeout(value); + } + }; + const run = async script => { + await using proc = Bun.spawn({ cmd: [bunExe(), "-e", script], env: bunEnv, stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; + }; + + describe("the native console keeps its text", () => { + test("Bun.inspect prints what it printed before the classes had the method", () => { + const text = Object.fromEntries( + rows.map(([name, create]) => [name, withValue(create, value => Bun.inspect(value))]), + ); + expect(text).toEqual({ + Headers: 'Headers {\n "x-request-id": "abc123",\n}', + Response: + 'Response (4 bytes) {\n ok: false,\n url: "",\n status: 404,\n statusText: "",\n headers: Headers {\n "x-request-id": "abc123",\n },\n redirected: false,\n bodyUsed: false,\n Blob (4 bytes)\n}', + Request: + 'Request (1 bytes) {\n method: "POST",\n url: "http://127.0.0.1:1/users?id=7",\n headers: Headers {}\n Blob (1 bytes)\n}', + Blob: 'Blob (5 bytes) {\n type: "text/csv"\n}', + File: 'File (5 bytes) {\n name: "report.csv",\n type: "text/csv",\n lastModified: 5\n}', + FormData: 'FormData {\n "user": "ada",\n}', + AbortSignal: expect.stringContaining('AbortSignal {\n aborted: true,\n reason: "why",\n onabort: null,'), + AbortController: expect.stringContaining("AbortController {\n signal: AbortSignal {\n aborted: false,"), + Event: expect.stringContaining('Event {\n isTrusted: false,\n type: "ping",'), + TextDecoder: + 'TextDecoder {\n decode: [Function: decode],\n encoding: "utf-16le",\n fatal: false,\n ignoreBOM: false,\n}', + Timeout: expect.stringMatching(/^Timeout \(#\d+\)$/), + }); + // No text names the method. + expect(Object.values(text).filter(value => value.includes("inspect.custom"))).toEqual([]); + }); + + test("a prototype is listed without the method, by Bun.inspect and by the printer of bun:test", () => { + expect(Bun.inspect(Blob.prototype)).not.toContain("inspect.custom"); + expect([AbortController.prototype, TextDecoder.prototype]).toMatchInlineSnapshot(` + [ + AbortController AbortController { + "abort": [Function: abort], + "signal": undefined, + }, + TextDecoder TextDecoder { + "decode": [Function: decode], + "encoding": undefined, + "fatal": undefined, + "ignoreBOM": undefined, + }, + ] + `); + }); + + test("one of the methods under another key is listed as any function", () => { + const method = Blob.prototype[customSymbol]; + expect(Bun.inspect({ method, [Symbol("nodejs.util.inspect.custom")]: 1 })).toBe( + "{\n method: [Function: [nodejs.util.inspect.custom]],\n [Symbol(nodejs.util.inspect.custom)]: 1,\n}", + ); + }); + + test("a method that a program put on the value, or on a prototype above, is called", () => { + const own = new Blob(["x"]); + own[customSymbol] = () => "own method"; + class Logged extends Response { + [customSymbol]() { + return "subclass method"; + } + } + const signal = AbortSignal.abort(); + EventTarget.prototype[customSymbol] = () => "EventTarget method"; + try { + expect([Bun.inspect(own), Bun.inspect(new Logged(null)), Bun.inspect(signal)]).toEqual([ + "own method", + "subclass method", + "EventTarget method", + ]); + } finally { + delete EventTarget.prototype[customSymbol]; + } + // Object.prototype is not a place where the console looks for the method. + Object.prototype[customSymbol] = () => "Object method"; + try { + expect(Bun.inspect(signal)).toStartWith("AbortSignal {"); + } finally { + delete Object.prototype[customSymbol]; + } + }); + + test("a method of a program that passes a Response to its inspect argument prints the state", () => { + const wrapper = { + response: new Response(null, { status: 404 }), + [customSymbol](depth, options, inspect) { + return `Wrapper ${inspect(this.response, { ...options, breakLength: Infinity, colors: false })}`; + }, + }; + expect(Bun.inspect(wrapper)).toBe( + "Wrapper Response { status: 404, statusText: '', headers: Headers {}, body: null, bodyUsed: false, ok: false, redirected: false, type: 'default', url: '' }", + ); + }); + }); + + describe("the native half runs no code of the program", () => { + test("no getter of the class runs", () => { + const names = { + Headers: [], + Response: ["status", "statusText", "headers", "body", "bodyUsed", "ok", "redirected", "type", "url"], + Request: ["method", "url", "headers", "referrer", "mode", "credentials", "cache", "redirect", "signal"], + Blob: ["size", "type", "name", "lastModified"], + File: ["size", "type", "name", "lastModified"], + FormData: [], + AbortSignal: ["aborted"], + AbortController: ["signal"], + Event: ["type", "defaultPrevented", "cancelable", "timeStamp"], + TextDecoder: ["encoding", "fatal", "ignoreBOM"], + // A timer prints its own properties, so an accessor on it is part of its text. + Timeout: [], + }; + for (const [name, create] of rows) { + withValue(create, value => { + const before = inspect(value); + let calls = 0; + // A getter on the value hides the one of the class. Neither half reads it. + for (const key of names[name]) { + Object.defineProperty(value, key, { get: () => (calls++, undefined), configurable: true }); + } + expect({ name, text: inspect(value), calls }).toEqual({ name, text: before, calls: 0 }); + }); + } + }); + + test("a FormData and a Headers print their entries with setters of those names on Object.prototype", () => { + const form = new FormData(); + form.append("user", "ada"); + form.append("user", "bob"); + const headers = new Headers({ user: "ada" }); + let calls = 0; + Object.defineProperty(Object.prototype, "user", { set: () => void calls++, configurable: true }); + try { + expect([inspect(form), inspect(headers), calls]).toEqual([ + "FormData { user: [ 'ada', 'bob' ] }", + "Headers { user: 'ada' }", + 0, + ]); + } finally { + delete Object.prototype.user; + } + }); + + test("an option with an index key is an option like any other", () => { + const event = new Event("ping"); + expect( + [ + make.Blob(), + make.File(), + AbortSignal.abort(), + new AbortController(), + event, + new Response(new ReadableStream()), + ].map(value => inspect(value, { 0: 1, breakLength: Infinity })), + ).toEqual([ + "Blob { size: 5, type: 'text/csv' }", + "File { size: 5, type: 'text/csv', name: 'report.csv', lastModified: 5 }", + "AbortSignal { aborted: true }", + "AbortController { signal: AbortSignal { aborted: false } }", + `Event { type: 'ping', defaultPrevented: false, cancelable: false, timeStamp: ${event.timeStamp} }`, + "Response { status: 200, statusText: '', headers: Headers {}, body: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }, bodyUsed: false, ok: true, redirected: false, type: 'default', url: '' }", + ]); + }); + + test("the method does not go through the inspect export of node:util", () => { + const exported = util.inspect; + try { + util.inspect = 4; + expect(util.format("%O", make.Blob())).toBe("Blob { size: 5, type: 'text/csv' }"); + } finally { + util.inspect = exported; + } + }); + + test("a property named body on Object.prototype is not the body of a Request or a Response", () => { + const request = new Request("http://127.0.0.1:1/"); + const response = new Response("x"); + const before = [flat(request), flat(response)]; + Object.defineProperty(Object.prototype, "body", { value: "polluted", configurable: true }); + try { + expect([flat(request), flat(response)]).toEqual(before); + } finally { + delete Object.prototype.body; + } + }); + + test.concurrent("the methods do not read the globals Blob and File", async () => { + const { stdout, exitCode } = await run(` + const util = require("node:util"); + const file = new File(["x"], "a.txt", { lastModified: 5 }); + const headers = new Headers({ a: "1" }); + delete globalThis.Blob; + globalThis.File = class File {}; + console.log(util.inspect(headers)); + console.log(util.inspect({ it: file }, { depth: 0 })); + console.log(util.inspect(file)); + `); + expect({ stdout, exitCode }).toEqual({ + stdout: "Headers { a: '1' }\n{ it: [File] }\nFile { size: 1, type: '', name: 'a.txt', lastModified: 5 }\n", + exitCode: 0, + }); + }); + + test.concurrent("a stack overflow in the method is an error, not a crash", async () => { + // Every sixteenth level tries a print on the way back from the deepest call. `probe` runs after the others. + const { stdout, exitCode } = await run(` + const util = require("node:util"); + let ran = 0; + let level = 0; + const probe = { [util.inspect.custom]: () => (ran++, "probe") }; + const values = [new Blob(["x"]), new File(["x"], "a"), new TextDecoder(), AbortSignal.abort(), new Response(null)]; + function recurse() { + level++; + try { + recurse(); + } catch {} + level--; + if (level % 16 === 0 && ran < 2) { + try { + util.inspect([...values, probe], { depth: 0 }); + } catch {} + } + } + recurse(); + console.log(ran); + console.log(util.inspect({ it: values }, { depth: 1, breakLength: Infinity })); + `); + expect({ stdout, exitCode }).toEqual({ + stdout: + "2\n" + + "{ it: [ [Blob], [File], [TextDecoder], [AbortSignal], Response { status: 200, statusText: '', " + + "headers: Headers {}, body: null, bodyUsed: false, ok: true, redirected: false, type: 'default', url: '' } ] }\n", + exitCode: 0, + }); + }); + }); + + // Each method starts a new util.inspect, so the methods hand on which values they print. + describe("a value that holds itself in a field that its method prints", () => { + class Envelope { + constructor(value) { + this.value = value; + } + } + + test("is [Circular] where the depth does not count down", () => { + class ApiResponse extends Response { + body = new Envelope(this); + } + const controller = new AbortController(); + Object.defineProperty(controller, "signal", { value: controller }); + const decoder = new TextDecoder(); + Object.defineProperty(decoder, "encoding", { value: [decoder] }); + // A Proxy around the value is the same value. + const request = new Request("http://127.0.0.1:1/"); + Object.defineProperty(request, "signal", { value: new Proxy(request, {}) }); + expect([ + flat(new ApiResponse(null)), + inspect(controller, { depth: null }), + inspect(controller, { depth: Infinity }), + inspect(decoder), + flat(request).slice(-21), + ]).toEqual([ + "Response { status: 200, statusText: '', headers: Headers {}, body: Envelope { value: [Circular] }, bodyUsed: false, ok: true, redirected: false, type: 'default', url: '' }", + "AbortController { signal: [Circular] }", + "AbortController { signal: [Circular] }", + "TextDecoder { encoding: [ [Circular] ], fatal: false, ignoreBOM: false }", + " signal: [Circular] }", + ]); + }); + + test("the same value twice in one print is not a cycle", () => { + const blob = new Blob(["x"]); + const response = new Response(null); + Object.defineProperty(response, "url", { value: [blob, blob] }); + expect([inspect([blob, blob], { depth: null }), flat(response).slice(flat(response).indexOf("url:"))]).toEqual([ + "[ Blob { size: 1, type: '' }, Blob { size: 1, type: '' } ]", + "url: [ Blob { size: 1, type: '' }, Blob { size: 1, type: '' } ] }", + ]); + }); + + test("a print that starts while the same value prints is a print like any other", () => { + const response = new Response(null); + const plain = inspect(response); + let inner; + const outer = inspect(response, { + stylize(text) { + inner ??= inspect(response); + return text; + }, + }); + expect([inner, outer]).toEqual([plain, plain]); + }); + + test("a print that a node:vm timeout ends leaves the value as it was", () => { + const vm = require("node:vm"); + const values = { response: new Response(null), blob: new Blob(["x"]), headers: new Headers({ a: "1" }) }; + const before = Object.values(values).map(value => inspect(value)); + const context = vm.createContext({ inspect, values }); + for (const name of Object.keys(values)) { + expect(() => vm.runInContext(`for (;;) inspect(values.${name});`, context, { timeout: 20 })).toThrow( + expect.objectContaining({ code: "ERR_SCRIPT_EXECUTION_TIMEOUT" }), + ); + } + expect(Object.values(values).map(value => inspect(value))).toEqual(before); + }); + }); + + describe("a print changes nothing", () => { + test("the headers line is what response.headers gives, before and after a read of it", () => { + const line = response => + inspect(response) + .split("\n") + .find(text => text.includes("headers:")) + .trim(); + const of = headers => `headers: ${inspect(headers)},`; + const bodies = { + none: () => new Response(null), + string: () => new Response("x"), + blob: () => new Response(new Blob(["x"], { type: "text/csv" })), + init: () => new Response("x", { headers: { "x-a": "1" } }), + json: () => Response.json({ a: 1 }), + }; + for (const [name, create] of Object.entries(bodies)) { + const printed = create(); + const before = line(printed); + // The first read of the getter, after a print. The next print has that list. + const headers = printed.headers; + const after = line(printed); + expect({ name, before, after }).toEqual({ name, before: of(create().headers), after: of(headers) }); + expect(printed.headers).toBe(headers); + } + }); + + test.concurrent("Bun.serve sends a printed Response as it sends one that was not printed", async () => { + using dir = tempDir("inspect-web-classes", { "file.txt": "0123456789" }); + const path = join(String(dir), "file.txt"); + const formData = () => { + const data = new FormData(); + data.append("a", "1"); + return data; + }; + const bodies = { + none: () => new Response(null, { status: 204 }), + string: () => new Response("hello"), + bytes: () => new Response(new Uint8Array([104, 105])), + blob: () => new Response(new Blob(["hello"], { type: "text/csv" })), + file: () => new Response(Bun.file(path)), + slice: () => new Response(Bun.file(path).slice(2, 6)), + params: () => new Response(new URLSearchParams("a=1")), + json: () => Response.json({ a: 1 }), + stream: () => new Response(new Blob(["hello"]).stream()), + headers: () => new Response("hello", { headers: { "x-a": "1", "content-type": "text/x-test" } }), + form: () => new Response(formData()), + }; + await using server = Bun.serve({ + port: 0, + fetch(request) { + const url = new URL(request.url); + const response = bodies[url.pathname.slice(1)](); + if (url.searchParams.has("print")) inspect(response); + return response; + }, + }); + const seen = async (name, method, print) => { + const response = await fetch(`${server.url}${name}${print ? "?print" : ""}`, { method }); + const headers = Object.fromEntries(response.headers); + delete headers.date; + if (headers["content-type"]) + headers["content-type"] = headers["content-type"].replace(/boundary=.*/, "boundary"); + const body = (await response.text()).replace(/-+WebKitFormBoundary\w+/g, "boundary"); + return { name, method, status: response.status, headers, body }; + }; + for (const name of Object.keys(bodies)) { + for (const method of ["GET", "HEAD"]) { + expect(await seen(name, method, true)).toEqual(await seen(name, method, false)); + } + } + }); + + test.concurrent("a served Request prints its URL and its headers, and reads them the same after", async () => { + let seen; + await using server = Bun.serve({ + port: 0, + routes: { + "/users/:id": request => { + const text = flat(request); + seen = { text, url: request.url, accept: request.headers.get("accept"), id: request.params.id }; + return new Response("ok"); + }, + }, + fetch(request) { + const text = flat(request); + seen = { text, url: request.url, accept: request.headers.get("accept") }; + return new Response("ok"); + }, + }); + for (const path of ["/plain?q=1", "/users/7?q=1"]) { + await (await fetch(`${server.url}${path.slice(1)}`, { headers: { accept: "text/x-test" } })).text(); + const url = `${server.url}${path.slice(1)}`; + expect(seen.url).toBe(url); + expect(seen.accept).toBe("text/x-test"); + expect(seen.text).toStartWith(`Request { method: 'GET', url: '${url}', headers: Headers { `); + expect(seen.text).toContain("accept: 'text/x-test'"); + } + }); + + test("a Request shows the signal it has, or the one that `signal` gives, and keeps none", () => { + const { heapStats } = require("bun:jsc"); + const signals = () => heapStats().objectTypeCounts.AbortSignal ?? 0; + const controller = new AbortController(); + controller.abort(); + const withSignal = new Request("http://127.0.0.1:1/", { signal: controller.signal }); + const requests = Array.from({ length: 50 }, () => new Request("http://127.0.0.1:1/")); + const signalOf = request => flat(request).slice(flat(request).indexOf("signal:")); + expect([signalOf(withSignal), signalOf(requests[0])]).toEqual([ + "signal: AbortSignal { aborted: true } }", + "signal: AbortSignal { aborted: false } }", + ]); + Bun.gc(true); + const before = signals(); + for (const request of requests) inspect(request); + Bun.gc(true); + // A print made a signal for each Request, and no Request kept one. + expect(signals() - before).toBeLessThan(requests.length / 2); + // The getter makes the signal and keeps it. + const kept = requests.map(request => request.signal); + Bun.gc(true); + expect(signals() - before).toBeGreaterThan(kept.length / 2); + }); + + test.concurrent("after Bun.serve sent a Response, the print has what its getters give", async () => { + let response; + await using server = Bun.serve({ + port: 0, + fetch() { + response = new Response("hello", { headers: { "x-a": "1" } }); + // The program read the headers before the server sent the Response. + response.headers.set("x-b", "2"); + return response; + }, + }); + await (await fetch(server.url)).text(); + const line = name => + inspect(response) + .split("\n") + .find(text => text.trim().startsWith(`${name}:`)) + ?.trim(); + expect([line("headers"), line("bodyUsed"), line("status")]).toEqual([ + `headers: ${inspect(response.headers)},`, + `bodyUsed: ${response.bodyUsed},`, + "status: 200,", + ]); + }); + + test("a Bun.file() shows a size only once it has one", async () => { + using dir = tempDir("inspect-web-classes", { "file.txt": "0123456789" }); + const file = Bun.file(join(String(dir), "file.txt")); + const missing = Bun.file(join(String(dir), "missing.txt")); + const before = [inspect(file), inspect(missing), inspect(file.slice(2, 6))]; + const size = file.size; + expect({ before, after: inspect(file), size }).toEqual({ + before: [ + "Blob { type: 'text/plain;charset=utf-8' }", + "Blob { type: 'text/plain;charset=utf-8' }", + "Blob { type: 'text/plain;charset=utf-8' }", + ], + after: "Blob { size: 10, type: 'text/plain;charset=utf-8' }", + size: 10, + }); + }); + + test.concurrent("an S3 file prints as a Blob, and no request is made", async () => { + let requests = 0; + await using server = Bun.serve({ + port: 0, + fetch() { + requests++; + return new Response("", { status: 404 }); + }, + }); + const client = new Bun.S3Client({ + accessKeyId: "test", + secretAccessKey: "test", + bucket: "bucket", + endpoint: server.url.href, + }); + const file = client.file("key.txt"); + expect([inspect(file), inspect({ it: file }, { depth: 0 })]).toEqual([ + `Blob { type: '${file.type}' }`, + "{ it: [Blob [S3File]] }", + ]); + // A request of a print would be at the server before this one. + await (await fetch(server.url)).text(); + expect(requests).toBe(1); + // The prototype of an S3 file inherits the method. + expect(Object.hasOwn(Object.getPrototypeOf(file), customSymbol)).toBe(false); + }); + + test("a value prints as a File when instanceof File says so", () => { + const file = new File(["x"], "a.txt", { lastModified: 5 }); + const copy = new Blob([file]); + const notNumber = new File(["x"], "a.txt", { lastModified: NaN }); + expect([inspect(file), inspect(new Blob(["x"])), inspect(copy).startsWith("File {"), inspect(notNumber)]).toEqual( + [ + "File { size: 1, type: '', name: 'a.txt', lastModified: 5 }", + "Blob { size: 1, type: '' }", + copy instanceof File, + `File { size: 1, type: '', name: 'a.txt', lastModified: ${notNumber.lastModified} }`, + ], + ); + }); + }); + + describe("Timeout", () => { + test("prints the properties a program added, after its own", () => { + const timeout = setTimeout(onTimeout, 50); + try { + timeout.custom = 7; + timeout[Symbol.for("tag")] = "t"; + timeout.self = timeout; + Object.defineProperty(timeout, "hidden", { value: 1 }); + expect(inspect(timeout).split("\n")).toEqual([ + " Timeout {", + " _idleTimeout: 50,", + ` _idleStart: ${timeout._idleStart},`, + " _onTimeout: [Function: onTimeout],", + " _repeat: null,", + " _destroyed: false,", + " custom: 7,", + " self: [Circular *1],", + " Symbol(tag): 't'", + "}", + ]); + expect(inspect(timeout, { showHidden: true })).toContain("[hidden]: 1"); + // The print made no change to the timer. + expect([timeout.self, timeout.custom, timeout.hasRef(), Object.keys(timeout)]).toEqual([ + timeout, + 7, + true, + ["custom", "self"], + ]); + } finally { + clearTimeout(timeout); + } + }); + + test("prints its callback one level deep, as the function it was given", () => { + function withProperty() {} + withProperty.meta = { nested: { deep: 1 } }; + const timeout = setTimeout(withProperty, 50); + try { + expect(inspect(timeout).split("\n")[3]).toBe(" _onTimeout: [Function],"); + expect(timeout._onTimeout).toBe(withProperty); + } finally { + clearTimeout(timeout); + } + }); + + test("an object that inherits from a timer is not the timer", () => { + const timeout = setTimeout(onTimeout, 50); + try { + const child = Object.create(timeout); + child.own = 1; + expect(inspect(child)).toBe("Timeout { own: 1 }"); + } finally { + clearTimeout(timeout); + } + }); + }); + + test.concurrent("each prototype has the method before node:util loads, and in a Worker", async () => { + const { stdout, exitCode } = await run(` + const custom = Symbol.for("nodejs.util.inspect.custom"); + const count = () => { + const timeout = setTimeout(() => {}, 1); + clearTimeout(timeout); + return [Response, Request, Headers, FormData, Blob, AbortSignal, AbortController, Event, TextDecoder] + .map(constructor => constructor.prototype) + .concat(Object.getPrototypeOf(timeout)) + .filter(prototype => typeof Object.getOwnPropertyDescriptor(prototype, custom)?.value === "function").length; + }; + console.log(count(), new Blob(["hello"])[custom](2, {})); + const code = + "const custom = Symbol.for('nodejs.util.inspect.custom'); const count = " + + count + + "; postMessage([count(), new Blob(['hello'])[custom](2, {})]);"; + const worker = new Worker(URL.createObjectURL(new Blob([code]))); + worker.onmessage = event => { + console.log(...event.data); + worker.terminate(); + }; + `); + expect({ stdout, exitCode }).toEqual({ + stdout: "10 Blob { size: 5, type: '' }\n10 Blob { size: 5, type: '' }\n", + exitCode: 0, + }); + }); +}); diff --git a/test/js/node/util/inspect-web-classes.test.ts b/test/js/node/util/inspect-web-classes.test.ts new file mode 100644 index 000000000000..37107c3c0569 --- /dev/null +++ b/test/js/node/util/inspect-web-classes.test.ts @@ -0,0 +1,1099 @@ +// The text that Node.js v26.3.0 prints for the classes with native state. `node --test` passes this file too. +import assert from "node:assert"; +import { spawnSync } from "node:child_process"; +import { Console } from "node:console"; +import { X509Certificate } from "node:crypto"; +import { BlockList, SocketAddress } from "node:net"; +import { Writable } from "node:stream"; +import { describe, test } from "node:test"; +import { format, inspect, stripVTControlCharacters } from "node:util"; +import { Worker } from "node:worker_threads"; + +const isBun = typeof process.versions.bun === "string"; +const custom = Symbol.for("nodejs.util.inspect.custom"); + +/** The text in Node.js and the text in Bun, and why they are not the same. */ +const differs = (node: string, bun: string, why: string) => { + assert.ok(why.length > 0); + return isBun ? bun : node; +}; + +/** What `fn` returns when that is a string, else the kind of value or the error. */ +const outcome = (fn: () => unknown) => { + try { + const value = fn(); + return typeof value === "string" ? value : `(returns ${value === null ? "null" : typeof value})`; + } catch (error: any) { + return `${error.name}${error.code ? ` [${error.code}]` : ""}: ${error.message}`; + } +}; + +function onTimeout() {} +const make = { + Headers: () => new Headers({ "x-request-id": "abc123" }), + Response: () => new Response(null, { status: 404, statusText: "Not Found", headers: { "x-request-id": "abc123" } }), + Request: () => new Request("http://example.com/users?id=7", { method: "POST", headers: { accept: "text/html" } }), + Blob: () => new Blob(["hello"], { type: "text/csv" }), + File: () => new File(["hello"], "report.csv", { type: "text/csv", lastModified: 5 }), + FormData: () => { + const form = new FormData(); + form.append("username", "john_doe"); + form.append("email", "john@example.com"); + return form; + }, + AbortSignal: () => AbortSignal.abort(), + AbortController: () => new AbortController(), + Event: () => new Event("ping", { cancelable: true }), + TextDecoder: () => new TextDecoder("utf-16le", { fatal: true }), +}; + +const views = (value: unknown) => ({ + "text": inspect(value), + "past the depth limit": inspect({ it: value }, { depth: 0 }), + "three levels deep": inspect({ a: { b: { c: value } } }), + "%s": format("%s", value), +}); + +const responseText = [ + "Response {", + " status: 404,", + " statusText: 'Not Found',", + " headers: Headers { 'x-request-id': 'abc123' },", + " body: null,", + " bodyUsed: false,", + " ok: false,", + " redirected: false,", + " type: 'default',", + " url: ''", + "}", +]; +const indented = (lines: string[], by: string) => lines.map(line => by + line).join("\n"); + +// Bun's Request holds other values than undici's, and the method prints what the getters give. +const requestWhy = + "Bun's Request has referrer '' and credentials 'include', and has no keepalive and no navigation flags"; +const requestText = { + node: [ + "Request {", + " method: 'POST',", + " url: 'http://example.com/users?id=7',", + " headers: Headers { accept: 'text/html' },", + " destination: '',", + " referrer: 'about:client',", + " referrerPolicy: '',", + " mode: 'cors',", + " credentials: 'same-origin',", + " cache: 'default',", + " redirect: 'follow',", + " integrity: '',", + " keepalive: false,", + " isReloadNavigation: false,", + " isHistoryNavigation: false,", + ], + bun: [ + "Request {", + " method: 'POST',", + " url: 'http://example.com/users?id=7',", + " headers: Headers { accept: 'text/html' },", + " destination: '',", + " referrer: '',", + " referrerPolicy: '',", + " mode: 'cors',", + " credentials: 'include',", + " cache: 'default',", + " redirect: 'follow',", + " integrity: '',", + ], +}; +const requestLines = (signal: string) => { + const tail = [` signal: ${signal}`, "}"]; + return differs([...requestText.node, ...tail].join("\n"), [...requestText.bun, ...tail].join("\n"), requestWhy).split( + "\n", + ); +}; + +describe("the text of each class", () => { + test("Headers", () => { + assert.deepStrictEqual(views(make.Headers()), { + "text": "Headers { 'x-request-id': 'abc123' }", + "past the depth limit": "{ it: Headers { 'x-request-id': 'abc123' } }", + "three levels deep": "{ a: { b: { c: Headers { 'x-request-id': 'abc123' } } } }", + "%s": "Headers { 'x-request-id': 'abc123' }", + }); + }); + + test("Headers: the values of a repeated name are one string, for set-cookie too", () => { + const headers = new Headers(); + headers.append("x-a", "1"); + headers.append("x-a", "2"); + headers.append("set-cookie", "a=1"); + headers.append("set-cookie", "b=2"); + assert.deepStrictEqual( + [inspect(headers), inspect(new Headers()), inspect(new Headers({ "0": "zero", "a": "1" }))], + [ + differs( + "Headers { 'x-a': '1, 2', 'set-cookie': 'a=1, b=2' }", + "Headers { 'set-cookie': 'a=1, b=2', 'x-a': '1, 2' }", + "the order is the one that Bun stores the names in", + ), + "Headers {}", + "Headers { '0': 'zero', a: '1' }", + ], + ); + }); + + test("Response", () => { + const value = make.Response(); + assert.deepStrictEqual( + { + ...views(value), + "depth null": inspect(value, { depth: null }), + "breakLength Infinity": inspect(value, { breakLength: Infinity }), + "compact false": inspect(value, { compact: false }), + }, + { + "text": responseText.join("\n"), + "past the depth limit": `{\n${indented(responseText, " ").replace(" Response", " it: Response")}\n}`, + "three levels deep": + "{\n a: {\n b: {\n" + + indented(responseText, " ").replace(" Response", " c: Response") + + "\n }\n }\n}", + "%s": responseText.join("\n"), + "depth null": responseText.join("\n"), + "breakLength Infinity": + "Response { status: 404, statusText: 'Not Found', headers: Headers { 'x-request-id': 'abc123' }, " + + "body: null, bodyUsed: false, ok: false, redirected: false, type: 'default', url: '' }", + "compact false": responseText + .join("\n") + .replace("Headers { 'x-request-id': 'abc123' }", "Headers {\n 'x-request-id': 'abc123'\n }"), + }, + ); + }); + + test("Request", () => { + const full = requestLines("AbortSignal { aborted: false }"); + const nested = requestLines("[AbortSignal]"); + assert.deepStrictEqual(views(make.Request()), { + "text": full.join("\n"), + "past the depth limit": `{\n${indented(nested, " ").replace(" Request", " it: Request")}\n}`, + "three levels deep": + "{\n a: {\n b: {\n" + + indented(full, " ").replace(" Request", " c: Request") + + "\n }\n }\n}", + "%s": nested.join("\n"), + }); + }); + + test("Blob", () => { + assert.deepStrictEqual(views(make.Blob()), { + "text": "Blob { size: 5, type: 'text/csv' }", + "past the depth limit": "{ it: [Blob] }", + "three levels deep": "{ a: { b: { c: [Blob] } } }", + "%s": "Blob [Object]", + }); + }); + + test("File", () => { + assert.deepStrictEqual(views(make.File()), { + "text": "File { size: 5, type: 'text/csv', name: 'report.csv', lastModified: 5 }", + "past the depth limit": "{ it: [File] }", + "three levels deep": "{ a: { b: { c: [File] } } }", + "%s": "File [Object]", + }); + }); + + test("FormData", () => { + const value = make.FormData(); + const lines = "FormData {\n username: 'john_doe',\n email: 'john@example.com'\n}"; + const nested = (indent: string) => lines.replaceAll("\n", `\n${indent}`); + assert.deepStrictEqual( + { ...views(value), "breakLength Infinity": inspect(value, { breakLength: Infinity }) }, + { + "text": lines, + "past the depth limit": `{\n it: ${nested(" ")}\n}`, + "three levels deep": `{\n a: {\n b: {\n c: ${nested(" ")}\n }\n }\n}`, + "%s": lines, + "breakLength Infinity": "FormData { username: 'john_doe', email: 'john@example.com' }", + }, + ); + }); + + test("FormData: the values of a repeated name, and no entries", () => { + const form = new FormData(); + form.append("a", "1"); + const one = inspect(form); + form.append("a", "2"); + // undici starts an array only when the value the name has is truthy. + form.append("b", ""); + form.append("b", "3"); + assert.deepStrictEqual( + [one, inspect(form), inspect(new FormData())], + ["FormData { a: '1' }", "FormData { a: [ '1', '2' ], b: '3' }", "FormData {}"], + ); + }); + + test("FormData: four values of a name, and the names __proto__ and 0", () => { + const form = new FormData(); + for (const value of ["1", "", "3", "4"]) form.append("a", value); + form.append("__proto__", "p"); + form.append("0", "zero"); + form.append("0", "one"); + assert.strictEqual( + inspect(form), + "FormData {\n '0': [ 'zero', 'one' ],\n a: [ '1', '', '3', '4' ],\n ['__proto__']: 'p'\n}", + ); + }); + + test("FormData: a File entry", () => { + const form = new FormData(); + form.append("doc", new File(["hello"], "report.csv", { type: "application/pdf", lastModified: 5 })); + assert.strictEqual( + inspect(form, { breakLength: Infinity }), + "FormData { doc: File { size: 5, type: 'application/pdf', name: 'report.csv', lastModified: 5 } }", + ); + }); + + test("AbortSignal", () => { + assert.deepStrictEqual(views(make.AbortSignal()), { + "text": "AbortSignal { aborted: true }", + "past the depth limit": "{ it: [AbortSignal] }", + "three levels deep": "{ a: { b: { c: [AbortSignal] } } }", + "%s": "AbortSignal [Object]", + }); + assert.deepStrictEqual( + [inspect(AbortSignal.timeout(100_000)), inspect(AbortSignal.any([]))], + ["AbortSignal { aborted: false }", "AbortSignal { aborted: false }"], + ); + }); + + test("AbortController", () => { + assert.deepStrictEqual(views(make.AbortController()), { + "text": "AbortController { signal: AbortSignal { aborted: false } }", + "past the depth limit": "{ it: AbortController {} }", + "three levels deep": "{ a: { b: { c: AbortController {} } } }", + "%s": "AbortController [Object]", + }); + }); + + test("Event", () => { + const value = make.Event(); + // The time is 0 in Bun, so the test takes it from the event. + const fields = { type: "ping", defaultPrevented: false, cancelable: true, timeStamp: value.timeStamp }; + assert.deepStrictEqual(views(value), { + "text": `Event ${inspect(fields)}`, + "past the depth limit": "{ it: Event }", + "three levels deep": "{ a: { b: { c: Event } } }", + "%s": "Event [Object]", + }); + value.preventDefault(); + assert.strictEqual(inspect(value), `Event ${inspect({ ...fields, defaultPrevented: true })}`); + }); + + test("TextDecoder", () => { + assert.deepStrictEqual(views(make.TextDecoder()), { + "text": "TextDecoder { encoding: 'utf-16le', fatal: true, ignoreBOM: false }", + "past the depth limit": "{ it: [TextDecoder] }", + "three levels deep": "{ a: { b: { c: [TextDecoder] } } }", + // The method prints its fields with default options, so a depth of 0 does not cut them. + "%s": "TextDecoder { encoding: 'utf-16le', fatal: true, ignoreBOM: false }", + }); + }); + + test("Timeout", () => { + const timeout = setTimeout(onTimeout, 50); + const interval = setInterval(onTimeout, 70); + try { + const why = "Bun stores five of node's fields of a timer"; + const nodeOnly = /^ (_idlePrev|_idleNext|_timerArgs|Symbol\(\w+\)): /; + // The fields are what the properties of the timer give. + const expected = (value: any) => [ + "Timeout {", + ` _idleTimeout: ${value._idleTimeout},`, + ` _idleStart: ${value._idleStart},`, + ` _onTimeout: ${inspect(value._onTimeout, { depth: 0 })},`, + ` _repeat: ${value._repeat},`, + differs(" _destroyed: false,", " _destroyed: false", why), + "}", + ]; + const lines = (value: NodeJS.Timeout) => + inspect(value) + .split("\n") + .filter(line => !nodeOnly.test(line)); + assert.deepStrictEqual([lines(timeout), lines(interval)], [expected(timeout), expected(interval)]); + assert.deepStrictEqual( + [(timeout as any)._idleTimeout, (interval as any)._repeat, (timeout as any)._repeat], + [50, 70, null], + ); + // The method prints the timer one level deep at any depth. + assert.strictEqual(inspect({ it: timeout }, { depth: 0 }).includes("_idleTimeout: 50"), true); + } finally { + clearTimeout(timeout); + clearInterval(interval); + } + }); + + test("util.format and a Console print the text util.inspect gives", () => { + let written = ""; + const stream = new Writable({ + write(chunk, _encoding, callback) { + written += chunk; + callback(); + }, + }); + const console = new Console({ stdout: stream, stderr: stream, colorMode: false }); + console.log(make.Blob()); + console.log("%o", make.Headers()); + console.error(make.AbortSignal()); + assert.deepStrictEqual( + [format("%o", make.Blob()), format("%O", make.Headers()), format(make.TextDecoder()), written.split("\n")], + [ + "Blob { size: 5, type: 'text/csv' }", + "Headers { 'x-request-id': 'abc123' }", + "TextDecoder { encoding: 'utf-16le', fatal: true, ignoreBOM: false }", + [ + "Blob { size: 5, type: 'text/csv' }", + "Headers { 'x-request-id': 'abc123' }", + "AbortSignal { aborted: true }", + "", + ], + ], + ); + }); + + test("colors", () => { + const event = new Event("ping"); + assert.deepStrictEqual( + [ + inspect(make.Blob(), { colors: true }), + inspect({ it: make.File() }, { depth: 0, colors: true }), + inspect(make.Headers(), { colors: true }), + inspect(event, { colors: true }).split("\n")[1], + // undici turns colors on when the caller did not say. + (make.Response() as any)[custom](2, {}).split("\n")[1], + inspect(make.Response()).split("\n")[1], + // The methods inside the print have the colors too. + inspect(make.Request(), { depth: 0, colors: undefined }).split("\n").at(-2), + ], + [ + "Blob { size: \x1b[33m5\x1b[39m, type: \x1b[32m'text/csv'\x1b[39m }", + "{ it: \x1b[36m[File]\x1b[39m }", + "Headers { \x1b[32m'x-request-id'\x1b[39m: \x1b[32m'abc123'\x1b[39m }", + " type: \x1b[32m'ping'\x1b[39m,", + " status: \x1b[33m404\x1b[39m,", + " status: 404,", + " signal: \x1b[36m[AbortSignal]\x1b[39m", + ], + ); + }); + + test("console.log in a node:worker_threads Worker", async () => { + const worker = new Worker( + `console.log(new Blob(["hello"], { type: "text/csv" })); + console.log(new Headers({ "x-request-id": "abc123" }));`, + { eval: true, stdout: true }, + ); + let stdout = ""; + worker.stdout.setEncoding("utf8"); + worker.stdout.on("data", chunk => (stdout += chunk)); + await new Promise((resolve, reject) => { + worker.on("exit", resolve); + worker.on("error", reject); + }); + // The Console of a Worker has colors where the process has them. + assert.strictEqual( + stripVTControlCharacters(stdout), + "Blob { size: 5, type: 'text/csv' }\nHeaders { 'x-request-id': 'abc123' }\n", + ); + }); +}); + +const flat = (value: unknown) => inspect(value, { breakLength: Infinity }); +const past = (value: unknown) => inspect({ it: value }, { depth: 0 }); + +describe("a subclass", () => { + class MyBlob extends Blob {} + class MyFile extends File {} + class MyEvent extends Event {} + class MyTextDecoder extends TextDecoder {} + class MyAbortController extends AbortController {} + class Derived extends Blob {} + class Other extends TextDecoder {} + + test("prints the name node prints", () => { + const event = new MyEvent("ping"); + const customEvent = new CustomEvent("c"); + assert.deepStrictEqual( + [ + new (class MyHeaders extends Headers {})({ a: "1" }), + new (class MyResponse extends Response {})(null), + new MyBlob(["hello"]), + new MyFile(["hello"], "report.csv", { lastModified: 5 }), + new (class MyFormData extends FormData {})(), + event, + customEvent, + new MyTextDecoder(), + new MyAbortController(), + ].map(flat), + [ + // undici and node:buffer print the name of the class. + "Headers { a: '1' }", + "Response { status: 200, statusText: '', headers: Headers {}, body: null, bodyUsed: false, ok: true, redirected: false, type: 'default', url: '' }", + "Blob { size: 5, type: '' }", + "File { size: 5, type: '', name: 'report.csv', lastModified: 5 }", + "FormData {}", + // These print the name of the constructor. + `MyEvent { type: 'ping', defaultPrevented: false, cancelable: false, timeStamp: ${event.timeStamp} }`, + `CustomEvent { type: 'c', defaultPrevented: false, cancelable: false, timeStamp: ${customEvent.timeStamp} }`, + "MyTextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: false }", + "MyAbortController { signal: AbortSignal { aborted: false } }", + ], + ); + }); + + test("past the depth limit has the constructor's name and the tag", () => { + // Node v26.3.0 leaves the tag out when the constructor's name has it in it. v26.9.0 has no such rule (nodejs/node#63257). + const why = "Bun's util.inspect always adds the tag of a subclass"; + assert.deepStrictEqual( + [ + past(new MyBlob(["hello"])), + past(new Derived(["hello"])), + past(new MyFile(["hello"], "report.csv")), + past(new MyTextDecoder()), + past(new Other()), + past(new MyEvent("ping")), + past(new MyAbortController()), + ], + [ + differs("{ it: [MyBlob] }", "{ it: [MyBlob [Blob]] }", why), + "{ it: [Derived [Blob]] }", + differs("{ it: [MyFile] }", "{ it: [MyFile [File]] }", why), + differs("{ it: [MyTextDecoder] }", "{ it: [MyTextDecoder [TextDecoder]] }", why), + "{ it: [Other [TextDecoder]] }", + "{ it: MyEvent }", + differs("{ it: MyAbortController {} }", "{ it: MyAbortController [AbortController] {} }", why), + ], + ); + }); + + test("a class with no name prints as node prints it", () => { + const event = new (class extends Event {})("ping"); + assert.deepStrictEqual( + [ + flat(new (class extends TextDecoder {})()), + flat(event), + flat(new (class extends AbortController {})()), + past(new (class extends Blob {})([])), + ], + [ + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: false }", + ` { type: 'ping', defaultPrevented: false, cancelable: false, timeStamp: ${event.timeStamp} }`, + " { signal: AbortSignal { aborted: false } }", + "{ it: [Blob] }", + ], + ); + }); +}); + +describe("the receiver", () => { + // Node.js keeps the state of these six in private fields, so its method throws for a receiver that is not the instance. + const privateField: Record = { + Headers: "#headersList", + Response: "#state", + Request: "#state", + FormData: "#state", + AbortController: "#signal", + Event: "#defaultPrevented", + }; + const notDeclared = (name: string) => + `TypeError: Cannot read private member ${privateField[name]} from an object whose class did not declare it`; + const why = "Node.js reads a private field of the receiver. Bun finds the instance"; + + for (const [label, wrap] of [ + ["a Proxy around an instance prints its state", (value: object) => new Proxy(value, {})], + ["an object that inherits from an instance prints its state", (value: object) => Object.create(value)], + ] as const) { + test(label, () => { + const actual: Record = {}; + const expected: Record = {}; + for (const [name, create] of Object.entries(make)) { + const value = create(); + actual[name] = outcome(() => flat(wrap(value))); + expected[name] = name in privateField ? differs(notDeclared(name), flat(value), why) : flat(value); + } + assert.deepStrictEqual(actual, expected); + }); + } + + test("a Proxy's traps do not run", () => { + let traps = 0; + const handler = new Proxy({}, { get: () => (traps++, undefined) }); + const texts = [new Blob(["hello"]), AbortSignal.abort(), new TextDecoder()].map(value => + flat(new Proxy(value, handler)), + ); + assert.deepStrictEqual(texts, [ + "Blob { size: 5, type: '' }", + "AbortSignal { aborted: true }", + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: false }", + ]); + assert.strictEqual( + String(traps > 0), + differs("true", "false", "Node.js reads each field through the Proxy. Bun reads the instance"), + ); + }); + + test("a receiver that holds no instance", () => { + const invalidThis = (name: string) => `TypeError [ERR_INVALID_THIS]: Value of "this" must be of type ${name}`; + const whyPlain = "Bun gives the receiver back, or says that it is not an instance. Node.js reads undefined fields"; + const actual: Record = {}; + for (const [name, create] of Object.entries(make)) { + const method = (Object.getPrototypeOf(create()) as any)[custom]; + actual[name] = outcome(() => method.call({}, 2, {})).split("\n")[0]; + } + assert.deepStrictEqual(actual, { + Headers: differs(notDeclared("Headers"), invalidThis("Headers"), whyPlain), + Response: differs("Response {", "(returns object)", whyPlain), + Request: differs("Request {", "(returns object)", whyPlain), + Blob: differs("Blob { size: undefined, type: undefined }", "(returns object)", whyPlain), + File: differs("TypeError: Cannot read properties of undefined (reading 'name')", "(returns object)", whyPlain), + FormData: differs(notDeclared("FormData"), invalidThis("FormData"), whyPlain), + AbortSignal: differs("Object { aborted: undefined }", "(returns object)", whyPlain), + AbortController: differs("Object { signal: undefined }", "(returns object)", whyPlain), + Event: invalidThis("Event"), + TextDecoder: invalidThis("TextDecoder"), + }); + }); + + test("null as the receiver is an error", () => { + const invalidThis = (name: string) => `TypeError [ERR_INVALID_THIS]: Value of "this" must be of type ${name}`; + const reading = (name: string) => `TypeError: Cannot read properties of null (reading '${name}')`; + const whyNull = "Bun's error says which class the receiver must be"; + const actual: Record = {}; + for (const [name, create] of Object.entries(make)) { + const method = (Object.getPrototypeOf(create()) as any)[custom]; + actual[name] = outcome(() => method.call(null, 2, {})); + } + assert.deepStrictEqual(actual, { + Headers: differs(reading("#headersList"), invalidThis("Headers"), whyNull), + Response: differs(reading("status"), invalidThis("Response"), whyNull), + Request: differs(reading("method"), invalidThis("Request"), whyNull), + Blob: differs(reading("size"), invalidThis("Blob"), whyNull), + File: differs(reading("size"), invalidThis("Blob"), whyNull), + FormData: differs(reading("#state"), invalidThis("FormData"), whyNull), + AbortSignal: differs(reading("aborted"), invalidThis("AbortSignal"), whyNull), + AbortController: differs(reading("signal"), invalidThis("AbortController"), whyNull), + Event: invalidThis("Event"), + TextDecoder: invalidThis("TextDecoder"), + }); + }); + + test("the method of one class on an instance of another", () => { + const blobMethod = (Blob.prototype as any)[custom]; + const eventMethod = (Event.prototype as any)[custom]; + assert.deepStrictEqual( + [outcome(() => eventMethod.call(new Blob([]), 2, {})), outcome(() => blobMethod.call(new TextDecoder(), 2, {}))], + [ + 'TypeError [ERR_INVALID_THIS]: Value of "this" must be of type Event', + differs("Blob { size: undefined, type: undefined }", "(returns object)", "Bun gives the receiver back"), + ], + ); + }); +}); + +describe("what the class holds in Bun", () => { + test("Headers: the names are lower-case, in the order that Bun stores them", () => { + const headers = new Headers([ + ["X-B", "2"], + ["Accept", "a"], + ["x-a", "1"], + ["Content-Type", "text/plain"], + ]); + assert.strictEqual( + flat(headers), + differs( + "Headers { 'X-B': '2', Accept: 'a', 'x-a': '1', 'Content-Type': 'text/plain' }", + "Headers { accept: 'a', 'content-type': 'text/plain', 'x-b': '2', 'x-a': '1' }", + "undici keeps the case and the order of the names. Bun's header list does not", + ), + ); + }); + + test("Response: a string body has no stream and no content-type until something asks", () => { + const tail = "bodyUsed: false, ok: true, redirected: false, type: 'default', url: '' }"; + assert.strictEqual( + flat(new Response("hello")), + differs( + "Response { status: 200, statusText: '', headers: Headers { 'content-type': 'text/plain;charset=UTF-8' }, " + + `body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true }, ${tail}`, + `Response { status: 200, statusText: '', headers: Headers {}, ${tail}`, + "Bun makes the stream at the first read of response.body, and a print makes nothing", + ), + ); + }); + + test("Timeout: a timer that was cleared keeps its delay and its callback", () => { + const timeout = setTimeout(onTimeout, 50); + clearTimeout(timeout); + const text = inspect(timeout); + const why = "Node.js sets _idleTimeout to -1 and _onTimeout to null"; + assert.deepStrictEqual( + [/_idleTimeout: (-?\d+)/.exec(text)?.[1], String(/_onTimeout: null/.test(text)), /_destroyed: true/.test(text)], + [differs("-1", "50", why), differs("true", "false", why), true], + ); + }); + + test("TextDecoder: showHidden adds nothing", () => { + assert.strictEqual( + inspect(new TextDecoder(), { showHidden: true }).replace(/\s+/g, " "), + differs( + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: false, Symbol(flags): 0, Symbol(handle): undefined }", + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: false }", + "Bun's TextDecoder has no flags and no handle", + ), + ); + }); +}); + +describe("a property that a program put on the value", () => { + test("a data property with the name of a field is the field, as in Node.js", () => { + class StatusField extends Response { + status = 1; + } + const response = new Response(null); + Object.defineProperty(response, "url", { value: "http://own/" }); + class ProtoData extends Blob {} + Object.defineProperty(ProtoData.prototype, "type", { value: "proto/type" }); + const signal = AbortSignal.abort(); + Object.defineProperty(signal, "aborted", { value: "yes" }); + const decoder = new TextDecoder(); + Object.defineProperty(decoder, "encoding", { value: "x" }); + const controller = new AbortController(); + Object.defineProperty(controller, "signal", { value: 5 }); + const child = Object.create(new Blob(["abc"])); + Object.defineProperty(child, "type", { value: "child/type" }); + assert.deepStrictEqual( + [ + flat(new StatusField(null)).slice(0, 22), + flat(response).slice(-20), + flat(new ProtoData(["x"])), + flat(signal), + flat(decoder), + flat(controller), + flat(child), + ], + [ + "Response { status: 1, ", + "url: 'http://own/' }", + "Blob { size: 1, type: 'proto/type' }", + "AbortSignal { aborted: 'yes' }", + "TextDecoder { encoding: 'x', fatal: false, ignoreBOM: false }", + "AbortController { signal: 5 }", + "Blob { size: 3, type: 'child/type' }", + ], + ); + }); + + test("an accessor with the name of a field is not called", () => { + let calls = 0; + class Getter extends Blob { + get size() { + calls++; + return 99; + } + } + const own = new Blob(["x"]); + Object.defineProperty(own, "size", { get: () => (calls++, 42) }); + const why = "Node.js reads this.size. Bun prints the state of the class and runs no getter"; + assert.deepStrictEqual( + [flat(new Getter(["x"])), flat(own), String(calls)], + [ + differs("Blob { size: 99, type: '' }", "Blob { size: 1, type: '' }", why), + differs("Blob { size: 42, type: '' }", "Blob { size: 1, type: '' }", why), + differs("2", "0", why), + ], + ); + }); + + test("a property with another name does not show, and customInspect: false shows it", () => { + const request = make.Request(); + const pristine = inspect(request); + (request as any).user = { id: 7 }; + assert.deepStrictEqual( + [inspect(request), inspect(request, { customInspect: false }).includes("user: { id: 7 }")], + [pristine, true], + ); + }); + + test("a name that node reads and Bun's Request does not have shows when a program put it there", () => { + const request = new Request("http://example.com/"); + Object.defineProperty(request, "keepalive", { value: true }); + assert.strictEqual( + flat(request).slice(flat(request).indexOf("integrity")), + differs( + "integrity: '', keepalive: true, isReloadNavigation: false, isHistoryNavigation: false, signal: AbortSignal { aborted: false } }", + "integrity: '', keepalive: true, signal: AbortSignal { aborted: false } }", + requestWhy, + ), + ); + }); + + test("with getters: true, a getter that a program put on a timer runs on the timer", () => { + const timeout = setTimeout(onTimeout, 50); + try { + Object.defineProperty(timeout, "isTheTimer", { + get() { + return this === timeout; + }, + enumerable: true, + }); + assert.match(inspect(timeout, { getters: true }), /isTheTimer: \[Getter: true\]/); + } finally { + clearTimeout(timeout); + } + }); + + test("a value that holds itself where the depth counts down prints as in Node.js", () => { + const controller = new AbortController(); + Object.defineProperty(controller, "signal", { value: controller }); + assert.strictEqual( + inspect(controller), + "AbortController { signal: AbortController { signal: AbortController {} } }", + ); + }); +}); + +describe("past the depth limit, a value prints as util.inspect prints any value there", () => { + test("the constructor is one that the value is an instance of, and an own tag does not show", () => { + const ownConstructor = new Blob([]); + Object.defineProperty(ownConstructor, "constructor", { value: function Foo() {} }); + const ownTag = new Blob([]); + Object.defineProperty(ownTag, Symbol.toStringTag, { value: "Own", enumerable: true }); + const hiddenTag = new Blob([]); + Object.defineProperty(hiddenTag, Symbol.toStringTag, { value: "Hidden" }); + class SymbolName extends Blob { + static name: any = Symbol("n"); + } + const decoder = new TextDecoder(); + Object.defineProperty(decoder, "constructor", { value: class Other {} }); + assert.deepStrictEqual( + [past(ownConstructor), past(ownTag), past(hiddenTag), past(new SymbolName([])), past(decoder)], + [ + "{ it: [Blob] }", + "{ it: [Blob] }", + "{ it: [Blob [Hidden]] }", + "{ it: [Symbol(n) [Blob]] }", + "{ it: [TextDecoder] }", + ], + ); + }); + + test("a File keeps a name and a tag that a program gave it", () => { + const NamedBlob = (Base => class Blob extends Base {})(File); + class Tagged extends File { + get [Symbol.toStringTag]() { + return "Blob"; + } + } + const ownTag = Object.defineProperty(new File([], "a.txt"), Symbol.toStringTag, { value: "Blob" }); + assert.deepStrictEqual( + [past(new NamedBlob([], "a.txt")), past(new Tagged([], "a.txt")), past(ownTag)], + ["{ it: [Blob [File]] }", "{ it: [Tagged [Blob]] }", "{ it: [File [Blob]] }"], + ); + }); + + test("a receiver that inherits from a value has no key of its own", () => { + assert.deepStrictEqual( + [past(Object.create(new Blob([]))), past(Object.create(new TextDecoder()))], + ["{ it: Blob {} }", "{ it: TextDecoder {} }"], + ); + }); + + test("the body of a Response", () => { + const response = new Response(new ReadableStream()); + const body = (text: string) => + text + .split("\n") + .find(line => line.includes("body:")) + ?.trim(); + assert.deepStrictEqual( + [body(inspect(response)), body(inspect(response, { depth: 0 }))], + [ + "body: ReadableStream { locked: false, state: 'readable', supportsBYOB: false },", + differs( + "body: undefined,", + "body: ReadableStream {},", + "Node's method for a stream returns undefined past the depth limit. Bun's returns the stream", + ), + ], + ); + }); + + test("a direct call with a depth below zero", () => { + const why = "Node.js returns the value, and its util.inspect prints [Blob] for it. Bun returns that text"; + assert.deepStrictEqual( + ["Blob", "File", "AbortSignal", "TextDecoder", "AbortController", "Event"].map(name => { + const value = (make as any)[name](); + return outcome(() => value[custom](-1, {})); + }), + [ + differs("(returns object)", "[Blob]", why), + differs("(returns object)", "[File]", why), + differs("(returns object)", "[AbortSignal]", why), + differs("(returns object)", "[TextDecoder]", why), + "(returns object)", + "Event", + ], + ); + }); +}); + +describe("options and errors", () => { + test("a function as the options of a fetch class is an error, as in undici", () => { + const form = new FormData(); + form.append("a", "1"); + const invalid = + 'TypeError [ERR_INVALID_ARG_TYPE]: The "inspectOptions" argument must be of type object. Received function '; + assert.deepStrictEqual( + [form, new Response(null), new Headers()].map(value => outcome(() => (value as any)[custom](2, function () {}))), + [invalid, invalid, invalid], + ); + }); + + test("a second call with the same options object prints the same text", () => { + const response = new Response(null); + const request = new Request("http://127.0.0.1:1/"); + const options: Record = { depth: 2 }; + const first = [(response as any)[custom](2, options), (request as any)[custom](2, options)]; + assert.deepStrictEqual( + [[(response as any)[custom](2, options), (request as any)[custom](2, options)], Object.keys(options)], + // undici sets `colors` in the options that it got. + [first, ["depth", "colors"]], + ); + assert.match(first[0], /^Response \{/); + }); + + test("an error that a nested method throws is the error that util.inspect throws", () => { + const error = new RangeError("boom"); + let caught: unknown; + try { + inspect({ + a: { + [custom]() { + throw error; + }, + }, + }); + } catch (thrown) { + caught = thrown; + } + assert.strictEqual(caught, error); + // The same for the error of one of the methods. + const method = (Event.prototype as any)[custom]; + assert.throws(() => inspect({ a: { b: { [custom]: () => method.call({}, 2, {}) } } }), { + code: "ERR_INVALID_THIS", + }); + }); + + test("with getters: true, a method that throws null inside a getter's value prints as the getter's error", () => { + const thrower = (value: null | undefined) => ({ + get config() { + return { + [custom]() { + throw value; + }, + }; + }, + after: 1, + }); + assert.deepStrictEqual( + [inspect(thrower(null), { getters: true }), inspect(thrower(undefined), { getters: true })], + [ + "{ config: [Getter: ], after: 1 }", + "{ config: [Getter: ], after: 1 }", + ], + ); + }); +}); + +// The prototypes that own the method in Node.js v26.3.0 and that a global or a module export gives, and Timeout. +describe("the prototypes that own the method in Node.js", () => { + const globals = [ + "AbortController", + "AbortSignal", + "Blob", + "BroadcastChannel", + "Buffer", + "ByteLengthQueuingStrategy", + "CompressionStream", + "CountQueuingStrategy", + "CryptoKey", + "DecompressionStream", + "Event", + "EventTarget", + "FormData", + "Headers", + "MessagePort", + "Performance", + "PerformanceEntry", + "PerformanceObserver", + "PerformanceObserverEntryList", + "ReadableByteStreamController", + "ReadableStream", + "ReadableStreamBYOBReader", + "ReadableStreamBYOBRequest", + "ReadableStreamDefaultController", + "ReadableStreamDefaultReader", + "Request", + "Response", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TransformStream", + "TransformStreamDefaultController", + "URL", + "URLSearchParams", + "WritableStream", + "WritableStreamDefaultController", + "WritableStreamDefaultWriter", + ]; + const prototypes: [string, () => object][] = [ + ...globals.map((name): [string, () => object] => [name, () => (globalThis as any)[name].prototype]), + // In Node.js, File.prototype has a method of its own. In Bun, a File has Blob.prototype. + ["File", () => Object.getPrototypeOf(new File([], "a"))], + ["AssertionError", () => assert.AssertionError.prototype], + ["X509Certificate", () => X509Certificate.prototype], + ["BlockList", () => BlockList.prototype], + ["SocketAddress", () => SocketAddress.prototype], + [ + "Timeout", + () => { + const timeout = setTimeout(onTimeout, 50); + clearTimeout(timeout); + return Object.getPrototypeOf(timeout); + }, + ], + ]; + const todoInBun = new Set([ + "BlockList", + "EventTarget", + "Performance", + "PerformanceObserver", + "PerformanceObserverEntryList", + "SocketAddress", + "TextEncoder", + "X509Certificate", + ]); + + for (const [name, prototype] of prototypes) { + test(name, { todo: isBun && todoInBun.has(name) }, () => { + assert.strictEqual(typeof Object.getOwnPropertyDescriptor(prototype(), custom)?.value, "function"); + }); + } + + test("the method of the eleven classes has node's name, length and attributes", () => { + const timeout = setTimeout(onTimeout, 50); + clearTimeout(timeout); + assert.deepStrictEqual( + [Response, Request, Headers, FormData, Blob, AbortSignal, AbortController, Event, TextDecoder] + .map(constructor => constructor.prototype as object) + .concat(Object.getPrototypeOf(timeout)) + .map(prototype => { + const { value, ...attributes } = Object.getOwnPropertyDescriptor(prototype, custom)!; + return [value.name, value.length, attributes]; + }), + Array.from({ length: 10 }, () => [ + "[nodejs.util.inspect.custom]", + 2, + { writable: true, enumerable: false, configurable: true }, + ]), + ); + }); +}); + +// The assertions about these methods in the tests of Node.js v26.3.0. Event has its own in test/js/node/test/parallel. +describe("upstream", () => { + test("node: test-blob.js", () => { + const b = new Blob(); + assert.strictEqual(inspect(b, { depth: null }), "Blob { size: 0, type: '' }"); + assert.strictEqual(inspect(b, { depth: 1 }), "Blob { size: 0, type: '' }"); + assert.strictEqual(inspect(b, { depth: -1 }), "[Blob]"); + }); + + test("node: test-file.js", () => { + const file = new File([], ""); + assert(inspect(file).startsWith("File { size: 0, type: '', name: '', lastModified:")); + }); + + test("node: test-abortcontroller.js, AbortController inspection depth 1 or null works", () => { + const ac = new AbortController(); + assert.strictEqual(inspect(ac, { depth: 1 }), "AbortController { signal: [AbortSignal] }"); + assert.strictEqual(inspect(ac, { depth: null }), "AbortController { signal: AbortSignal { aborted: false } }"); + }); + + test("node: test-whatwg-encoding-custom-textdecoder.js", () => { + // Test TextDecoder inspect with hidden fields + { + const dec = new TextDecoder("utf-8", { ignoreBOM: true }); + assert.strictEqual( + inspect(dec, { showHidden: true }), + differs( + "TextDecoder {\n" + + " encoding: 'utf-8',\n" + + " fatal: false,\n" + + " ignoreBOM: true,\n" + + " Symbol(flags): 4,\n" + + " Symbol(handle): undefined\n" + + "}", + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: true }", + "Bun's TextDecoder has no flags and no handle", + ), + ); + } + + // Test TextDecoder inspect without hidden fields + { + const dec = new TextDecoder("utf-8", { ignoreBOM: true }); + assert.strictEqual( + inspect(dec, { showHidden: false }), + "TextDecoder { encoding: 'utf-8', fatal: false, ignoreBOM: true }", + ); + } + + // Test TextDecoder inspect with negative depth + { + const dec = new TextDecoder(); + assert.strictEqual(inspect(dec, { depth: -1 }), "[TextDecoder]"); + } + + { + const inspectFn = (TextDecoder.prototype as any)[custom]; + const instance = new TextDecoder(); + const expectedError = { + code: "ERR_INVALID_THIS", + name: "TypeError", + message: 'Value of "this" must be of type TextDecoder', + }; + + inspectFn.call(instance, Infinity, {}); + + const invalidThisArgs = [{}, [], true, 1, "", new TextEncoder()]; + invalidThisArgs.forEach(i => { + assert.throws(() => inspectFn.call(i, Infinity, {}), expectedError); + }); + } + }); +}); + +// The text in this file is the text of one version of Node.js. +test("Node.js passes this file", { skip: !isBun }, () => { + const version = spawnSync("node", ["-p", "process.versions.node"], { encoding: "utf8" }); + if (version.status !== 0 || version.stdout.trim() !== process.versions.node) { + // No `node` on the path, or another version: its text for some rows is not this text. + return; + } + const run = spawnSync("node", ["--test", import.meta.filename], { + encoding: "utf8", + env: { ...process.env, FORCE_COLOR: "0", NODE_NO_WARNINGS: "1" }, + }); + assert.strictEqual(run.status, 0, run.stdout.slice(-4000)); +});