All files / lib/internal util.js

99.63% Statements 534/536
98.53% Branches 201/204
100% Functions 30/30
99.63% Lines 534/536

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 53728x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 1291x 1291x 1291x 1291x 1291x 1291x 1291x 17x 1291x 28x 28x 28x 1x 1x 1x 1x 28x 231747x 231747x 231747x 28x 84043x 84043x 84043x 84043x 84043x 84043x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 97293x 97293x 47x 47x 97246x 97246x 97246x 97247x 97246x 97246x 97246x 97241x 97241x 97241x 259x 108x 108x 100x 71x 71x 71x 108x 8x 8x 108x 259x 2x 2x 257x 259x 97241x 97241x 97241x 97246x 89600x 89600x 89600x 89600x 89600x 97241x 97241x 97293x 28x 104x 104x 104x 104x 72x 72x 72x 103x 12x 12x 12x 104x 28x 5608x 5608x 5608x 5608x 28x 28x 28x 28x 84310x 84310x 40541x 84310x 28x 40541x 40541x 40541x 634x 634x 24x 633x 536x 22x 40541x 1775x 1775x 1775x 8x 40541x 440x 29x 18x 15x 15x 9x 9x 15x 8x 5x 40541x 37267x 37267x 37212x 37267x 1218x 2437x 37267x 1216x 40541x 179x 179x 179x 4x 40541x 17x 17x 17x 3x 40541x 192x 192x 192x 3x 40541x 37x 40541x 40541x 28x 303x 303x 159x 159x 159x 159x 303x 28x 15x 15x 15x 1377x 1377x 1377x 65x 1377x 1312x 1312x 1377x 15x 15x 28x 13289x 13289x 13289x 37x 37x 37x 13289x 13289x 28x 28x 28x 28x 28x 28x 28x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 62x 62x 62x 12x 12x 62x 408x 408x 12x 12x 62x 28x 1032x 1032x 1032x 974x 1008x 970x 970x 970x 19x 19x 1032x 28x 9x 9x 18x 18x 18x 18x 9x 9x 9x 9x 9x     9x 28x 4212x 4212x 4212x 4212x 28x 1x 1x 1x 28x 28x 28x 28x 28x 28x 16334x 16334x 16334x 16334x 16334x 16334x 16334x 16334x 60x 60x 60x 60x 60x 60x 60x 60x 16266x 16266x 16266x 16266x 16266x 16266x 142x 142x 141x 30x 30x 141x 18x 18x 18x 18x 140x 93x 93x 142x 142x 142x 142x 16266x 16266x 16266x 16266x 16266x 16266x 16266x 16266x 16266x 16266x 16334x 28x 28x 28x 28x 170536x 170536x 170536x 170450x 170450x 726194x 726194x 726194x 726194x 170450x 170450x 170536x 170536x 28x 28x 28x 36365x 36365x 36365x 36365x 36365x 28x 28x 28x 28x 28x 36x 36x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 36x 36x 36x 36x 36x 36x 35x 219x 219x 219x 219x 219x 29x 29x 6x 7x 36x 28x 3301x 3301x 3301x 5868x 3266x 3266x 3301x 3301x 28x 28x 28x 20x 20x 20x 20x 20x 20x 20x 20x 28x 5562x 5562x 5562x 5562x 5562x 5562x 5562x 5562x 5562x 5562x 28x 28x 28x 11x 11x 28x 28x 28x 7370x 7370x 28x 28x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x  
'use strict';
 
const {
  ArrayFrom,
  ArrayIsArray,
  ArrayPrototypePush,
  ArrayPrototypeSlice,
  ArrayPrototypeSort,
  Error,
  ObjectCreate,
  ObjectDefineProperties,
  ObjectDefineProperty,
  ObjectGetOwnPropertyDescriptor,
  ObjectGetOwnPropertyDescriptors,
  ObjectGetPrototypeOf,
  ObjectSetPrototypeOf,
  Promise,
  ReflectApply,
  ReflectConstruct,
  RegExpPrototypeExec,
  RegExpPrototypeTest,
  SafeMap,
  SafeSet,
  StringPrototypeReplace,
  StringPrototypeToLowerCase,
  StringPrototypeToUpperCase,
  Symbol,
  SymbolFor,
} = primordials;
 
const {
  toUSVString: _toUSVString,
} = internalBinding('url');
 
const {
  hideStackFrames,
  codes: {
    ERR_NO_CRYPTO,
    ERR_UNKNOWN_SIGNAL
  },
  uvErrmapGet,
  overrideStackTrace,
} = require('internal/errors');
const { signals } = internalBinding('constants').os;
const {
  getHiddenValue,
  setHiddenValue,
  arrow_message_private_symbol: kArrowMessagePrivateSymbolIndex,
  decorated_private_symbol: kDecoratedPrivateSymbolIndex,
  sleep: _sleep
} = internalBinding('util');
const { isNativeError } = internalBinding('types');
 
