From 57253746c37efcda6e9d7ca7110f7cc5cedbb4a9 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Mon, 6 Jan 2025 23:49:19 -0800 Subject: [PATCH 1/2] reduce the import weight of internal/primordials --- src/js/internal/primordials.js | 115 +--------------- src/js/internal/util/inspect.js | 236 ++++++++++++++++---------------- src/js/internal/validators.ts | 2 +- src/js/node/dgram.ts | 24 ++-- src/js/node/http2.ts | 64 ++++----- src/js/node/querystring.ts | 68 +++++---- 6 files changed, 194 insertions(+), 315 deletions(-) diff --git a/src/js/internal/primordials.js b/src/js/internal/primordials.js index 565a056a60de3f..db1b136ff94b15 100644 --- a/src/js/internal/primordials.js +++ b/src/js/internal/primordials.js @@ -2,6 +2,9 @@ // Do not use this file for new code, many things here will be slow especailly when intrinsics for these operations is available. // It is primarily used for `internal/util` +const ObjectSetPrototypeOf = Object.setPrototypeOf; +const ObjectFreeze = Object.freeze; + const createSafeIterator = (factory, next) => { class SafeIterator { constructor(iterable) { @@ -14,9 +17,9 @@ const createSafeIterator = (factory, next) => { return this; } } - Object.setPrototypeOf(SafeIterator.prototype, null); - Object.freeze(SafeIterator.prototype); - Object.freeze(SafeIterator); + ObjectSetPrototypeOf(SafeIterator.prototype, null); + ObjectFreeze(SafeIterator.prototype); + ObjectFreeze(SafeIterator); return SafeIterator; }; @@ -76,86 +79,16 @@ const StringIterator = uncurryThis(String.prototype[Symbol.iterator]); const StringIteratorPrototype = Reflect.getPrototypeOf(StringIterator("")); const ArrayPrototypeForEach = uncurryThis(Array.prototype.forEach); -function ErrorCaptureStackTrace(targetObject) { - const stack = new Error().stack; - // Remove the second line, which is this function - targetObject.stack = stack.replace(/.*\n.*/, "$1"); -} - -const arrayProtoPush = Array.prototype.push; const ArrayPrototypeSymbolIterator = uncurryThis(Array.prototype[Symbol.iterator]); const ArrayIteratorPrototypeNext = uncurryThis(ArrayPrototypeSymbolIterator.next); + export default { - makeSafe, // exported for testing Array, - ArrayFrom: Array.from, - ArrayIsArray: Array.isArray, SafeArrayIterator: createSafeIterator(ArrayPrototypeSymbolIterator, ArrayIteratorPrototypeNext), - ArrayPrototypeFlat: uncurryThis(Array.prototype.flat), - ArrayPrototypeFilter: uncurryThis(Array.prototype.filter), - ArrayPrototypeForEach, - ArrayPrototypeIncludes: uncurryThis(Array.prototype.includes), - ArrayPrototypeIndexOf: uncurryThis(Array.prototype.indexOf), - ArrayPrototypeJoin: uncurryThis(Array.prototype.join), - ArrayPrototypeMap: uncurryThis(Array.prototype.map), - ArrayPrototypePop: uncurryThis(Array.prototype.pop), - ArrayPrototypePush: uncurryThis(arrayProtoPush), - ArrayPrototypePushApply: (a, b) => arrayProtoPush.$apply(a, b), - ArrayPrototypeSlice: uncurryThis(Array.prototype.slice), - ArrayPrototypeSort: uncurryThis(Array.prototype.sort), - ArrayPrototypeSplice: uncurryThis(Array.prototype.splice), - ArrayPrototypeUnshift: uncurryThis(Array.prototype.unshift), - BigIntPrototypeValueOf: uncurryThis(BigInt.prototype.valueOf), - BooleanPrototypeValueOf: uncurryThis(Boolean.prototype.valueOf), - DatePrototypeGetTime: uncurryThis(Date.prototype.getTime), - DatePrototypeToISOString: uncurryThis(Date.prototype.toISOString), - DatePrototypeToString: uncurryThis(Date.prototype.toString), - ErrorCaptureStackTrace, - ErrorPrototypeToString: uncurryThis(Error.prototype.toString), - FunctionPrototypeToString: uncurryThis(Function.prototype.toString), - JSONStringify: JSON.stringify, MapPrototypeGetSize: getGetter(Map, "size"), - MapPrototypeEntries: uncurryThis(Map.prototype.entries), - MapPrototypeValues: uncurryThis(Map.prototype.values), - MapPrototypeKeys: uncurryThis(Map.prototype.keys), - MathFloor: Math.floor, - MathMax: Math.max, - MathMin: Math.min, - MathRound: Math.round, - MathSqrt: Math.sqrt, - MathTrunc: Math.trunc, - MathAbs: Math.abs, Number, - NumberIsFinite: Number.isFinite, - NumberIsNaN: Number.isNaN, - NumberParseFloat: Number.parseFloat, - NumberParseInt: Number.parseInt, - NumberPrototypeToString: uncurryThis(Number.prototype.toString), - NumberPrototypeValueOf: uncurryThis(Number.prototype.valueOf), Object, - ObjectAssign: Object.assign, - ObjectCreate: Object.create, - ObjectDefineProperty: Object.defineProperty, - ObjectEntries: Object.entries, - ObjectGetOwnPropertyDescriptor: Object.getOwnPropertyDescriptor, - ObjectGetOwnPropertyDescriptors: Object.getOwnPropertyDescriptors, - ObjectGetOwnPropertyNames: Object.getOwnPropertyNames, - ObjectGetOwnPropertySymbols: Object.getOwnPropertySymbols, - ObjectGetPrototypeOf: Object.getPrototypeOf, - ObjectIs: Object.is, - ObjectKeys: Object.keys, - ObjectPrototypeHasOwnProperty: uncurryThis(Object.prototype.hasOwnProperty), - ObjectPrototypePropertyIsEnumerable: uncurryThis(Object.prototype.propertyIsEnumerable), - ObjectPrototypeToString: uncurryThis(Object.prototype.toString), - ObjectSeal: Object.seal, - ObjectSetPrototypeOf: Object.setPrototypeOf, - ReflectOwnKeys: Reflect.ownKeys, RegExp, - RegExpPrototypeExec: uncurryThis(RegExp.prototype.exec), - RegExpPrototypeSymbolReplace: uncurryThis(RegExp.prototype[Symbol.replace]), - RegExpPrototypeSymbolSplit: uncurryThis(RegExp.prototype[Symbol.split]), - RegExpPrototypeTest: uncurryThis(RegExp.prototype.test), - RegExpPrototypeToString: uncurryThis(RegExp.prototype.toString), SafeStringIterator: createSafeIterator(StringIterator, uncurryThis(StringIteratorPrototype.next)), SafeMap: makeSafe( Map, @@ -173,42 +106,8 @@ export default { } }, ), - DatePrototypeGetMilliseconds: uncurryThis(Date.prototype.getMilliseconds), - DatePrototypeToUTCString: uncurryThis(Date.prototype.toUTCString), SetPrototypeGetSize: getGetter(Set, "size"), - SetPrototypeEntries: uncurryThis(Set.prototype.entries), - SetPrototypeValues: uncurryThis(Set.prototype.values), String, - StringPrototypeCharCodeAt: uncurryThis(String.prototype.charCodeAt), - StringPrototypeCodePointAt: uncurryThis(String.prototype.codePointAt), - StringPrototypeEndsWith: uncurryThis(String.prototype.endsWith), - StringPrototypeIncludes: uncurryThis(String.prototype.includes), - StringPrototypeIndexOf: uncurryThis(String.prototype.indexOf), - StringPrototypeLastIndexOf: uncurryThis(String.prototype.lastIndexOf), - StringPrototypeMatch: uncurryThis(String.prototype.match), - StringPrototypeNormalize: uncurryThis(String.prototype.normalize), - StringPrototypePadEnd: uncurryThis(String.prototype.padEnd), - StringPrototypePadStart: uncurryThis(String.prototype.padStart), - StringPrototypeRepeat: uncurryThis(String.prototype.repeat), - StringPrototypeReplace: uncurryThis(String.prototype.replace), - StringPrototypeReplaceAll: uncurryThis(String.prototype.replaceAll), - StringPrototypeSlice: uncurryThis(String.prototype.slice), - StringPrototypeSplit: uncurryThis(String.prototype.split), - StringPrototypeStartsWith: uncurryThis(String.prototype.startsWith), - StringPrototypeToLowerCase: uncurryThis(String.prototype.toLowerCase), - StringPrototypeToUpperCase: uncurryThis(String.prototype.toUpperCase), - StringPrototypeTrim: uncurryThis(String.prototype.trim), - StringPrototypeValueOf: uncurryThis(String.prototype.valueOf), - SymbolPrototypeToString: uncurryThis(Symbol.prototype.toString), - SymbolPrototypeValueOf: uncurryThis(Symbol.prototype.valueOf), - FunctionPrototypeToString: uncurryThis(Function.prototype.toString), - FunctionPrototypeBind: uncurryThis(Function.prototype.bind), - SymbolDispose: Symbol.dispose, - SymbolAsyncDispose: Symbol.asyncDispose, - SymbolIterator: Symbol.iterator, - SymbolAsyncIterator: Symbol.asyncIterator, - SymbolFor: Symbol.for, - SymbolToStringTag: Symbol.toStringTag, TypedArrayPrototypeGetLength: getGetter(Uint8Array, "length"), TypedArrayPrototypeGetSymbolToStringTag: getGetter(Uint8Array, Symbol.toStringTag), Uint8ClampedArray, diff --git a/src/js/internal/util/inspect.js b/src/js/internal/util/inspect.js index f98354aae01343..e632119bfb42a7 100644 --- a/src/js/internal/util/inspect.js +++ b/src/js/internal/util/inspect.js @@ -34,106 +34,100 @@ const { pathToFileURL } = require("node:url"); let BufferModule; const primordials = require("internal/primordials"); +const { uncurryThis } = primordials; const { - Array, - ArrayFrom, - ArrayPrototypeFilter, - ArrayPrototypeFlat, - ArrayPrototypeForEach, - ArrayPrototypeIncludes, - ArrayPrototypeIndexOf, - ArrayPrototypeJoin, - ArrayPrototypeMap, - ArrayPrototypePop, - ArrayPrototypePush, - ArrayPrototypePushApply, - ArrayPrototypeSlice, - ArrayPrototypeSplice, - ArrayPrototypeSort, - ArrayPrototypeUnshift, - BigIntPrototypeValueOf, - BooleanPrototypeValueOf, - DatePrototypeGetTime, - DatePrototypeToISOString, - DatePrototypeToString, - ErrorCaptureStackTrace, - ErrorPrototypeToString, - FunctionPrototypeBind, - FunctionPrototypeToString, - JSONStringify, MapPrototypeGetSize, - MapPrototypeEntries, - MapPrototypeValues, - MapPrototypeKeys, - MathFloor, - MathMax, - MathMin, - MathRound, - MathSqrt, - MathTrunc, - Number, - NumberIsFinite, - NumberIsNaN, - NumberParseFloat, - NumberParseInt, - NumberPrototypeToString, - NumberPrototypeValueOf, - Object, - ObjectAssign, - ObjectDefineProperty, - ObjectEntries, - ObjectGetOwnPropertyDescriptor, - ObjectGetOwnPropertyDescriptors, - ObjectGetOwnPropertyNames, - ObjectGetOwnPropertySymbols, - ObjectGetPrototypeOf, - ObjectIs, - ObjectKeys, - ObjectPrototypeHasOwnProperty, - ObjectPrototypePropertyIsEnumerable, - ObjectPrototypeToString, - ObjectSeal, - ObjectSetPrototypeOf, - ReflectOwnKeys, - RegExp, - RegExpPrototypeExec, - RegExpPrototypeSymbolReplace, - RegExpPrototypeSymbolSplit, - RegExpPrototypeTest, - RegExpPrototypeToString, SafeMap, SafeSet, - SetPrototypeEntries, SetPrototypeGetSize, - SetPrototypeValues, - String, - StringPrototypeCharCodeAt, - StringPrototypeCodePointAt, - StringPrototypeIncludes, - StringPrototypeIndexOf, - StringPrototypeLastIndexOf, - StringPrototypeMatch, - StringPrototypeNormalize, - StringPrototypePadEnd, - StringPrototypePadStart, - StringPrototypeRepeat, - StringPrototypeReplaceAll, - StringPrototypeSlice, - StringPrototypeSplit, - StringPrototypeEndsWith, - StringPrototypeStartsWith, - StringPrototypeToLowerCase, - StringPrototypeTrim, - StringPrototypeValueOf, - SymbolPrototypeToString, - SymbolPrototypeValueOf, - SymbolIterator, - SymbolToStringTag, TypedArrayPrototypeGetLength, TypedArrayPrototypeGetSymbolToStringTag, - Uint8Array, } = primordials; +const ArrayFrom = Array.from; +const ArrayPrototypeFilter = uncurryThis(Array.prototype.filter); +const ArrayPrototypeFlat = uncurryThis(Array.prototype.flat); +const ArrayPrototypeForEach = uncurryThis(Array.prototype.forEach); +const ArrayPrototypeIncludes = uncurryThis(Array.prototype.includes); +const ArrayPrototypeIndexOf = uncurryThis(Array.prototype.indexOf); +const ArrayPrototypeJoin = uncurryThis(Array.prototype.join); +const ArrayPrototypeMap = uncurryThis(Array.prototype.map); +const ArrayPrototypePop = uncurryThis(Array.prototype.pop); +const ArrayPrototypePush = Array.prototype.push; +const ArrayPrototypeSlice = uncurryThis(Array.prototype.slice); +const ArrayPrototypeSplice = uncurryThis(Array.prototype.splice); +const ArrayPrototypeSort = uncurryThis(Array.prototype.sort); +const ArrayPrototypeUnshift = uncurryThis(Array.prototype.unshift); +const BigIntPrototypeValueOf = uncurryThis(BigInt.prototype.valueOf); +const BooleanPrototypeValueOf = uncurryThis(Boolean.prototype.valueOf); +const DatePrototypeGetTime = uncurryThis(Date.prototype.getTime); +const DatePrototypeToISOString = uncurryThis(Date.prototype.toISOString); +const DatePrototypeToString = uncurryThis(Date.prototype.toString); +const ErrorCaptureStackTrace = Error.captureStackTrace; +const ErrorPrototypeToString = uncurryThis(Error.prototype.toString); +const FunctionPrototypeBind = uncurryThis(Function.prototype.bind); +const FunctionPrototypeToString = uncurryThis(Function.prototype.toString); +const JSONStringify = JSON.stringify; +const MapPrototypeEntries = uncurryThis(Map.prototype.entries); +const MapPrototypeValues = uncurryThis(Map.prototype.values); +const MapPrototypeKeys = uncurryThis(Map.prototype.keys); +const MathFloor = Math.floor; +const MathMax = Math.max; +const MathMin = Math.min; +const MathRound = Math.round; +const MathSqrt = Math.sqrt; +const MathTrunc = Math.trunc; +const NumberIsFinite = Number.isFinite; +const NumberIsNaN = Number.isNaN; +const NumberParseFloat = Number.parseFloat; +const NumberParseInt = Number.parseInt; +const NumberPrototypeToString = uncurryThis(Number.prototype.toString); +const NumberPrototypeValueOf = uncurryThis(Number.prototype.valueOf); +const ObjectAssign = Object.assign; +const ObjectDefineProperty = Object.defineProperty; +const ObjectEntries = Object.entries; +const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +const ObjectGetOwnPropertyDescriptors = Object.getOwnPropertyDescriptors; +const ObjectGetOwnPropertyNames = Object.getOwnPropertyNames; +const ObjectGetOwnPropertySymbols = Object.getOwnPropertySymbols; +const ObjectGetPrototypeOf = Object.getPrototypeOf; +const ObjectIs = Object.is; +const ObjectKeys = Object.keys; +const ObjectPrototypeHasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); +const ObjectPrototypePropertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); +const ObjectPrototypeToString = uncurryThis(Object.prototype.toString); +const ObjectSeal = Object.seal; +const ObjectSetPrototypeOf = Object.setPrototypeOf; +const ReflectOwnKeys = Reflect.ownKeys; +const RegExpPrototypeExec = uncurryThis(RegExp.prototype.exec); +const RegExpPrototypeSymbolReplace = uncurryThis(RegExp.prototype[Symbol.replace]); +const RegExpPrototypeSymbolSplit = uncurryThis(RegExp.prototype[Symbol.split]); +const RegExpPrototypeTest = uncurryThis(RegExp.prototype.test); +const RegExpPrototypeToString = uncurryThis(RegExp.prototype.toString); +const SetPrototypeEntries = uncurryThis(Set.prototype.entries); +const SetPrototypeValues = uncurryThis(Set.prototype.values); +const StringPrototypeCharCodeAt = uncurryThis(String.prototype.charCodeAt); +const StringPrototypeIncludes = uncurryThis(String.prototype.includes); +const StringPrototypeIndexOf = uncurryThis(String.prototype.indexOf); +const StringPrototypeLastIndexOf = uncurryThis(String.prototype.lastIndexOf); +const StringPrototypeMatch = uncurryThis(String.prototype.match); +const StringPrototypeNormalize = uncurryThis(String.prototype.normalize); +const StringPrototypePadEnd = uncurryThis(String.prototype.padEnd); +const StringPrototypePadStart = uncurryThis(String.prototype.padStart); +const StringPrototypeRepeat = uncurryThis(String.prototype.repeat); +const StringPrototypeReplaceAll = uncurryThis(String.prototype.replaceAll); +const StringPrototypeSlice = uncurryThis(String.prototype.slice); +const StringPrototypeSplit = uncurryThis(String.prototype.split); +const StringPrototypeEndsWith = uncurryThis(String.prototype.endsWith); +const StringPrototypeStartsWith = uncurryThis(String.prototype.startsWith); +const StringPrototypeToLowerCase = uncurryThis(String.prototype.toLowerCase); +const StringPrototypeTrim = uncurryThis(String.prototype.trim); +const StringPrototypeValueOf = uncurryThis(String.prototype.valueOf); +const SymbolPrototypeToString = uncurryThis(Symbol.prototype.toString); +const SymbolPrototypeValueOf = uncurryThis(Symbol.prototype.valueOf); +const SymbolIterator = Symbol.iterator; +const SymbolToStringTag = Symbol.toStringTag; + const customInspectSymbol = Symbol.for("nodejs.util.inspect.custom"); const kPending = Symbol("kPending"); // state ID 0 const kFulfilled = Symbol("kFulfilled"); // state ID 1 @@ -266,11 +260,11 @@ const codes = {}; // exported from errors.js const other = []; for (const value of expected) { assert(typeof value === "string", "All expected entries have to be of type string"); - if (ArrayPrototypeIncludes(kTypes, value)) ArrayPrototypePush(types, StringPrototypeToLowerCase(value)); - else if (RegExpPrototypeTest(classRegExp, value)) ArrayPrototypePush(instances, value); + if (ArrayPrototypeIncludes(kTypes, value)) ArrayPrototypePush.$call(types, StringPrototypeToLowerCase(value)); + else if (RegExpPrototypeTest(classRegExp, value)) ArrayPrototypePush.$call(instances, value); else { assert(value !== "object", 'The value "object" should be written as "Object"'); - ArrayPrototypePush(other, value); + ArrayPrototypePush.$call(other, value); } } // Special handle `object` in case other instances are allowed to outline the differences between each other. @@ -278,7 +272,7 @@ const codes = {}; // exported from errors.js const pos = ArrayPrototypeIndexOf(types, "object"); if (pos !== -1) { ArrayPrototypeSplice(types, pos, 1); - ArrayPrototypePush(instances, "Object"); + ArrayPrototypePush.$call(instances, "Object"); } } if (types.length > 0) { @@ -1047,7 +1041,7 @@ function addPrototypeProperties(ctx, main, obj, recurseTimes, output) { } // Get all own property names and symbols. keys = ReflectOwnKeys(obj); - ArrayPrototypePush(ctx.seen, main); + ArrayPrototypePush.$call(ctx.seen, main); for (const key of keys) { // Ignore the `constructor` property and keys that exist on layers above. if (key === "constructor" || ObjectPrototypeHasOwnProperty(main, key) || (depth !== 0 && keySet.has(key))) { @@ -1060,9 +1054,9 @@ function addPrototypeProperties(ctx, main, obj, recurseTimes, output) { const value = formatProperty(ctx, obj, recurseTimes, key, kObjectType, desc, main); if (ctx.colors) { // Faint! - ArrayPrototypePush(output, `\u001b[2m${value}\u001b[22m`); + ArrayPrototypePush.$call(output, `\u001b[2m${value}\u001b[22m`); } else { - ArrayPrototypePush(output, value); + ArrayPrototypePush.$call(output, value); } } ArrayPrototypePop(ctx.seen); @@ -1092,7 +1086,7 @@ function getKeys(value, showHidden) { const symbols = ObjectGetOwnPropertySymbols(value); if (showHidden) { keys = ObjectGetOwnPropertyNames(value); - if (symbols.length !== 0) ArrayPrototypePushApply(keys, symbols); + if (symbols.length !== 0) ArrayPrototypePush.$apply(keys, symbols); } else { // This might throw if `value` is a Module Namespace Object from an // unevaluated module, but we don't want to perform the actual type @@ -1107,7 +1101,7 @@ function getKeys(value, showHidden) { } if (symbols.length !== 0) { const filter = key => ObjectPrototypePropertyIsEnumerable(value, key); - ArrayPrototypePushApply(keys, ArrayPrototypeFilter(symbols, filter)); + ArrayPrototypePush.$apply(keys, ArrayPrototypeFilter(symbols, filter)); } } return keys; @@ -1399,10 +1393,10 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { if (ctx.currentDepth > 1000) throw new RangeError(ERROR_STACK_OVERFLOW_MSG); output = formatter(ctx, value, recurseTimes); for (i = 0; i < keys.length; i++) { - ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, keys[i], extrasType)); + ArrayPrototypePush.$call(output, formatProperty(ctx, value, recurseTimes, keys[i], extrasType)); } if (protoProps !== undefined) { - ArrayPrototypePushApply(output, protoProps); + ArrayPrototypePush.$apply(output, protoProps); } } catch (err) { if (err instanceof RangeError && err.message === ERROR_STACK_OVERFLOW_MSG) { @@ -1742,12 +1736,12 @@ function formatError(err, constructor, tag, ctx, keys) { removeDuplicateErrorKeys(ctx, keys, err, stack); if ("cause" in err && (keys.length === 0 || !ArrayPrototypeIncludes(keys, "cause"))) { - ArrayPrototypePush(keys, "cause"); + ArrayPrototypePush.$call(keys, "cause"); } // Print errors aggregated into AggregateError if ($isJSArray(err.errors) && (keys.length === 0 || !ArrayPrototypeIncludes(keys, "errors"))) { - ArrayPrototypePush(keys, "errors"); + ArrayPrototypePush.$call(keys, "errors"); } stack = improveStack(stack, constructor, name, tag); @@ -1893,10 +1887,10 @@ function groupArrayElements(ctx, output, value) { } else { str += output[j]; } - ArrayPrototypePush(tmp, str); + ArrayPrototypePush.$call(tmp, str); } if (ctx.maxArrayLength < output.length) { - ArrayPrototypePush(tmp, output[outputLength]); + ArrayPrototypePush.$call(tmp, output[outputLength]); } output = tmp; } @@ -2030,13 +2024,13 @@ function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) { const emptyItems = tmp - index; const ending = emptyItems > 1 ? "s" : ""; const message = `<${emptyItems} empty item${ending}>`; - ArrayPrototypePush(output, ctx.stylize(message, "undefined")); + ArrayPrototypePush.$call(output, ctx.stylize(message, "undefined")); index = tmp; if (output.length === maxLength) { break; } } - ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, key, kArrayType)); + ArrayPrototypePush.$call(output, formatProperty(ctx, value, recurseTimes, key, kArrayType)); index++; } const remaining = value.length - index; @@ -2044,10 +2038,10 @@ function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) { if (remaining > 0) { const ending = remaining > 1 ? "s" : ""; const message = `<${remaining} empty item${ending}>`; - ArrayPrototypePush(output, ctx.stylize(message, "undefined")); + ArrayPrototypePush.$call(output, ctx.stylize(message, "undefined")); } } else if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } return output; } @@ -2085,10 +2079,10 @@ function formatArray(ctx, value, recurseTimes) { if (!ObjectPrototypeHasOwnProperty(value, i)) { return formatSpecialArray(ctx, value, recurseTimes, len, output, i); } - ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, i, kArrayType)); + ArrayPrototypePush.$call(output, formatProperty(ctx, value, recurseTimes, i, kArrayType)); } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } return output; } @@ -2115,7 +2109,7 @@ function formatTypedArray(value, length, ctx, ignored, recurseTimes) { ctx.indentationLvl += 2; for (const key of ["BYTES_PER_ELEMENT", "length", "byteLength", "byteOffset", "buffer"]) { const str = formatValue(ctx, value[key], recurseTimes, true); - ArrayPrototypePush(output, `[${key}]: ${str}`); + ArrayPrototypePush.$call(output, `[${key}]: ${str}`); } ctx.indentationLvl -= 2; } @@ -2131,11 +2125,11 @@ function formatSet(value, ctx, ignored, recurseTimes) { let i = 0; for (const v of value) { if (i >= maxLength) break; - ArrayPrototypePush(output, formatValue(ctx, v, recurseTimes)); + ArrayPrototypePush.$call(output, formatValue(ctx, v, recurseTimes)); i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } ctx.indentationLvl -= 2; return output; @@ -2150,11 +2144,11 @@ function formatMap(value, ctx, ignored, recurseTimes) { let i = 0; for (const { 0: k, 1: v } of value) { if (i >= maxLength) break; - ArrayPrototypePush(output, `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`); + ArrayPrototypePush.$call(output, `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`); i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } ctx.indentationLvl -= 2; return output; @@ -2177,7 +2171,7 @@ function formatSetIterInner(ctx, recurseTimes, entries, state) { } const remaining = entries.length - maxLength; if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } return output; } @@ -2213,7 +2207,7 @@ function formatMapIterInner(ctx, recurseTimes, entries, state) { } ctx.indentationLvl -= 2; if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + ArrayPrototypePush.$call(output, remainingText(remaining)); } return output; } @@ -2630,13 +2624,13 @@ function getOwnNonIndexProperties(a, filter = ONLY_ENUMERABLE) { if (!RegExpPrototypeTest(/^(0|[1-9][0-9]*)$/, k) || NumberParseInt(k, 10) >= 2 ** 32 - 1) { // Arrays are limited in size if (filter === ONLY_ENUMERABLE && !v.enumerable) continue; - else ArrayPrototypePush(ret, k); + else ArrayPrototypePush.$call(ret, k); } } for (const s of ObjectGetOwnPropertySymbols(a)) { const v = ObjectGetOwnPropertyDescriptor(a, s); if (filter === ONLY_ENUMERABLE && !v.enumerable) continue; - ArrayPrototypePush(ret, s); + ArrayPrototypePush.$call(ret, s); } return ret; } diff --git a/src/js/internal/validators.ts b/src/js/internal/validators.ts index 414b943e7f4e0f..ac0ed66f91573a 100644 --- a/src/js/internal/validators.ts +++ b/src/js/internal/validators.ts @@ -1,10 +1,10 @@ const { hideFromStack } = require("internal/shared"); -const { ArrayIsArray } = require("internal/primordials"); const RegExpPrototypeExec = RegExp.prototype.exec; const ArrayPrototypeIncludes = Array.prototype.includes; const ArrayPrototypeJoin = Array.prototype.join; const ArrayPrototypeMap = Array.prototype.map; +const ArrayIsArray = Array.isArray; const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; /** diff --git a/src/js/node/dgram.ts b/src/js/node/dgram.ts index ed652132e50060..bce9debb419599 100644 --- a/src/js/node/dgram.ts +++ b/src/js/node/dgram.ts @@ -42,17 +42,13 @@ const { validateAbortSignal, } = require("internal/validators"); -const { - FunctionPrototypeBind, - ObjectSetPrototypeOf, - SymbolAsyncDispose, - SymbolDispose, - StringPrototypeTrim, - NumberIsNaN, -} = require("internal/primordials"); - const EventEmitter = require("node:events"); +const SymbolDispose = Symbol.dispose; +const SymbolAsyncDispose = Symbol.asyncDispose; +const ObjectSetPrototypeOf = Object.setPrototypeOf; +const FunctionPrototypeBind = Function.prototype.bind; + class ERR_SOCKET_BUFFER_SIZE extends Error { constructor(ctx) { super(`Invalid buffer size: ${ctx}`); @@ -92,9 +88,9 @@ function newHandle(type, lookup) { const handle = {}; if (type === "udp4") { - handle.lookup = FunctionPrototypeBind(lookup4, handle, lookup); + handle.lookup = FunctionPrototypeBind.$call(lookup4, handle, lookup); } else if (type === "udp6") { - handle.lookup = FunctionPrototypeBind(lookup6, handle, lookup); + handle.lookup = FunctionPrototypeBind.$call(lookup6, handle, lookup); } else { throw $ERR_SOCKET_BAD_TYPE(); } @@ -328,7 +324,7 @@ Socket.prototype.connect = function (port, address, callback) { if (state.bindState === BIND_STATE_UNBOUND) this.bind({ port: 0, exclusive: true }, null); if (state.bindState !== BIND_STATE_BOUND) { - enqueue(this, FunctionPrototypeBind(_connect, this, port, address, callback)); + enqueue(this, FunctionPrototypeBind.$call(_connect, this, port, address, callback)); return; } @@ -534,7 +530,7 @@ Socket.prototype.send = function (buffer, offset, length, port, address, callbac // If the socket hasn't been bound yet, push the outbound packet onto the // send queue and send after binding is complete. if (state.bindState !== BIND_STATE_BOUND) { - enqueue(this, FunctionPrototypeBind(this.send, this, list, port, address, callback)); + enqueue(this, FunctionPrototypeBind.$call(this.send, this, list, port, address, callback)); return; } @@ -642,7 +638,7 @@ Socket.prototype.close = function (callback) { if (typeof callback === "function") this.on("close", callback); if (queue !== undefined) { - queue.push(FunctionPrototypeBind(this.close, this)); + queue.push(FunctionPrototypeBind.$call(this.close, this)); return this; } diff --git a/src/js/node/http2.ts b/src/js/node/http2.ts index bb7544bdbceb0b..aac7f7f0431960 100644 --- a/src/js/node/http2.ts +++ b/src/js/node/http2.ts @@ -1,8 +1,6 @@ // Hardcoded module "node:http2" const { isTypedArray } = require("node:util/types"); - -// This is a stub! None of this is actually implemented yet. const { hideFromStack, throwNotImplemented } = require("internal/shared"); const tls = require("node:tls"); @@ -24,22 +22,20 @@ const Socket = net.Socket; const EventEmitter = require("node:events"); const { Duplex } = require("node:stream"); -const { - FunctionPrototypeBind, - StringPrototypeTrim, - ArrayPrototypePush, - ObjectAssign, - ArrayIsArray, - SafeArrayIterator, - StringPrototypeToLowerCase, - StringPrototypeIncludes, - ObjectKeys, - ObjectPrototypeHasOwnProperty, - SafeSet, - DatePrototypeToUTCString, - DatePrototypeGetMilliseconds, -} = require("internal/primordials"); +const { SafeArrayIterator, SafeSet } = require("internal/primordials"); + const RegExpPrototypeExec = RegExp.prototype.exec; +const ObjectAssign = Object.assign; +const ArrayIsArray = Array.isArray; +const ObjectKeys = Object.keys; +const FunctionPrototypeBind = Function.prototype.bind; +const StringPrototypeTrim = String.prototype.trim; +const ArrayPrototypePush = Array.prototype.push; +const StringPrototypeToLowerCase = String.prototype.toLocaleLowerCase; +const StringPrototypeIncludes = String.prototype.includes; +const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; +const DatePrototypeToUTCString = Date.prototype.toUTCString; +const DatePrototypeGetMilliseconds = Date.prototype.getMilliseconds; const [H2FrameParser, assertSettings, getPackedSettings, getUnpackedSettings] = $zig( "h2_frame_parser.zig", @@ -91,8 +87,8 @@ function utcDate() { function cache() { const d = new Date(); - utcCache = DatePrototypeToUTCString(d); - setTimeout(resetCache, 1000 - DatePrototypeGetMilliseconds(d)).unref(); + utcCache = DatePrototypeToUTCString.$call(d); + setTimeout(resetCache, 1000 - DatePrototypeGetMilliseconds.call(d)).unref(); } function resetCache() { @@ -116,7 +112,7 @@ function onStreamTrailers(trailers, flags, rawTrailers) { const request = this[kRequest]; if (request !== undefined) { ObjectAssign(request[kTrailers], trailers); - ArrayPrototypePush(request[kRawTrailers], ...new SafeArrayIterator(rawTrailers)); + ArrayPrototypePush.$call(request[kRawTrailers], ...new SafeArrayIterator(rawTrailers)); } } @@ -240,7 +236,7 @@ function connectionHeaderMessageWarn() { } function assertValidHeader(name, value) { - if (name === "" || typeof name !== "string" || StringPrototypeIncludes(name, " ")) { + if (name === "" || typeof name !== "string" || StringPrototypeIncludes.$call(name, " ")) { throw $ERR_INVALID_HTTP_TOKEN(`The arguments Header name is invalid. Received ${name}`); } if (isPseudoHeader(name)) { @@ -349,7 +345,7 @@ class Http2ServerRequest extends Readable { set method(method) { validateString(method, "method"); - if (StringPrototypeTrim(method) === "") + if (StringPrototypeTrim.$call(method) === "") throw $ERR_INVALID_ARG_VALUE(`The arguments method is invalid. Received ${method}`); this[kHeaders][HTTP2_HEADER_METHOD] = method; @@ -474,7 +470,7 @@ class Http2ServerResponse extends Stream { setTrailer(name, value) { validateString(name, "name"); - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); assertValidHeader(name, value); this[kTrailers][name] = value; } @@ -490,7 +486,7 @@ class Http2ServerResponse extends Stream { getHeader(name) { validateString(name, "name"); - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); return this[kHeaders][name]; } @@ -505,15 +501,15 @@ class Http2ServerResponse extends Stream { hasHeader(name) { validateString(name, "name"); - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); - return ObjectPrototypeHasOwnProperty(this[kHeaders], name); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); + return ObjectPrototypeHasOwnProperty.$call(this[kHeaders], name); } removeHeader(name) { validateString(name, "name"); if (this[kStream].headersSent) throw $ERR_HTTP2_HEADERS_SENT("Response has already been initiated"); - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); if (name === "date") { this[kState].sendDate = false; @@ -532,7 +528,7 @@ class Http2ServerResponse extends Stream { } [kSetHeader](name, value) { - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); assertValidHeader(name, value); if (!isConnectionHeaderAllowed(name, value)) { @@ -554,7 +550,7 @@ class Http2ServerResponse extends Stream { } [kAppendHeader](name, value) { - name = StringPrototypeToLowerCase(StringPrototypeTrim(name)); + name = StringPrototypeToLowerCase.$call(StringPrototypeTrim.$call(name)); assertValidHeader(name, value); if (!isConnectionHeaderAllowed(name, value)) { @@ -852,7 +848,7 @@ const proxySocketHandler = { case "setTimeout": case "ref": case "unref": - return FunctionPrototypeBind(session[prop], session); + return FunctionPrototypeBind.$call(session[prop], session); case "destroy": case "emit": case "end": @@ -872,7 +868,7 @@ const proxySocketHandler = { throw $ERR_HTTP2_SOCKET_UNBOUND("The socket has been disconnected from the Http2Session"); } const value = socket[prop]; - return typeof value === "function" ? FunctionPrototypeBind(value, socket) : value; + return typeof value === "function" ? FunctionPrototypeBind.$call(value, socket) : value; } } }, @@ -2073,7 +2069,7 @@ class ServerHttp2Stream extends Http2Stream { if (!this[kInfoHeaders]) { this[kInfoHeaders] = [headers]; } else { - ArrayPrototypePush(this[kInfoHeaders], headers); + ArrayPrototypePush.$call(this[kInfoHeaders], headers); } session[bunHTTP2Native]?.request(this.id, undefined, headers, sensitiveNames); @@ -2191,7 +2187,7 @@ function toHeaderObject(headers, sensitiveHeadersValue) { // fields with the same name. Since it cannot be combined into a // single field-value, recipients ought to handle "Set-Cookie" as a // special case while processing header fields." - ArrayPrototypePush(existing, value); + ArrayPrototypePush.$call(existing, value); break; default: // https://tools.ietf.org/html/rfc7230#section-3.2.2 @@ -3171,7 +3167,7 @@ function setupCompat(ev) { const options = this[bunSocketServerOptions]; const ServerRequest = options?.Http2ServerRequest || Http2ServerRequest; const ServerResponse = options?.Http2ServerResponse || Http2ServerResponse; - this.on("stream", FunctionPrototypeBind(onServerStream, this, ServerRequest, ServerResponse)); + this.on("stream", FunctionPrototypeBind.$call(onServerStream, this, ServerRequest, ServerResponse)); } } diff --git a/src/js/node/querystring.ts b/src/js/node/querystring.ts index 21d16fb44172b7..d91e69f0a4b6e0 100644 --- a/src/js/node/querystring.ts +++ b/src/js/node/querystring.ts @@ -19,28 +19,22 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +const { Buffer } = require("node:buffer"); + +const ArrayIsArray = Array.isArray; +const MathAbs = Math.abs; +const NumberIsFinite = Number.isFinite; +const ObjectKeys = Object.keys; +const StringPrototypeCharCodeAt = String.prototype.charCodeAt; +const StringPrototypeSlice = String.prototype.slice; +const StringPrototypeToUpperCase = String.prototype.toUpperCase; +const NumberPrototypeToString = Number.prototype.toString; + var __commonJS = (cb, mod: typeof module | undefined = undefined) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); var require_src = __commonJS((exports, module) => { - const { - Array, - ArrayIsArray, - Int8Array, - MathAbs, - NumberIsFinite, - ObjectKeys, - String, - StringPrototypeCharCodeAt, - StringPrototypeSlice, - decodeURIComponent, - StringPrototypeToUpperCase, - NumberPrototypeToString, - } = require("internal/primordials"); - - const { Buffer } = require("node:buffer"); - /** * @param {string} str * @param {Int8Array} noEscapeTable @@ -56,22 +50,22 @@ var require_src = __commonJS((exports, module) => { let i = 0; outer: for (; i < len; i++) { - let c = StringPrototypeCharCodeAt(str, i); + let c = StringPrototypeCharCodeAt.$call(str, i); // ASCII while (c < 0x80) { if (noEscapeTable[c] !== 1) { - if (lastPos < i) out += StringPrototypeSlice(str, lastPos, i); + if (lastPos < i) out += StringPrototypeSlice.$call(str, lastPos, i); lastPos = i + 1; out += hexTable[c]; } if (++i === len) break outer; - c = StringPrototypeCharCodeAt(str, i); + c = StringPrototypeCharCodeAt.$call(str, i); } - if (lastPos < i) out += StringPrototypeSlice(str, lastPos, i); + if (lastPos < i) out += StringPrototypeSlice.$call(str, lastPos, i); // Multi-byte characters ... if (c < 0x800) { @@ -92,7 +86,7 @@ var require_src = __commonJS((exports, module) => { // completion's sake anyway. if (i >= len) throw $ERR_INVALID_URI("URI malformed"); - const c2 = StringPrototypeCharCodeAt(str, i) & 0x3ff; + const c2 = StringPrototypeCharCodeAt.$call(str, i) & 0x3ff; lastPos = i + 1; c = 0x10000 + (((c & 0x3ff) << 10) | c2); @@ -103,13 +97,13 @@ var require_src = __commonJS((exports, module) => { hexTable[0x80 | (c & 0x3f)]; } if (lastPos === 0) return str; - if (lastPos < len) return out + StringPrototypeSlice(str, lastPos); + if (lastPos < len) return out + StringPrototypeSlice.$call(str, lastPos); return out; } const hexTable = new Array(256); for (let i = 0; i < 256; ++i) - hexTable[i] = "%" + StringPrototypeToUpperCase((i < 16 ? "0" : "") + NumberPrototypeToString(i, 16)); + hexTable[i] = "%" + StringPrototypeToUpperCase.$call((i < 16 ? "0" : "") + NumberPrototypeToString.$call(i, 16)); // prettier-ignore const isHexTable = new Int8Array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 @@ -181,20 +175,20 @@ var require_src = __commonJS((exports, module) => { // Flag to know if some hex chars have been decoded let hasHex = false; while (index < s.length) { - currentChar = StringPrototypeCharCodeAt(s, index); + currentChar = StringPrototypeCharCodeAt.$call(s, index); if (currentChar === 43 /* '+' */ && decodeSpaces) { out[outIndex++] = 32; // ' ' index++; continue; } if (currentChar === 37 /* '%' */ && index < maxLength) { - currentChar = StringPrototypeCharCodeAt(s, ++index); + currentChar = StringPrototypeCharCodeAt.$call(s, ++index); hexHigh = unhexTable[currentChar]; if (!(hexHigh >= 0)) { out[outIndex++] = 37; // '%' continue; } else { - nextChar = StringPrototypeCharCodeAt(s, ++index); + nextChar = StringPrototypeCharCodeAt.$call(s, ++index); hexLow = unhexTable[nextChar]; if (!(hexLow >= 0)) { out[outIndex++] = 37; // '%' @@ -349,9 +343,9 @@ var require_src = __commonJS((exports, module) => { */ function charCodes(str) { if (str.length === 0) return []; - if (str.length === 1) return [StringPrototypeCharCodeAt(str, 0)]; + if (str.length === 1) return [StringPrototypeCharCodeAt.$call(str, 0)]; const ret = new Array(str.length); - for (let i = 0; i < str.length; ++i) ret[i] = StringPrototypeCharCodeAt(str, i); + for (let i = 0; i < str.length; ++i) ret[i] = StringPrototypeCharCodeAt.$call(str, i); return ret; } const defSepCodes = [38]; // & @@ -423,7 +417,7 @@ var require_src = __commonJS((exports, module) => { const plusChar = customDecode ? "%20" : " "; let encodeCheck = 0; for (let i = 0; i < qs.length; ++i) { - const code = StringPrototypeCharCodeAt(qs, i); + const code = StringPrototypeCharCodeAt.$call(qs, i); // Try matching key/value pair separator (e.g. '&') if (code === sepCodes[sepIdx]) { @@ -434,7 +428,7 @@ var require_src = __commonJS((exports, module) => { // We didn't find the (entire) key/value separator if (lastPos < end) { // Treat the substring as part of the key instead of the value - key += StringPrototypeSlice(qs, lastPos, end); + key += StringPrototypeSlice.$call(qs, lastPos, end); } else if (key.length === 0) { // We saw an empty substring between separators if (--pairs === 0) return obj; @@ -443,7 +437,7 @@ var require_src = __commonJS((exports, module) => { continue; } } else if (lastPos < end) { - value += StringPrototypeSlice(qs, lastPos, end); + value += StringPrototypeSlice.$call(qs, lastPos, end); } addKeyVal(obj, key, value, keyEncoded, valEncoded, decode); @@ -463,7 +457,7 @@ var require_src = __commonJS((exports, module) => { if (++eqIdx === eqLen) { // Key/value separator match! const end = i - eqIdx + 1; - if (lastPos < end) key += StringPrototypeSlice(qs, lastPos, end); + if (lastPos < end) key += StringPrototypeSlice.$call(qs, lastPos, end); encodeCheck = 0; lastPos = i + 1; } @@ -487,14 +481,14 @@ var require_src = __commonJS((exports, module) => { } } if (code === 43 /* + */) { - if (lastPos < i) key += StringPrototypeSlice(qs, lastPos, i); + if (lastPos < i) key += StringPrototypeSlice.$call(qs, lastPos, i); key += plusChar; lastPos = i + 1; continue; } } if (code === 43 /* + */) { - if (lastPos < i) value += StringPrototypeSlice(qs, lastPos, i); + if (lastPos < i) value += StringPrototypeSlice.$call(qs, lastPos, i); value += plusChar; lastPos = i + 1; } else if (!valEncoded) { @@ -515,8 +509,8 @@ var require_src = __commonJS((exports, module) => { // Deal with any leftover key or value data if (lastPos < qs.length) { - if (eqIdx < eqLen) key += StringPrototypeSlice(qs, lastPos); - else if (sepIdx < sepLen) value += StringPrototypeSlice(qs, lastPos); + if (eqIdx < eqLen) key += StringPrototypeSlice.$call(qs, lastPos); + else if (sepIdx < sepLen) value += StringPrototypeSlice.$call(qs, lastPos); } else if (eqIdx === 0 && key.length === 0) { // We ended on an empty substring return obj; From 898eb7bb1eb41880856bf60762e8f5e1b7dbb8fc Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Fri, 10 Jan 2025 21:27:57 -0800 Subject: [PATCH 2/2] fix merge error --- src/js/internal/assert/assertion_error.ts | 61 ++++++++-------- src/js/internal/assert/calltracker.ts | 25 +++---- src/js/internal/assert/utils.ts | 16 ----- src/js/node/assert.ts | 84 +++++++++++------------ 4 files changed, 78 insertions(+), 108 deletions(-) diff --git a/src/js/internal/assert/assertion_error.ts b/src/js/internal/assert/assertion_error.ts index 3ee25df569d71f..780e3489152f57 100644 --- a/src/js/internal/assert/assertion_error.ts +++ b/src/js/internal/assert/assertion_error.ts @@ -1,26 +1,21 @@ "use strict"; -const { - ArrayPrototypeJoin, - ArrayPrototypePop, - ArrayPrototypeSlice, - Error, - ErrorCaptureStackTrace, - ObjectAssign, - ObjectDefineProperty, - ObjectGetPrototypeOf, - ObjectPrototypeHasOwnProperty, - String, - StringPrototypeRepeat, - StringPrototypeSlice, - StringPrototypeSplit, -} = require("internal/primordials"); - - const { inspect } = require("internal/util/inspect"); const colors = require("internal/util/colors"); const { validateObject } = require("internal/validators"); +const ErrorCaptureStackTrace = Error.captureStackTrace; +const ObjectAssign = Object.assign; +const ObjectDefineProperty = Object.defineProperty; +const ObjectGetPrototypeOf = Object.getPrototypeOf; +const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; +const ArrayPrototypeJoin = Array.prototype.join; +const ArrayPrototypePop = Array.prototype.pop; +const ArrayPrototypeSlice = Array.prototype.slice; +const StringPrototypeRepeat = String.prototype.repeat; +const StringPrototypeSlice = String.prototype.slice; +const StringPrototypeSplit = String.prototype.split; + declare namespace Internal { const enum Operation { Insert = 0, @@ -63,7 +58,7 @@ function copyError(source) { __proto__: null, value: source.message, }); - if (ObjectPrototypeHasOwnProperty(source, "cause")) { + if (ObjectPrototypeHasOwnProperty.$call(source, "cause")) { let { cause } = source; if (Error.isError(cause)) { @@ -115,7 +110,7 @@ function getColoredMyersDiff(actual, expected) { const header = `${colors.green}actual${colors.white} ${colors.red}expected${colors.white}`; const skipped = false; - // const diff = myersDiff(StringPrototypeSplit(actual, ""), StringPrototypeSplit(expected, "")); + // const diff = myersDiff(StringPrototypeSplit.$call(actual, ""), StringPrototypeSplit.$call(expected, "")); const diff = myersDiff(actual, expected, false, false); let message = printSimpleMyersDiff(diff); @@ -149,7 +144,7 @@ function getStackedDiff(actual, expected) { } if (indicatorIdx !== -1) { - message += `\n${StringPrototypeRepeat(" ", indicatorIdx + 2)}^`; + message += `\n${StringPrototypeRepeat.$call(" ", indicatorIdx + 2)}^`; } } @@ -193,8 +188,8 @@ function createErrDiff(actual, expected, operator, customMessage) { let message = ""; const inspectedActual = inspectValue(actual); const inspectedExpected = inspectValue(expected); - const inspectedSplitActual = StringPrototypeSplit(inspectedActual, "\n"); - const inspectedSplitExpected = StringPrototypeSplit(inspectedExpected, "\n"); + const inspectedSplitActual = StringPrototypeSplit.$call(inspectedActual, "\n"); + const inspectedSplitExpected = StringPrototypeSplit.$call(inspectedExpected, "\n"); const showSimpleDiff = isSimpleDiff(actual, inspectedSplitActual, expected, inspectedSplitExpected); let header = `${colors.green}+ actual${colors.white} ${colors.red}- expected${colors.white}`; @@ -211,10 +206,10 @@ function createErrDiff(actual, expected, operator, customMessage) { // Handles the case where the objects are structurally the same but different references operator = "notIdentical"; if (inspectedSplitActual.length > 50) { - message = `${ArrayPrototypeJoin(ArrayPrototypeSlice(inspectedSplitActual, 0, 50), "\n")}\n...}`; + message = `${ArrayPrototypeJoin.$call(ArrayPrototypeSlice.$call(inspectedSplitActual, 0, 50), "\n")}\n...}`; skipped = true; } else { - message = ArrayPrototypeJoin(inspectedSplitActual, "\n"); + message = ArrayPrototypeJoin.$call(inspectedSplitActual, "\n"); } header = ""; } else { @@ -236,12 +231,12 @@ function createErrDiff(actual, expected, operator, customMessage) { } function addEllipsis(string) { - const lines = StringPrototypeSplit(string, "\n", 11); + const lines = StringPrototypeSplit.$call(string, "\n", 11); if (lines.length > 10) { lines.length = 10; - return `${ArrayPrototypeJoin(lines, "\n")}\n...`; + return `${ArrayPrototypeJoin.$call(lines, "\n")}\n...`; } else if (string.length > kMaxLongStringLength) { - return `${StringPrototypeSlice(string, kMaxLongStringLength)}...`; + return `${StringPrototypeSlice.$call(string, kMaxLongStringLength)}...`; } return string; } @@ -296,7 +291,7 @@ class AssertionError extends Error { // In case the objects are equal but the operator requires unequal, show // the first object and say A equals B let base = kReadableOperator[operator]; - const res = StringPrototypeSplit(inspectValue(actual), "\n"); + const res = StringPrototypeSplit.$call(inspectValue(actual), "\n"); // In case "actual" is an object or a function, it should not be // reference equal. @@ -312,7 +307,7 @@ class AssertionError extends Error { if (res.length > 50) { res[46] = `${colors.blue}...${colors.white}`; while (res.length > 47) { - ArrayPrototypePop(res); + ArrayPrototypePop.$call(res); } } @@ -320,7 +315,7 @@ class AssertionError extends Error { if (res.length === 1) { super(`${base}${res[0].length > 5 ? "\n\n" : " "}${res[0]}`); } else { - super(`${base}\n\n${ArrayPrototypeJoin(res, "\n")}\n`); + super(`${base}\n\n${ArrayPrototypeJoin.$call(res, "\n")}\n`); } } else { let res = inspectValue(actual); @@ -329,15 +324,15 @@ class AssertionError extends Error { if (operator === "notDeepEqual" && res === other) { res = `${knownOperator}\n\n${res}`; if (res.length > 1024) { - res = `${StringPrototypeSlice(res, 0, 1021)}...`; + res = `${StringPrototypeSlice.$call(res, 0, 1021)}...`; } super(res); } else { if (res.length > kMaxLongStringLength) { - res = `${StringPrototypeSlice(res, 0, 509)}...`; + res = `${StringPrototypeSlice.$call(res, 0, 509)}...`; } if (other.length > kMaxLongStringLength) { - other = `${StringPrototypeSlice(other, 0, 509)}...`; + other = `${StringPrototypeSlice.$call(other, 0, 509)}...`; } if (operator === "deepEqual") { res = `${knownOperator}\n\n${res}\n\nshould loosely deep-equal\n\n`; diff --git a/src/js/internal/assert/calltracker.ts b/src/js/internal/assert/calltracker.ts index 25dea7baee79f0..57221f78cde108 100644 --- a/src/js/internal/assert/calltracker.ts +++ b/src/js/internal/assert/calltracker.ts @@ -1,20 +1,15 @@ "use strict"; -const { - ArrayPrototypePush, - ArrayPrototypeSlice, - Error, - FunctionPrototype, - ObjectFreeze, - Proxy, - SafeSet, - SafeWeakMap, -} = require("internal/primordials"); +const { SafeSet, SafeWeakMap } = require("internal/primordials"); const AssertionError = require("internal/assert/assertion_error"); const { validateUint32 } = require("internal/validators"); -const noop = FunctionPrototype; +const ObjectFreeze = Object.freeze; +const ArrayPrototypePush = Array.prototype.push; +const ArrayPrototypeSlice = Array.prototype.slice; + +const noop = () => {}; class CallTrackerContext { #expected; @@ -29,8 +24,8 @@ class CallTrackerContext { } track(thisArg, args) { - const argsClone = ObjectFreeze(ArrayPrototypeSlice(args)); - ArrayPrototypePush(this.#calls, ObjectFreeze({ thisArg, arguments: argsClone })); + const argsClone = ObjectFreeze(ArrayPrototypeSlice.$call(args)); + ArrayPrototypePush.$call(this.#calls, ObjectFreeze({ thisArg, arguments: argsClone })); } get delta() { @@ -41,7 +36,7 @@ class CallTrackerContext { this.#calls = []; } getCalls() { - return ObjectFreeze(ArrayPrototypeSlice(this.#calls)); + return ObjectFreeze(ArrayPrototypeSlice.$call(this.#calls)); } report() { @@ -119,7 +114,7 @@ class CallTracker { for (const context of this.#callChecks) { const message = context.report(); if (message !== undefined) { - ArrayPrototypePush(errors, message); + ArrayPrototypePush.$call(errors, message); } } return errors; diff --git a/src/js/internal/assert/utils.ts b/src/js/internal/assert/utils.ts index 1f46df9a70b403..f5dfa91263c238 100644 --- a/src/js/internal/assert/utils.ts +++ b/src/js/internal/assert/utils.ts @@ -1,22 +1,6 @@ /* prettier-ignore */ 'use strict'; -// const { -// ArrayPrototypeShift, -// Error, -// ErrorCaptureStackTrace, -// FunctionPrototypeBind, -// RegExpPrototypeSymbolReplace, -// SafeMap, -// StringPrototypeCharCodeAt, -// StringPrototypeIncludes, -// StringPrototypeIndexOf, -// StringPrototypeReplace, -// StringPrototypeSlice, -// StringPrototypeSplit, -// StringPrototypeStartsWith, -// } = require("internal/primordials"); - var AssertionError; function loadAssertionError() { if (AssertionError === undefined) { diff --git a/src/js/node/assert.ts b/src/js/node/assert.ts index a5ef9adc2e085b..4c12a84626e6ac 100644 --- a/src/js/node/assert.ts +++ b/src/js/node/assert.ts @@ -1,4 +1,3 @@ -/// // Copied from Node.js (src/lib/assert.js) // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> @@ -22,37 +21,30 @@ "use strict"; -const { - ArrayFrom, - ArrayPrototypeIndexOf, - ArrayPrototypeJoin, - ArrayPrototypePush, - ArrayPrototypeSlice, - Error, - FunctionPrototypeCall, - NumberIsNaN, - ObjectAssign, - ObjectIs, - ObjectKeys, - ObjectPrototypeIsPrototypeOf, - ReflectHas, - ReflectOwnKeys, - RegExpPrototypeExec, - SafeMap, - SafeSet, - SafeWeakSet, - StringPrototypeIndexOf, - StringPrototypeSlice, - StringPrototypeSplit, - SymbolIterator, -} = require("internal/primordials"); - +const { SafeMap, SafeSet, SafeWeakSet } = require("internal/primordials"); const { Buffer } = require("node:buffer"); const { isKeyObject, isPromise, isRegExp, isMap, isSet, isDate, isWeakSet, isWeakMap } = require("node:util/types"); const { innerOk } = require("internal/assert/utils"); - const { validateFunction } = require("internal/validators"); +const ArrayFrom = Array.from; +const ArrayPrototypeIndexOf = Array.prototype.indexOf; +const ArrayPrototypeJoin = Array.prototype.join; +const ArrayPrototypePush = Array.prototype.push; +const ArrayPrototypeSlice = Array.prototype.slice; +const NumberIsNaN = Number.isNaN; +const ObjectAssign = Object.assign; +const ObjectIs = Object.is; +const ObjectKeys = Object.keys; +const ObjectPrototypeIsPrototypeOf = Object.prototype.isPrototypeOf; +const ReflectHas = Reflect.has; +const ReflectOwnKeys = Reflect.ownKeys; +const RegExpPrototypeExec = RegExp.prototype.exec; +const StringPrototypeIndexOf = String.prototype.indexOf; +const StringPrototypeSlice = String.prototype.slice; +const StringPrototypeSplit = String.prototype.split; +const SymbolIterator = Symbol.iterator; + type nodeAssert = typeof import("node:assert"); function isDeepEqual(a, b) { @@ -375,6 +367,7 @@ function isSpecial(obj) { } const typesToCallDeepStrictEqualWith = [isKeyObject, isWeakSet, isWeakMap, Buffer.isBuffer]; +const SafeSetPrototypeIterator = SafeSet.prototype[SymbolIterator]; /** * Compares two objects or values recursively to check if they are equal. @@ -403,8 +396,8 @@ function compareBranch(actual, expected, comparedObjects) { return false; // `expected` can't be a subset if it has more elements } - const actualArray = ArrayFrom(FunctionPrototypeCall(SafeSet.prototype[SymbolIterator], actual)); - const expectedIterator = FunctionPrototypeCall(SafeSet.prototype[SymbolIterator], expected); + const actualArray = ArrayFrom(SafeSetPrototypeIterator.$call(actual)); + const expectedIterator = SafeSetPrototypeIterator.$call(expected); const usedIndices = new SafeSet(); expectedIteration: for (const expectedItem of expectedIterator) { @@ -523,7 +516,7 @@ class Comparison { actual !== undefined && typeof actual[key] === "string" && isRegExp(obj[key]) && - RegExpPrototypeExec(obj[key], actual[key]) !== null + RegExpPrototypeExec.$call(obj[key], actual[key]) !== null ) { this[key] = actual[key]; } else { @@ -571,7 +564,7 @@ function expectedException(actual, expected, message, fn) { // Handle regular expressions. if (isRegExp(expected)) { const str = String(actual); - if (RegExpPrototypeExec(expected, str) !== null) return; + if (RegExpPrototypeExec.$call(expected, str) !== null) return; const inspect = lazyInspect(); if (!message) { @@ -598,7 +591,7 @@ function expectedException(actual, expected, message, fn) { // Special handle errors to make sure the name and the message are // compared as well. if (expected instanceof Error) { - ArrayPrototypePush(keys, "name", "message"); + ArrayPrototypePush.$call(keys, "name", "message"); } else if (keys.length === 0) { throw $ERR_INVALID_ARG_VALUE("error", expected, "may not be an empty object"); } @@ -606,7 +599,7 @@ function expectedException(actual, expected, message, fn) { if ( typeof actual[key] === "string" && isRegExp(expected[key]) && - RegExpPrototypeExec(expected[key], actual[key]) !== null + RegExpPrototypeExec.$call(expected[key], actual[key]) !== null ) { continue; } @@ -618,7 +611,7 @@ function expectedException(actual, expected, message, fn) { // Check for matching Error classes. } else if (expected.prototype !== undefined && actual instanceof expected) { return; - } else if (ObjectPrototypeIsPrototypeOf(Error, expected)) { + } else if (ObjectPrototypeIsPrototypeOf.$call(Error, expected)) { if (!message) { generatedMessage = true; message = "The error is expected to be an instance of " + `"${expected.name}". Received `; @@ -762,7 +755,7 @@ function hasMatchingError(actual, expected) { if (typeof expected !== "function") { if (isRegExp(expected)) { const str = String(actual); - return RegExpPrototypeExec(expected, str) !== null; + return RegExpPrototypeExec.$call(expected, str) !== null; } throw $ERR_INVALID_ARG_TYPE("expected", ["Function", "RegExp"], expected); } @@ -770,7 +763,7 @@ function hasMatchingError(actual, expected) { if (expected.prototype !== undefined && actual instanceof expected) { return true; } - if (ObjectPrototypeIsPrototypeOf(Error, expected)) { + if (ObjectPrototypeIsPrototypeOf.$call(Error, expected)) { return false; } return expected.$apply({}, [actual]) === true; @@ -879,22 +872,25 @@ assert.ifError = function ifError(err: unknown): void { // This will remove any duplicated frames from the error frames taken // from within `ifError` and add the original error frames to the newly // created ones. - const origStackStart = StringPrototypeIndexOf(origStack, "\n at"); + const origStackStart = StringPrototypeIndexOf.$call(origStack, "\n at"); if (origStackStart !== -1) { - const originalFrames = StringPrototypeSplit(StringPrototypeSlice(origStack, origStackStart + 1), "\n"); + const originalFrames = StringPrototypeSplit.$call( + StringPrototypeSlice.$call(origStack, origStackStart + 1), + "\n", + ); // Filter all frames existing in err.stack. - let newFrames = StringPrototypeSplit(newErr.stack, "\n"); + let newFrames = StringPrototypeSplit.$call(newErr.stack, "\n"); for (const errFrame of originalFrames) { // Find the first occurrence of the frame. - const pos = ArrayPrototypeIndexOf(newFrames, errFrame); + const pos = ArrayPrototypeIndexOf.$call(newFrames, errFrame); if (pos !== -1) { // Only keep new frames. - newFrames = ArrayPrototypeSlice(newFrames, 0, pos); + newFrames = ArrayPrototypeSlice.$call(newFrames, 0, pos); break; } } - const stackStart = ArrayPrototypeJoin(newFrames, "\n"); - const stackEnd = ArrayPrototypeJoin(originalFrames, "\n"); + const stackStart = ArrayPrototypeJoin.$call(newFrames, "\n"); + const stackEnd = ArrayPrototypeJoin.$call(originalFrames, "\n"); newErr.stack = `${stackStart}\n${stackEnd}`; } } @@ -908,7 +904,7 @@ function internalMatch(string, regexp, message, fn) { throw $ERR_INVALID_ARG_TYPE("regexp", "RegExp", regexp); } const match = fn === assert.match; - if (typeof string !== "string" || (RegExpPrototypeExec(regexp, string) !== null) !== match) { + if (typeof string !== "string" || (RegExpPrototypeExec.$call(regexp, string) !== null) !== match) { if (message instanceof Error) { throw message; }