UNPKG

nstdlib-nightly

Version:

Node.js standard library converted to runtime-agnostic ES modules.

585 lines (542 loc) 17 kB
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/util.js import * as __hoisted_internal_abort_controller__ from "nstdlib/lib/internal/abort_controller"; import * as __hoisted_internal_console_global__ from "nstdlib/lib/internal/console/global"; import * as __hoisted_internal_util_comparisons__ from "nstdlib/lib/internal/util/comparisons"; import { ErrnoException, ExceptionWithHostPort, codes as __codes__, isErrorStackTraceLimitWritable, } from "nstdlib/lib/internal/errors"; import { format, formatWithOptions, inspect, stripVTControlCharacters, } from "nstdlib/lib/internal/util/inspect"; import { debuglog } from "nstdlib/lib/internal/util/debuglog"; import { validateFunction, validateNumber, validateString, validateOneOf, } from "nstdlib/lib/internal/validators"; import { Buffer as __Buffer__ } from "nstdlib/lib/buffer"; import * as types from "nstdlib/lib/internal/util/types"; import * as binding from "nstdlib/stub/binding/util"; import { deprecate, getSystemErrorMap, getSystemErrorName as internalErrorName, promisify, defineLazyProperties, } from "nstdlib/lib/internal/util"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. const { ERR_FALSY_VALUE_REJECTION, ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE } = __codes__; const { isBuffer } = __Buffer__; let abortController; function lazyAbortController() { abortController ??= __hoisted_internal_abort_controller__; return abortController; } let internalDeepEqual; /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is boolean} */ function isBoolean(arg) { return typeof arg === "boolean"; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is null} */ function isNull(arg) { return arg === null; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is (null | undefined)} */ function isNullOrUndefined(arg) { return arg === null || arg === undefined; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is number} */ function isNumber(arg) { return typeof arg === "number"; } /** * @param {any} arg * @returns {arg is string} */ function isString(arg) { return typeof arg === "string"; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is symbol} */ function isSymbol(arg) { return typeof arg === "symbol"; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is undefined} */ function isUndefined(arg) { return arg === undefined; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {a is NonNullable<object>} */ function isObject(arg) { return arg !== null && typeof arg === "object"; } /** * @deprecated since v4.0.0 * @param {any} e * @returns {arg is Error} */ function isError(e) { return ( Object.prototype.toString.call(e) === "[object Error]" || e instanceof Error ); } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is Function} */ function isFunction(arg) { return typeof arg === "function"; } /** * @deprecated since v4.0.0 * @param {any} arg * @returns {arg is (boolean | null | number | string | symbol | undefined)} */ function isPrimitive(arg) { return arg === null || (typeof arg !== "object" && typeof arg !== "function"); } /** * @param {number} n * @returns {string} */ function pad(n) { return String.prototype.padStart.call(n.toString(), 2, "0"); } /** * @param {string} code * @returns {string} */ function escapeStyleCode(code) { return `\u001b[${code}m`; } /** * @param {string | string[]} format * @param {string} text * @returns {string} */ function styleText(format, text) { validateString(text, "text"); if (Array.isArray(format)) { let left = ""; let right = ""; for (const key of format) { const formatCodes = inspect.colors[key]; if (formatCodes == null) { validateOneOf(key, "format", Object.keys(inspect.colors)); } left += ((...args) => globalThis.escapeStyleCode(...args))( formatCodes[0], ); right = `${((...args) => globalThis.escapeStyleCode(...args))(formatCodes[1])}${right}`; } return `${left}${text}${right}`; } const formatCodes = inspect.colors[format]; if (formatCodes == null) { validateOneOf(format, "format", Object.keys(inspect.colors)); } return `${((...args) => globalThis.escapeStyleCode(...args))(formatCodes[0])}${text}${((...args) => globalThis.escapeStyleCode(...args))(formatCodes[1])}`; } const months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; /** * @returns {string} 26 Feb 16:19:34 */ function timestamp() { const d = new Date(); const t = Array.prototype.join.call( [ pad(Date.prototype.getHours.call(d)), pad(Date.prototype.getMinutes.call(d)), pad(Date.prototype.getSeconds.call(d)), ], ":", ); return `${Date.prototype.getDate.call(d)} ${months[Date.prototype.getMonth.call(d)]} ${t}`; } let console; /** * Log is just a thin wrapper to console.log that prepends a timestamp * @deprecated since v6.0.0 * @type {(...args: any[]) => void} */ function log(...args) { if (!console) { console = __hoisted_internal_console_global__; } console.log("%s - %s", timestamp(), format(...args)); } /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * @param {Function} ctor Constructor function which needs to inherit the * prototype. * @param {Function} superCtor Constructor function to inherit prototype from. * @throws {TypeError} Will error if either constructor is null, or if * the super constructor lacks a prototype. */ function inherits(ctor, superCtor) { if (ctor === undefined || ctor === null) throw new ERR_INVALID_ARG_TYPE("ctor", "Function", ctor); if (superCtor === undefined || superCtor === null) throw new ERR_INVALID_ARG_TYPE("superCtor", "Function", superCtor); if (superCtor.prototype === undefined) { throw new ERR_INVALID_ARG_TYPE( "superCtor.prototype", "Object", superCtor.prototype, ); } Object.defineProperty(ctor, "super_", { __proto__: null, value: superCtor, writable: true, configurable: true, }); Object.setPrototypeOf(ctor.prototype, superCtor.prototype); } /** * @deprecated since v6.0.0 * @template T * @template S * @param {T} target * @param {S} source * @returns {S extends null ? T : (T & S)} */ function _extend(target, source) { // Don't do anything if source isn't an object if (source === null || typeof source !== "object") return target; const keys = Object.keys(source); let i = keys.length; while (i--) { target[keys[i]] = source[keys[i]]; } return target; } const callbackifyOnRejected = (reason, cb) => { // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). // Because `null` is a special error value in callbacks which means "no error // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { reason = new ERR_FALSY_VALUE_REJECTION.HideStackFramesError(reason); Error.captureStackTrace(reason, callbackifyOnRejected); } return cb(reason); }; /** * @template {(...args: any[]) => Promise<any>} T * @param {T} original * @returns {T extends (...args: infer TArgs) => Promise<infer TReturn> ? * ((...params: [...TArgs, ((err: Error, ret: TReturn) => any)]) => void) : * never * } */ function callbackify(original) { validateFunction(original, "original"); // We DO NOT return the promise as it gives the user a false sense that // the promise is actually somehow related to the callback's execution // and that the callback throwing will reject the promise. function callbackified(...args) { const maybeCb = Array.prototype.pop.call(args); validateFunction(maybeCb, "last argument"); const cb = Function.prototype.bind.call(maybeCb, this); // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) ReflectApply(original, this, args).then( (ret) => process.nextTick(cb, null, ret), (rej) => process.nextTick(callbackifyOnRejected, rej, cb), ); } const descriptors = Object.getOwnPropertyDescriptors(original); // It is possible to manipulate a functions `length` or `name` property. This // guards against the manipulation. if (typeof descriptors.length.value === "number") { descriptors.length.value++; } if (typeof descriptors.name.value === "string") { descriptors.name.value += "Callbackified"; } const propertiesValues = Object.values(descriptors); for (let i = 0; i < propertiesValues.length; i++) { // We want to use null-prototype objects to not rely on globally mutable // %Object.prototype%. Object.setPrototypeOf(propertiesValues[i], null); } Object.defineProperties(callbackified, descriptors); return callbackified; } /** * @param {number} err * @returns {string} */ function getSystemErrorName(err) { validateNumber(err, "err"); if (err >= 0 || !Number.isSafeInteger(err)) { throw new ERR_OUT_OF_RANGE("err", "a negative integer", err); } return internalErrorName(err); } function _errnoException(...args) { if (isErrorStackTraceLimitWritable()) { const limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; const e = new ErrnoException(...args); Error.stackTraceLimit = limit; Error.captureStackTrace(e, _exceptionWithHostPort); return e; } return new ErrnoException(...args); } function _exceptionWithHostPort(...args) { if (isErrorStackTraceLimitWritable()) { const limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; const e = new ExceptionWithHostPort(...args); Error.stackTraceLimit = limit; Error.captureStackTrace(e, _exceptionWithHostPort); return e; } return new ExceptionWithHostPort(...args); } /** * Parses the content of a `.env` file. * @param {string} content * @returns {Record<string, string>} */ function parseEnv(content) { validateString(content, "content"); return binding.parseEnv(content); } // Keep the `exports =` so that various functions can still be monkeypatched export { _errnoException }; export { _exceptionWithHostPort }; const _export__extend_ = deprecate( _extend, "The `util._extend` API is deprecated. Please use Object.assign() instead.", "DEP0060", ); export { _export__extend_ as _extend }; export { callbackify }; export { debuglog as debug }; export { debuglog }; export { deprecate }; export { format }; export { styleText }; export { formatWithOptions }; export { getSystemErrorMap }; export { getSystemErrorName }; export { inherits }; export { inspect }; const _export_isArray_ = deprecate( ArrayIsArray, "The `util.isArray` API is deprecated. Please use `Array.isArray()` instead.", "DEP0044", ); export { _export_isArray_ as isArray }; const _export_isBoolean_ = deprecate( isBoolean, 'The `util.isBoolean` API is deprecated. Please use `typeof arg === "boolean"` instead.', "DEP0045", ); export { _export_isBoolean_ as isBoolean }; const _export_isBuffer_ = deprecate( isBuffer, "The `util.isBuffer` API is deprecated. Please use `Buffer.isBuffer()` instead.", "DEP0046", ); export { _export_isBuffer_ as isBuffer }; const _export_isDeepStrictEqual_ = function (a, b) { if (internalDeepEqual === undefined) { internalDeepEqual = __hoisted_internal_util_comparisons__.isDeepStrictEqual; } return internalDeepEqual(a, b); }; export { _export_isDeepStrictEqual_ as isDeepStrictEqual }; const _export_isNull_ = deprecate( isNull, "The `util.isNull` API is deprecated. Please use `arg === null` instead.", "DEP0050", ); export { _export_isNull_ as isNull }; const _export_isNullOrUndefined_ = deprecate( isNullOrUndefined, "The `util.isNullOrUndefined` API is deprecated. " + "Please use `arg === null || arg === undefined` instead.", "DEP0051", ); export { _export_isNullOrUndefined_ as isNullOrUndefined }; const _export_isNumber_ = deprecate( isNumber, 'The `util.isNumber` API is deprecated. Please use `typeof arg === "number"` instead.', "DEP0052", ); export { _export_isNumber_ as isNumber }; const _export_isString_ = deprecate( isString, 'The `util.isString` API is deprecated. Please use `typeof arg === "string"` instead.', "DEP0056", ); export { _export_isString_ as isString }; const _export_isSymbol_ = deprecate( isSymbol, 'The `util.isSymbol` API is deprecated. Please use `arg === "symbol"` instead.', "DEP0057", ); export { _export_isSymbol_ as isSymbol }; const _export_isUndefined_ = deprecate( isUndefined, "The `util.isUndefined` API is deprecated. Please use `arg === undefined` instead.", "DEP0058", ); export { _export_isUndefined_ as isUndefined }; const _export_isRegExp_ = deprecate( types.isRegExp, "The `util.isRegExp` API is deprecated. Please use `arg instanceof RegExp` instead.", "DEP0055", ); export { _export_isRegExp_ as isRegExp }; const _export_isObject_ = deprecate( isObject, "The `util.isObject` API is deprecated. " + 'Please use `arg !== null && typeof arg === "object"` instead.', "DEP0053", ); export { _export_isObject_ as isObject }; const _export_isDate_ = deprecate( types.isDate, "The `util.isDate` API is deprecated. Please use `arg instanceof Date` instead.", "DEP0047", ); export { _export_isDate_ as isDate }; const _export_isError_ = deprecate( isError, "The `util.isError` API is deprecated. " + 'Please use `ObjectPrototypeToString(e) === "[object Error]" ' + "|| e instanceof Error` instead.", "DEP0048", ); export { _export_isError_ as isError }; const _export_isFunction_ = deprecate( isFunction, 'The `util.isFunction` API is deprecated. Please use `typeof arg === "function"` instead.', "DEP0049", ); export { _export_isFunction_ as isFunction }; const _export_isPrimitive_ = deprecate( isPrimitive, "The `util.isPrimitive` API is deprecated. " + "Please use `arg === null || " + '(typeof arg !== "object" && typeof arg !== "function")` instead.', "DEP0054", ); export { _export_isPrimitive_ as isPrimitive }; const _export_log_ = deprecate( log, "The `util.log API is deprecated. " + "Please use console.log() with a custom formatter or a third-party logger instead.", "DEP0059", ); export { _export_log_ as log }; export { promisify }; export { stripVTControlCharacters }; const _export_toUSVString_ = function (input) { return String.prototype.toWellFormed.call(`${input}`); }; export { _export_toUSVString_ as toUSVString }; const _export_transferableAbortSignal_ = () => { return lazyAbortController().transferableAbortSignal; }; export { _export_transferableAbortSignal_ as transferableAbortSignal }; const _export_transferableAbortController_ = () => { return lazyAbortController().transferableAbortController; }; export { _export_transferableAbortController_ as transferableAbortController }; const _export_aborted_ = () => { return lazyAbortController().aborted; }; export { _export_aborted_ as aborted }; export { types }; export { parseEnv }; defineLazyProperties(module.exports, "internal/util/parse_args/parse_args", [ "parseArgs", ]); defineLazyProperties(module.exports, "internal/encoding", [ "TextDecoder", "TextEncoder", ]); defineLazyProperties(module.exports, "internal/mime", [ "MIMEType", "MIMEParams", ]);