const noCrypto = !process.versions.openssl;
 
const experimentalWarnings = new SafeSet();
 
const colorRegExp = /\u001b\[\d\d?m/g; // eslint-disable-line no-control-regex
 
const unpairedSurrogateRe =
  /(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/;
function toUSVString(val) {
  const str = `${val}`;
  // As of V8 5.5, `str.search()` (and `unpairedSurrogateRe[@@search]()`) are
  // slower than `unpairedSurrogateRe.exec()`.
  const match = RegExpPrototypeExec(unpairedSurrogateRe, str);
  if (!match)
    return str;
  return _toUSVString(str, match.index);
}
 
let uvBinding;
 
function lazyUv() {
  uvBinding ??= internalBinding('uv');
  return uvBinding;
}
 
function removeColors(str) {
  return StringPrototypeReplace(str, colorRegExp, '');
}
 
function isError(e) {
  // An error could be an instance of Error while not being a native error
  // or could be from a different realm and not be instance of Error but still
  // be a native error.
  return isNativeError(e) || e instanceof Error;
}
 
// Keep a list of deprecation codes that have been warned on so we only warn on
// each one once.
const codesWarned = new SafeSet();
 
let validateString;
 
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
function deprecate(fn, msg, code) {
  if (process.noDeprecation === true) {
    return fn;
  }
 
  // Lazy-load to avoid a circular dependency.
  if (validateString === undefined)
    ({ validateString } = require('internal/validators'));
 
  if (code !== undefined)
    validateString(code, 'code');
 
  let warned = false;
  function deprecated(...args) {
    if (!warned) {
      warned = true;
      if (code !== undefined) {
        if (!codesWarned.has(code)) {
          process.emitWarning(msg, 'DeprecationWarning', code, deprecated);
          codesWarned.add(code);
        }
      } else {
        process.emitWarning(msg, 'DeprecationWarning', deprecated);
      }
    }
    if (new.target) {
      return ReflectConstruct(fn, args, new.target);
    }
    return ReflectApply(fn, this, args);
  }
 
  // The wrapper will keep the same prototype as fn to maintain prototype chain
  ObjectSetPrototypeOf(deprecated, fn);
  if (fn.prototype) {
    // Setting this (rather than using Object.setPrototype, as above) ensures
    // that calling the unwrapped constructor gives an instanceof the wrapped
    // constructor.
    deprecated.prototype = fn.prototype;
  }
 
  return deprecated;
}
 
function decorateErrorStack(err) {
  if (!(isError(err) && err.stack) ||
      getHiddenValue(err, kDecoratedPrivateSymbolIndex) === true)
    return;
 
  const arrow = getHiddenValue(err, kArrowMessagePrivateSymbolIndex);
 
  if (arrow) {
    err.stack = arrow + err.stack;
    setHiddenValue(err, kDecoratedPrivateSymbolIndex, true);
  }
}
 
function assertCrypto() {
  if (noCrypto)
    throw new ERR_NO_CRYPTO();
}
 
// Return undefined if there is no match.
// Move the "slow cases" to a separate function to make sure this function gets
// inlined properly. That prioritizes the common case.
function normalizeEncoding(enc) {
  if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';
  return slowCases(enc);
}
 
function slowCases(enc) {
  switch (enc.length) {
    case 4:
      if (enc === 'UTF8') return 'utf8';
      if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';
      enc = `${enc}`.toLowerCase();
      if (enc === 'utf8') return 'utf8';
      if (enc === 'ucs2') return 'utf16le';
      break;
    case 3:
      if (enc === 'hex' || enc === 'HEX' ||
          `${enc}`.toLowerCase() === 'hex')
        return 'hex';
      break;
    case 5:
      if (enc === 'ascii') return 'ascii';
      if (enc === 'ucs-2') return 'utf16le';
      if (enc === 'UTF-8') return 'utf8';
      if (enc === 'ASCII') return 'ascii';
      if (enc === 'UCS-2') return 'utf16le';
      enc = `${enc}`.toLowerCase();
      if (enc === 'utf-8') return 'utf8';
      if (enc === 'ascii') return 'ascii';
      if (enc === 'ucs-2') return 'utf16le';
      break;
    case 6:
      if (enc === 'base64') return 'base64';
      if (enc === 'latin1' || enc === 'binary') return 'latin1';
      if (enc === 'BASE64') return 'base64';
      if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';
      enc = `${enc}`.toLowerCase();
      if (enc === 'base64') return 'base64';
      if (enc === 'latin1' || enc === 'binary') return 'latin1';
      break;
    case 7:
      if (enc === 'utf16le' || enc === 'UTF16LE' ||
          `${enc}`.toLowerCase() === 'utf16le')
        return 'utf16le';
      break;
    case 8:
      if (enc === 'utf-16le' || enc === 'UTF-16LE' ||
        `${enc}`.toLowerCase() === 'utf-16le')
        return 'utf16le';
      break;
    case 9:
      if (enc === 'base64url' || enc === 'BASE64URL' ||
          `${enc}`.toLowerCase() === 'base64url')
        return 'base64url';
      break;
    default:
      if (enc === '') return 'utf8';
  }
}
 
function emitExperimentalWarning(feature) {
  if (experimentalWarnings.has(feature)) return;
  const msg = `${feature} is an experimental feature. This feature could ` +
       'change at any time';
  experimentalWarnings.add(feature);
  process.emitWarning(msg, 'ExperimentalWarning');
}
 
function filterDuplicateStrings(items, low) {
  const map = new SafeMap();
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const key = StringPrototypeToLowerCase(item);
    if (low) {
      map.set(key, key);
    } else {
      map.set(key, item);
    }
  }
  return ArrayPrototypeSort(ArrayFrom(map.values()));
}
 
function cachedResult(fn) {
  let result;
  return () => {
    if (result === undefined)
      result = fn();
    return ArrayPrototypeSlice(result);
  };
}
 
// Useful for Wrapping an ES6 Class with a constructor Function that
// does not require the new keyword. For instance:
//   class A { constructor(x) {this.x = x;}}
//   const B = createClassWrapper(A);
//   B() instanceof A // true
//   B() instanceof B // true
function createClassWrapper(type) {
  function fn(...args) {
    return ReflectConstruct(type, args, new.target || type);
  }
  // Mask the wrapper function name and length values
  ObjectDefineProperties(fn, {
    name: { value: type.name },
    length: { value: type.length }
  });
  ObjectSetPrototypeOf(fn, type);
  fn.prototype = type.prototype;
  return fn;
}
 
let signalsToNamesMapping;
function getSignalsToNamesMapping() {
  if (signalsToNamesMapping !== undefined)
    return signalsToNamesMapping;
 
  signalsToNamesMapping = ObjectCreate(null);
  for (const key in signals) {
    signalsToNamesMapping[signals[key]] = key;
  }
 
  return signalsToNamesMapping;
}
 
function convertToValidSignal(signal) {
  if (typeof signal === 'number' && getSignalsToNamesMapping()[signal])
    return signal;
 
  if (typeof signal === 'string') {
    const signalName = signals[StringPrototypeToUpperCase(signal)];
    if (signalName) return signalName;
  }
 
  throw new ERR_UNKNOWN_SIGNAL(signal);
}
 
function getConstructorOf(obj) {
  while (obj) {
    const descriptor = ObjectGetOwnPropertyDescriptor(obj, 'constructor');
    if (descriptor !== undefined &&
        typeof descriptor.value === 'function' &&
        descriptor.value.name !== '') {
      return descriptor.value;
    }
 
    obj = ObjectGetPrototypeOf(obj);
  }

  return null;
}
 
function getSystemErrorName(err) {
  const entry = uvErrmapGet(err);
  return entry ? entry[0] : `Unknown system error ${err}`;
}
 
function getSystemErrorMap() {
  return lazyUv().getErrorMap();
}
 
const kCustomPromisifiedSymbol = SymbolFor('nodejs.util.promisify.custom');
const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');
 
let validateFunction;
 
function promisify(original) {
  // Lazy-load to avoid a circular dependency.
  if (validateFunction === undefined)
    ({ validateFunction } = require('internal/validators'));
 
  validateFunction(original, 'original');
 
  if (original[kCustomPromisifiedSymbol]) {
    const fn = original[kCustomPromisifiedSymbol];
 
    validateFunction(fn, 'util.promisify.custom');
 
    return ObjectDefineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn, enumerable: false, writable: false, configurable: true
    });
  }
 
  // Names to create an object from in case the callback receives multiple
  // arguments, e.g. ['bytesRead', 'buffer'] for fs.read.
  const argumentNames = original[kCustomPromisifyArgsSymbol];
 
  function fn(...args) {
    return new Promise((resolve, reject) => {
      ArrayPrototypePush(args, (err, ...values) => {
        if (err) {
          return reject(err);
        }
        if (argumentNames !== undefined && values.length > 1) {
          const obj = {};
          for (let i = 0; i < argumentNames.length; i++)
            obj[argumentNames[i]] = values[i];
          resolve(obj);
        } else {
          resolve(values[0]);
        }
      });
      ReflectApply(original, this, args);
    });
  }
 
  ObjectSetPrototypeOf(fn, ObjectGetPrototypeOf(original));
 
  ObjectDefineProperty(fn, kCustomPromisifiedSymbol, {
    value: fn, enumerable: false, writable: false, configurable: true
  });
  return ObjectDefineProperties(
    fn,
    ObjectGetOwnPropertyDescriptors(original)
  );
}
 
promisify.custom = kCustomPromisifiedSymbol;
 
// The built-in Array#join is slower in v8 6.0
function join(output, separator) {
  let str = '';
  if (output.length !== 0) {
    const lastIndex = output.length - 1;
    for (let i = 0; i < lastIndex; i++) {
      // It is faster not to use a template string here
      str += output[i];
      str += separator;
    }
    str += output[lastIndex];
  }
  return str;
}
 
// As of V8 6.6, depending on the size of the array, this is anywhere
// between 1.5-10x faster than the two-arg version of Array#splice()
function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}
 
const kNodeModulesRE = /^(.*)[\\/]node_modules[\\/]/;
 
let getStructuredStack;
 
function isInsideNodeModules() {
  if (getStructuredStack === undefined) {
    // Lazy-load to avoid a circular dependency.
    const { runInNewContext } = require('vm');
    // Use `runInNewContext()` to get something tamper-proof and
    // side-effect-free. Since this is currently only used for a deprecated API,
    // the perf implications should be okay.
    getStructuredStack = runInNewContext(`(function() {
      try { Error.stackTraceLimit = Infinity; } catch {}
      return function structuredStack() {
        const e = new Error();
        overrideStackTrace.set(e, (err, trace) => trace);
        return e.stack;
      };
    })()`, { overrideStackTrace }, { filename: 'structured-stack' });
  }
 
  const stack = getStructuredStack();
 
  // Iterate over all stack frames and look for the first one not coming
  // from inside Node.js itself:
  if (ArrayIsArray(stack)) {
    for (const frame of stack) {
      const filename = frame.getFileName();
      // If a filename does not start with / or contain \,
      // it's likely from Node.js core.
      if (!RegExpPrototypeTest(/^\/|\\/, filename))
        continue;
      return RegExpPrototypeTest(kNodeModulesRE, filename);
    }
  }
  return false;
}
 
function once(callback) {
  let called = false;
  return function(...args) {
    if (called) return;
    called = true;
    ReflectApply(callback, this, args);
  };
}
 
let validateUint32;
 
function sleep(msec) {
  // Lazy-load to avoid a circular dependency.
  if (validateUint32 === undefined)
    ({ validateUint32 } = require('internal/validators'));
 
  validateUint32(msec, 'msec');
  _sleep(msec);
}
 
function createDeferredPromise() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
 
  return { promise, resolve, reject };
}
 
let _DOMException;
const lazyDOMExceptionClass = () => {
  _DOMException ??= internalBinding('messaging').DOMException;
  return _DOMException;
};
 
const lazyDOMException = hideStackFrames((message, name) => {
  _DOMException ??= internalBinding('messaging').DOMException;
  return new _DOMException(message, name);
});
 
function structuredClone(value) {
  const {
    DefaultSerializer,
    DefaultDeserializer,
  } = require('v8');
  const ser = new DefaultSerializer();
  ser._getDataCloneError = hideStackFrames((message) =>
    lazyDOMException(message, 'DataCloneError'));
  ser.writeValue(value);
  const serialized = ser.releaseBuffer();
 
  const des = new DefaultDeserializer(serialized);
  return des.readValue();
}
 
module.exports = {
  assertCrypto,
  cachedResult,
  convertToValidSignal,
  createClassWrapper,
  createDeferredPromise,
  decorateErrorStack,
  deprecate,
  emitExperimentalWarning,
  filterDuplicateStrings,
  getConstructorOf,
  getSystemErrorMap,
  getSystemErrorName,
  isError,
  isInsideNodeModules,
  join,
  lazyDOMException,
  lazyDOMExceptionClass,
  normalizeEncoding,
  once,
  promisify,
  sleep,
  spliceOne,
  structuredClone,
  toUSVString,
  removeColors,
 
  // Symbol used to customize promisify conversion
  customPromisifyArgs: kCustomPromisifyArgsSymbol,
 
  // Symbol used to provide a custom inspect function for an object as an
  // alternative to using 'inspect'
  customInspectSymbol: SymbolFor('nodejs.util.inspect.custom'),
 
  // Used by the buffer module to capture an internal reference to the
  // default isEncoding implementation, just in case userland overrides it.
  kIsEncodingSymbol: Symbol('kIsEncodingSymbol'),
  kVmBreakFirstLineSymbol: Symbol('kVmBreakFirstLineSymbol')
};