• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* eslint node-core/documented-errors: "error" */
2/* eslint node-core/alphabetize-errors: "error" */
3/* eslint node-core/prefer-util-format-errors: "error" */
4
5'use strict';
6
7// The whole point behind this internal module is to allow Node.js to no
8// longer be forced to treat every error message change as a semver-major
9// change. The NodeError classes here all expose a `code` property whose
10// value statically and permanently identifies the error. While the error
11// message may change, the code should not.
12
13const {
14  AggregateError,
15  ArrayFrom,
16  ArrayIsArray,
17  ArrayPrototypeFilter,
18  ArrayPrototypeIncludes,
19  ArrayPrototypeIndexOf,
20  ArrayPrototypeJoin,
21  ArrayPrototypeMap,
22  ArrayPrototypePush,
23  ArrayPrototypeSlice,
24  ArrayPrototypeSplice,
25  ArrayPrototypeUnshift,
26  Error,
27  ErrorCaptureStackTrace,
28  ErrorPrototypeToString,
29  JSONStringify,
30  MapPrototypeGet,
31  MathAbs,
32  MathMax,
33  Number,
34  NumberIsInteger,
35  ObjectAssign,
36  ObjectDefineProperty,
37  ObjectDefineProperties,
38  ObjectIsExtensible,
39  ObjectGetOwnPropertyDescriptor,
40  ObjectKeys,
41  ObjectPrototypeHasOwnProperty,
42  RangeError,
43  ReflectApply,
44  RegExpPrototypeExec,
45  SafeArrayIterator,
46  SafeMap,
47  SafeWeakMap,
48  String,
49  StringPrototypeEndsWith,
50  StringPrototypeIncludes,
51  StringPrototypeSlice,
52  StringPrototypeSplit,
53  StringPrototypeStartsWith,
54  StringPrototypeToLowerCase,
55  Symbol,
56  SymbolFor,
57  SyntaxError,
58  TypeError,
59  URIError,
60} = primordials;
61
62const kIsNodeError = Symbol('kIsNodeError');
63
64const isWindows = process.platform === 'win32';
65
66const messages = new SafeMap();
67const codes = {};
68
69const classRegExp = /^([A-Z][a-z0-9]*)+$/;
70// Sorted by a rough estimate on most frequently used entries.
71const kTypes = [
72  'string',
73  'function',
74  'number',
75  'object',
76  // Accept 'Function' and 'Object' as alternative to the lower cased version.
77  'Function',
78  'Object',
79  'boolean',
80  'bigint',
81  'symbol',
82];
83
84const MainContextError = Error;
85const overrideStackTrace = new SafeWeakMap();
86const kNoOverride = Symbol('kNoOverride');
87let userStackTraceLimit;
88const nodeInternalPrefix = '__node_internal_';
89const prepareStackTrace = (globalThis, error, trace) => {
90  // API for node internals to override error stack formatting
91  // without interfering with userland code.
92  if (overrideStackTrace.has(error)) {
93    const f = overrideStackTrace.get(error);
94    overrideStackTrace.delete(error);
95    return f(error, trace);
96  }
97
98  const firstFrame = trace[0]?.getFunctionName();
99  if (firstFrame && StringPrototypeStartsWith(firstFrame, nodeInternalPrefix)) {
100    for (let l = trace.length - 1; l >= 0; l--) {
101      const fn = trace[l]?.getFunctionName();
102      if (fn && StringPrototypeStartsWith(fn, nodeInternalPrefix)) {
103        ArrayPrototypeSplice(trace, 0, l + 1);
104        break;
105      }
106    }
107    // `userStackTraceLimit` is the user value for `Error.stackTraceLimit`,
108    // it is updated at every new exception in `captureLargerStackTrace`.
109    if (trace.length > userStackTraceLimit)
110      ArrayPrototypeSplice(trace, userStackTraceLimit);
111  }
112
113  const globalOverride =
114    maybeOverridePrepareStackTrace(globalThis, error, trace);
115  if (globalOverride !== kNoOverride) return globalOverride;
116
117  // Normal error formatting:
118  //
119  // Error: Message
120  //     at function (file)
121  //     at file
122  let errorString;
123  if (kIsNodeError in error) {
124    errorString = `${error.name} [${error.code}]: ${error.message}`;
125  } else {
126    errorString = ErrorPrototypeToString(error);
127  }
128  if (trace.length === 0) {
129    return errorString;
130  }
131  return `${errorString}\n    at ${ArrayPrototypeJoin(trace, '\n    at ')}`;
132};
133
134const maybeOverridePrepareStackTrace = (globalThis, error, trace) => {
135  // Polyfill of V8's Error.prepareStackTrace API.
136  // https://crbug.com/v8/7848
137  // `globalThis` is the global that contains the constructor which
138  // created `error`.
139  if (typeof globalThis.Error?.prepareStackTrace === 'function') {
140    return globalThis.Error.prepareStackTrace(error, trace);
141  }
142  // We still have legacy usage that depends on the main context's `Error`
143  // being used, even when the error is from a different context.
144  // TODO(devsnek): evaluate if this can be eventually deprecated/removed.
145  if (typeof MainContextError.prepareStackTrace === 'function') {
146    return MainContextError.prepareStackTrace(error, trace);
147  }
148
149  return kNoOverride;
150};
151
152const aggregateTwoErrors = hideStackFrames((innerError, outerError) => {
153  if (innerError && outerError && innerError !== outerError) {
154    if (ArrayIsArray(outerError.errors)) {
155      // If `outerError` is already an `AggregateError`.
156      ArrayPrototypePush(outerError.errors, innerError);
157      return outerError;
158    }
159    // eslint-disable-next-line no-restricted-syntax
160    const err = new AggregateError(new SafeArrayIterator([
161      outerError,
162      innerError,
163    ]), outerError.message);
164    err.code = outerError.code;
165    return err;
166  }
167  return innerError || outerError;
168});
169
170const aggregateErrors = hideStackFrames((errors, message, code) => {
171  // eslint-disable-next-line no-restricted-syntax
172  const err = new AggregateError(new SafeArrayIterator(errors), message);
173  err.code = errors[0]?.code;
174  return err;
175});
176
177// Lazily loaded
178let util;
179let assert;
180
181let internalUtil = null;
182function lazyInternalUtil() {
183  internalUtil ??= require('internal/util');
184  return internalUtil;
185}
186
187let internalUtilInspect = null;
188function lazyInternalUtilInspect() {
189  internalUtilInspect ??= require('internal/util/inspect');
190  return internalUtilInspect;
191}
192
193let utilColors;
194function lazyUtilColors() {
195  utilColors ??= require('internal/util/colors');
196  return utilColors;
197}
198
199let buffer;
200function lazyBuffer() {
201  buffer ??= require('buffer').Buffer;
202  return buffer;
203}
204
205function isErrorStackTraceLimitWritable() {
206  // Do no touch Error.stackTraceLimit as V8 would attempt to install
207  // it again during deserialization.
208  if (require('v8').startupSnapshot.isBuildingSnapshot()) {
209    return false;
210  }
211
212  const desc = ObjectGetOwnPropertyDescriptor(Error, 'stackTraceLimit');
213  if (desc === undefined) {
214    return ObjectIsExtensible(Error);
215  }
216
217  return ObjectPrototypeHasOwnProperty(desc, 'writable') ?
218    desc.writable :
219    desc.set !== undefined;
220}
221
222function inspectWithNoCustomRetry(obj, options) {
223  const utilInspect = lazyInternalUtilInspect();
224
225  try {
226    return utilInspect.inspect(obj, options);
227  } catch {
228    return utilInspect.inspect(obj, { ...options, customInspect: false });
229  }
230}
231
232// A specialized Error that includes an additional info property with
233// additional information about the error condition.
234// It has the properties present in a UVException but with a custom error
235// message followed by the uv error code and uv error message.
236// It also has its own error code with the original uv error context put into
237// `err.info`.
238// The context passed into this error must have .code, .syscall and .message,
239// and may have .path and .dest.
240class SystemError extends Error {
241  constructor(key, context) {
242    const limit = Error.stackTraceLimit;
243    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
244    super();
245    // Reset the limit and setting the name property.
246    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
247    const prefix = getMessage(key, [], this);
248    let message = `${prefix}: ${context.syscall} returned ` +
249                  `${context.code} (${context.message})`;
250
251    if (context.path !== undefined)
252      message += ` ${context.path}`;
253    if (context.dest !== undefined)
254      message += ` => ${context.dest}`;
255
256    captureLargerStackTrace(this);
257
258    this.code = key;
259
260    ObjectDefineProperties(this, {
261      [kIsNodeError]: {
262        __proto__: null,
263        value: true,
264        enumerable: false,
265        writable: false,
266        configurable: true,
267      },
268      name: {
269        __proto__: null,
270        value: 'SystemError',
271        enumerable: false,
272        writable: true,
273        configurable: true,
274      },
275      message: {
276        __proto__: null,
277        value: message,
278        enumerable: false,
279        writable: true,
280        configurable: true,
281      },
282      info: {
283        __proto__: null,
284        value: context,
285        enumerable: true,
286        configurable: true,
287        writable: false,
288      },
289      errno: {
290        __proto__: null,
291        get() {
292          return context.errno;
293        },
294        set: (value) => {
295          context.errno = value;
296        },
297        enumerable: true,
298        configurable: true,
299      },
300      syscall: {
301        __proto__: null,
302        get() {
303          return context.syscall;
304        },
305        set: (value) => {
306          context.syscall = value;
307        },
308        enumerable: true,
309        configurable: true,
310      },
311    });
312
313    if (context.path !== undefined) {
314      // TODO(BridgeAR): Investigate why and when the `.toString()` was
315      // introduced. The `path` and `dest` properties in the context seem to
316      // always be of type string. We should probably just remove the
317      // `.toString()` and `Buffer.from()` operations and set the value on the
318      // context as the user did.
319      ObjectDefineProperty(this, 'path', {
320        __proto__: null,
321        get() {
322          return context.path != null ?
323            context.path.toString() : context.path;
324        },
325        set: (value) => {
326          context.path = value ?
327            lazyBuffer().from(value.toString()) : undefined;
328        },
329        enumerable: true,
330        configurable: true,
331      });
332    }
333
334    if (context.dest !== undefined) {
335      ObjectDefineProperty(this, 'dest', {
336        __proto__: null,
337        get() {
338          return context.dest != null ?
339            context.dest.toString() : context.dest;
340        },
341        set: (value) => {
342          context.dest = value ?
343            lazyBuffer().from(value.toString()) : undefined;
344        },
345        enumerable: true,
346        configurable: true,
347      });
348    }
349  }
350
351  toString() {
352    return `${this.name} [${this.code}]: ${this.message}`;
353  }
354
355  [SymbolFor('nodejs.util.inspect.custom')](recurseTimes, ctx) {
356    return lazyInternalUtilInspect().inspect(this, {
357      ...ctx,
358      getters: true,
359      customInspect: false,
360    });
361  }
362}
363
364function makeSystemErrorWithCode(key) {
365  return class NodeError extends SystemError {
366    constructor(ctx) {
367      super(key, ctx);
368    }
369  };
370}
371
372function makeNodeErrorWithCode(Base, key) {
373  return function NodeError(...args) {
374    const limit = Error.stackTraceLimit;
375    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
376    const error = new Base();
377    // Reset the limit and setting the name property.
378    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
379    const message = getMessage(key, args, error);
380    ObjectDefineProperties(error, {
381      [kIsNodeError]: {
382        __proto__: null,
383        value: true,
384        enumerable: false,
385        writable: false,
386        configurable: true,
387      },
388      message: {
389        __proto__: null,
390        value: message,
391        enumerable: false,
392        writable: true,
393        configurable: true,
394      },
395      toString: {
396        __proto__: null,
397        value() {
398          return `${this.name} [${key}]: ${this.message}`;
399        },
400        enumerable: false,
401        writable: true,
402        configurable: true,
403      },
404    });
405    captureLargerStackTrace(error);
406    error.code = key;
407    return error;
408  };
409}
410
411/**
412 * This function removes unnecessary frames from Node.js core errors.
413 * @template {(...args: unknown[]) => unknown} T
414 * @param {T} fn
415 * @returns {T}
416 */
417function hideStackFrames(fn) {
418  // We rename the functions that will be hidden to cut off the stacktrace
419  // at the outermost one
420  const hidden = nodeInternalPrefix + fn.name;
421  ObjectDefineProperty(fn, 'name', { __proto__: null, value: hidden });
422  return fn;
423}
424
425// Utility function for registering the error codes. Only used here. Exported
426// *only* to allow for testing.
427function E(sym, val, def, ...otherClasses) {
428  // Special case for SystemError that formats the error message differently
429  // The SystemErrors only have SystemError as their base classes.
430  messages.set(sym, val);
431  if (def === SystemError) {
432    def = makeSystemErrorWithCode(sym);
433  } else {
434    def = makeNodeErrorWithCode(def, sym);
435  }
436
437  if (otherClasses.length !== 0) {
438    otherClasses.forEach((clazz) => {
439      def[clazz.name] = makeNodeErrorWithCode(clazz, sym);
440    });
441  }
442  codes[sym] = def;
443}
444
445function getMessage(key, args, self) {
446  const msg = messages.get(key);
447
448  assert ??= require('internal/assert');
449
450  if (typeof msg === 'function') {
451    assert(
452      msg.length <= args.length, // Default options do not count.
453      `Code: ${key}; The provided arguments length (${args.length}) does not ` +
454        `match the required ones (${msg.length}).`,
455    );
456    return ReflectApply(msg, self, args);
457  }
458
459  const regex = /%[dfijoOs]/g;
460  let expectedLength = 0;
461  while (RegExpPrototypeExec(regex, msg) !== null) expectedLength++;
462  assert(
463    expectedLength === args.length,
464    `Code: ${key}; The provided arguments length (${args.length}) does not ` +
465      `match the required ones (${expectedLength}).`,
466  );
467  if (args.length === 0)
468    return msg;
469
470  ArrayPrototypeUnshift(args, msg);
471  return ReflectApply(lazyInternalUtilInspect().format, null, args);
472}
473
474let uvBinding;
475
476function lazyUv() {
477  uvBinding ??= internalBinding('uv');
478  return uvBinding;
479}
480
481const uvUnmappedError = ['UNKNOWN', 'unknown error'];
482
483function uvErrmapGet(name) {
484  uvBinding = lazyUv();
485  uvBinding.errmap ??= uvBinding.getErrorMap();
486  return MapPrototypeGet(uvBinding.errmap, name);
487}
488
489const captureLargerStackTrace = hideStackFrames(
490  function captureLargerStackTrace(err) {
491    const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
492    if (stackTraceLimitIsWritable) {
493      userStackTraceLimit = Error.stackTraceLimit;
494      Error.stackTraceLimit = Infinity;
495    }
496    ErrorCaptureStackTrace(err);
497    // Reset the limit
498    if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
499
500    return err;
501  });
502
503/**
504 * This creates an error compatible with errors produced in the C++
505 * function UVException using a context object with data assembled in C++.
506 * The goal is to migrate them to ERR_* errors later when compatibility is
507 * not a concern.
508 * @param {object} ctx
509 * @returns {Error}
510 */
511const uvException = hideStackFrames(function uvException(ctx) {
512  const { 0: code, 1: uvmsg } = uvErrmapGet(ctx.errno) || uvUnmappedError;
513  let message = `${code}: ${ctx.message || uvmsg}, ${ctx.syscall}`;
514
515  let path;
516  let dest;
517  if (ctx.path) {
518    path = ctx.path.toString();
519    message += ` '${path}'`;
520  }
521  if (ctx.dest) {
522    dest = ctx.dest.toString();
523    message += ` -> '${dest}'`;
524  }
525
526  // Reducing the limit improves the performance significantly. We do not lose
527  // the stack frames due to the `captureStackTrace()` function that is called
528  // later.
529  const tmpLimit = Error.stackTraceLimit;
530  if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
531  // Pass the message to the constructor instead of setting it on the object
532  // to make sure it is the same as the one created in C++
533  // eslint-disable-next-line no-restricted-syntax
534  const err = new Error(message);
535  if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmpLimit;
536
537  for (const prop of ObjectKeys(ctx)) {
538    if (prop === 'message' || prop === 'path' || prop === 'dest') {
539      continue;
540    }
541    err[prop] = ctx[prop];
542  }
543
544  err.code = code;
545  if (path) {
546    err.path = path;
547  }
548  if (dest) {
549    err.dest = dest;
550  }
551
552  return captureLargerStackTrace(err);
553});
554
555/**
556 * This creates an error compatible with errors produced in the C++
557 * This function should replace the deprecated
558 * `exceptionWithHostPort()` function.
559 * @param {number} err - A libuv error number
560 * @param {string} syscall
561 * @param {string} address
562 * @param {number} [port]
563 * @returns {Error}
564 */
565const uvExceptionWithHostPort = hideStackFrames(
566  function uvExceptionWithHostPort(err, syscall, address, port) {
567    const { 0: code, 1: uvmsg } = uvErrmapGet(err) || uvUnmappedError;
568    const message = `${syscall} ${code}: ${uvmsg}`;
569    let details = '';
570
571    if (port && port > 0) {
572      details = ` ${address}:${port}`;
573    } else if (address) {
574      details = ` ${address}`;
575    }
576
577    // Reducing the limit improves the performance significantly. We do not
578    // lose the stack frames due to the `captureStackTrace()` function that
579    // is called later.
580    const tmpLimit = Error.stackTraceLimit;
581    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
582    // eslint-disable-next-line no-restricted-syntax
583    const ex = new Error(`${message}${details}`);
584    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmpLimit;
585    ex.code = code;
586    ex.errno = err;
587    ex.syscall = syscall;
588    ex.address = address;
589    if (port) {
590      ex.port = port;
591    }
592
593    return captureLargerStackTrace(ex);
594  });
595
596/**
597 * This used to be util._errnoException().
598 * @param {number} err - A libuv error number
599 * @param {string} syscall
600 * @param {string} [original]
601 * @returns {Error}
602 */
603const errnoException = hideStackFrames(
604  function errnoException(err, syscall, original) {
605    // TODO(joyeecheung): We have to use the type-checked
606    // getSystemErrorName(err) to guard against invalid arguments from users.
607    // This can be replaced with [ code ] = errmap.get(err) when this method
608    // is no longer exposed to user land.
609    util ??= require('util');
610    const code = util.getSystemErrorName(err);
611    const message = original ?
612      `${syscall} ${code} ${original}` : `${syscall} ${code}`;
613
614    const tmpLimit = Error.stackTraceLimit;
615    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
616    // eslint-disable-next-line no-restricted-syntax
617    const ex = new Error(message);
618    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmpLimit;
619    ex.errno = err;
620    ex.code = code;
621    ex.syscall = syscall;
622
623    return captureLargerStackTrace(ex);
624  });
625
626/**
627 * Deprecated, new function is `uvExceptionWithHostPort()`
628 * New function added the error description directly
629 * from C++. this method for backwards compatibility
630 * @param {number} err - A libuv error number
631 * @param {string} syscall
632 * @param {string} address
633 * @param {number} [port]
634 * @param {string} [additional]
635 * @returns {Error}
636 */
637const exceptionWithHostPort = hideStackFrames(
638  function exceptionWithHostPort(err, syscall, address, port, additional) {
639    // TODO(joyeecheung): We have to use the type-checked
640    // getSystemErrorName(err) to guard against invalid arguments from users.
641    // This can be replaced with [ code ] = errmap.get(err) when this method
642    // is no longer exposed to user land.
643    util ??= require('util');
644    const code = util.getSystemErrorName(err);
645    let details = '';
646    if (port && port > 0) {
647      details = ` ${address}:${port}`;
648    } else if (address) {
649      details = ` ${address}`;
650    }
651    if (additional) {
652      details += ` - Local (${additional})`;
653    }
654
655    // Reducing the limit improves the performance significantly. We do not
656    // lose the stack frames due to the `captureStackTrace()` function that
657    // is called later.
658    const tmpLimit = Error.stackTraceLimit;
659    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
660    // eslint-disable-next-line no-restricted-syntax
661    const ex = new Error(`${syscall} ${code}${details}`);
662    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmpLimit;
663    ex.errno = err;
664    ex.code = code;
665    ex.syscall = syscall;
666    ex.address = address;
667    if (port) {
668      ex.port = port;
669    }
670
671    return captureLargerStackTrace(ex);
672  });
673
674/**
675 * @param {number|string} code - A libuv error number or a c-ares error code
676 * @param {string} syscall
677 * @param {string} [hostname]
678 * @returns {Error}
679 */
680const dnsException = hideStackFrames(function(code, syscall, hostname) {
681  let errno;
682  // If `code` is of type number, it is a libuv error number, else it is a
683  // c-ares error code.
684  // TODO(joyeecheung): translate c-ares error codes into numeric ones and
685  // make them available in a property that's not error.errno (since they
686  // can be in conflict with libuv error codes). Also make sure
687  // util.getSystemErrorName() can understand them when an being informed that
688  // the number is a c-ares error code.
689  if (typeof code === 'number') {
690    errno = code;
691    // ENOTFOUND is not a proper POSIX error, but this error has been in place
692    // long enough that it's not practical to remove it.
693    if (code === lazyUv().UV_EAI_NODATA || code === lazyUv().UV_EAI_NONAME) {
694      code = 'ENOTFOUND'; // Fabricated error name.
695    } else {
696      code = lazyInternalUtil().getSystemErrorName(code);
697    }
698  }
699  const message = `${syscall} ${code}${hostname ? ` ${hostname}` : ''}`;
700  // Reducing the limit improves the performance significantly. We do not lose
701  // the stack frames due to the `captureStackTrace()` function that is called
702  // later.
703  const tmpLimit = Error.stackTraceLimit;
704  if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
705  // eslint-disable-next-line no-restricted-syntax
706  const ex = new Error(message);
707  if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmpLimit;
708  ex.errno = errno;
709  ex.code = code;
710  ex.syscall = syscall;
711  if (hostname) {
712    ex.hostname = hostname;
713  }
714
715  return captureLargerStackTrace(ex);
716});
717
718function connResetException(msg) {
719  // eslint-disable-next-line no-restricted-syntax
720  const ex = new Error(msg);
721  ex.code = 'ECONNRESET';
722  return ex;
723}
724
725let maxStack_ErrorName;
726let maxStack_ErrorMessage;
727/**
728 * Returns true if `err.name` and `err.message` are equal to engine-specific
729 * values indicating max call stack size has been exceeded.
730 * "Maximum call stack size exceeded" in V8.
731 * @param {Error} err
732 * @returns {boolean}
733 */
734function isStackOverflowError(err) {
735  if (maxStack_ErrorMessage === undefined) {
736    try {
737      function overflowStack() { overflowStack(); }
738      overflowStack();
739    } catch (err) {
740      maxStack_ErrorMessage = err.message;
741      maxStack_ErrorName = err.name;
742    }
743  }
744
745  return err && err.name === maxStack_ErrorName &&
746         err.message === maxStack_ErrorMessage;
747}
748
749// Only use this for integers! Decimal numbers do not work with this function.
750function addNumericalSeparator(val) {
751  let res = '';
752  let i = val.length;
753  const start = val[0] === '-' ? 1 : 0;
754  for (; i >= start + 4; i -= 3) {
755    res = `_${StringPrototypeSlice(val, i - 3, i)}${res}`;
756  }
757  return `${StringPrototypeSlice(val, 0, i)}${res}`;
758}
759
760// Used to enhance the stack that will be picked up by the inspector
761const kEnhanceStackBeforeInspector = Symbol('kEnhanceStackBeforeInspector');
762
763// These are supposed to be called only on fatal exceptions before
764// the process exits.
765const fatalExceptionStackEnhancers = {
766  beforeInspector(error) {
767    if (typeof error[kEnhanceStackBeforeInspector] !== 'function') {
768      return error.stack;
769    }
770
771    try {
772      // Set the error.stack here so it gets picked up by the
773      // inspector.
774      error.stack = error[kEnhanceStackBeforeInspector]();
775    } catch {
776      // We are just enhancing the error. If it fails, ignore it.
777    }
778    return error.stack;
779  },
780  afterInspector(error) {
781    const originalStack = error.stack;
782    let useColors = true;
783    // Some consoles do not convert ANSI escape sequences to colors,
784    // rather display them directly to the stdout. On those consoles,
785    // libuv emulates colors by intercepting stdout stream and calling
786    // corresponding Windows API functions for setting console colors.
787    // However, fatal error are handled differently and we cannot easily
788    // highlight them. On Windows, detecting whether a console supports
789    // ANSI escape sequences is not reliable.
790    if (isWindows) {
791      const info = internalBinding('os').getOSInformation();
792      const ver = ArrayPrototypeMap(StringPrototypeSplit(info[2], '.'),
793                                    Number);
794      if (ver[0] !== 10 || ver[2] < 14393) {
795        useColors = false;
796      }
797    }
798    const {
799      inspect,
800      inspectDefaultOptions: {
801        colors: defaultColors,
802      },
803    } = lazyInternalUtilInspect();
804    const colors = useColors && (lazyUtilColors().shouldColorize(process.stderr) || defaultColors);
805    try {
806      return inspect(error, {
807        colors,
808        customInspect: false,
809        depth: MathMax(inspect.defaultOptions.depth, 5),
810      });
811    } catch {
812      return originalStack;
813    }
814  },
815};
816
817const {
818  privateSymbols: {
819    arrow_message_private_symbol,
820  },
821} = internalBinding('util');
822// Ensures the printed error line is from user code.
823function setArrowMessage(err, arrowMessage) {
824  err[arrow_message_private_symbol] = arrowMessage;
825}
826
827// Hide stack lines before the first user code line.
828function hideInternalStackFrames(error) {
829  overrideStackTrace.set(error, (error, stackFrames) => {
830    let frames = stackFrames;
831    if (typeof stackFrames === 'object') {
832      frames = ArrayPrototypeFilter(
833        stackFrames,
834        (frm) => !StringPrototypeStartsWith(frm.getFileName() || '',
835                                            'node:internal'),
836      );
837    }
838    ArrayPrototypeUnshift(frames, error);
839    return ArrayPrototypeJoin(frames, '\n    at ');
840  });
841}
842
843// Node uses an AbortError that isn't exactly the same as the DOMException
844// to make usage of the error in userland and readable-stream easier.
845// It is a regular error with `.code` and `.name`.
846class AbortError extends Error {
847  constructor(message = 'The operation was aborted', options = undefined) {
848    if (options !== undefined && typeof options !== 'object') {
849      throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options);
850    }
851    super(message, options);
852    this.code = 'ABORT_ERR';
853    this.name = 'AbortError';
854  }
855}
856
857/**
858 * This creates a generic Node.js error.
859 * @param {string} message The error message.
860 * @param {object} errorProperties Object with additional properties to be added to the error.
861 * @returns {Error}
862 */
863const genericNodeError = hideStackFrames(function genericNodeError(message, errorProperties) {
864  // eslint-disable-next-line no-restricted-syntax
865  const err = new Error(message);
866  ObjectAssign(err, errorProperties);
867  return err;
868});
869
870/**
871 * Determine the specific type of a value for type-mismatch errors.
872 * @param {*} value
873 * @returns {string}
874 */
875function determineSpecificType(value) {
876  if (value == null) {
877    return '' + value;
878  }
879  if (typeof value === 'function' && value.name) {
880    return `function ${value.name}`;
881  }
882  if (typeof value === 'object') {
883    if (value.constructor?.name) {
884      return `an instance of ${value.constructor.name}`;
885    }
886    return `${lazyInternalUtilInspect().inspect(value, { depth: -1 })}`;
887  }
888  let inspected = lazyInternalUtilInspect()
889    .inspect(value, { colors: false });
890  if (inspected.length > 28) { inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`; }
891
892  return `type ${typeof value} (${inspected})`;
893}
894
895/**
896 * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
897 * We cannot use Intl.ListFormat because it's not available in
898 * --without-intl builds.
899 * @param {string[]} array An array of strings.
900 * @param {string} [type] The list type to be inserted before the last element.
901 * @returns {string}
902 */
903function formatList(array, type = 'and') {
904  return array.length < 3 ? ArrayPrototypeJoin(array, ` ${type} `) :
905    `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
906}
907
908module.exports = {
909  AbortError,
910  aggregateTwoErrors,
911  aggregateErrors,
912  captureLargerStackTrace,
913  codes,
914  connResetException,
915  dnsException,
916  // This is exported only to facilitate testing.
917  determineSpecificType,
918  E,
919  errnoException,
920  exceptionWithHostPort,
921  fatalExceptionStackEnhancers,
922  formatList,
923  genericNodeError,
924  getMessage,
925  hideInternalStackFrames,
926  hideStackFrames,
927  inspectWithNoCustomRetry,
928  isErrorStackTraceLimitWritable,
929  isStackOverflowError,
930  kEnhanceStackBeforeInspector,
931  kIsNodeError,
932  kNoOverride,
933  maybeOverridePrepareStackTrace,
934  overrideStackTrace,
935  prepareStackTrace,
936  setArrowMessage,
937  SystemError,
938  uvErrmapGet,
939  uvException,
940  uvExceptionWithHostPort,
941};
942
943// To declare an error message, use the E(sym, val, def) function above. The sym
944// must be an upper case string. The val can be either a function or a string.
945// The def must be an error class.
946// The return value of the function must be a string.
947// Examples:
948// E('EXAMPLE_KEY1', 'This is the error value', Error);
949// E('EXAMPLE_KEY2', (a, b) => return `${a} ${b}`, RangeError);
950//
951// Once an error code has been assigned, the code itself MUST NOT change and
952// any given error code must never be reused to identify a different error.
953//
954// Any error code added here should also be added to the documentation
955//
956// Note: Please try to keep these in alphabetical order
957//
958// Note: Node.js specific errors must begin with the prefix ERR_
959
960E('ERR_ACCESS_DENIED',
961  'Access to this API has been restricted. Permission: %s',
962  Error);
963E('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError);
964E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError);
965E('ERR_ASSERTION', '%s', Error);
966E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError);
967E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError);
968E('ERR_BROTLI_INVALID_PARAM', '%s is not a valid Brotli parameter', RangeError);
969E('ERR_BUFFER_OUT_OF_BOUNDS',
970  // Using a default argument here is important so the argument is not counted
971  // towards `Function#length`.
972  (name = undefined) => {
973    if (name) {
974      return `"${name}" is outside of buffer bounds`;
975    }
976    return 'Attempt to access memory outside buffer bounds';
977  }, RangeError);
978E('ERR_BUFFER_TOO_LARGE',
979  'Cannot create a Buffer larger than %s bytes',
980  RangeError);
981E('ERR_CANNOT_WATCH_SIGINT', 'Cannot watch for SIGINT signals', Error);
982E('ERR_CHILD_CLOSED_BEFORE_REPLY',
983  'Child closed before reply received', Error);
984E('ERR_CHILD_PROCESS_IPC_REQUIRED',
985  "Forked processes must have an IPC channel, missing value 'ipc' in %s",
986  Error);
987E('ERR_CHILD_PROCESS_STDIO_MAXBUFFER', '%s maxBuffer length exceeded',
988  RangeError);
989E('ERR_CONSOLE_WRITABLE_STREAM',
990  'Console expects a writable stream instance for %s', TypeError);
991E('ERR_CONTEXT_NOT_INITIALIZED', 'context used is not initialized', Error);
992E('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED',
993  'Custom engines not supported by this OpenSSL', Error);
994E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError);
995E('ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY',
996  'Public key is not valid for specified curve', Error);
997E('ERR_CRYPTO_ENGINE_UNKNOWN', 'Engine "%s" was not found', Error);
998E('ERR_CRYPTO_FIPS_FORCED',
999  'Cannot set FIPS mode, it was forced with --force-fips at startup.', Error);
1000E('ERR_CRYPTO_FIPS_UNAVAILABLE', 'Cannot set FIPS mode in a non-FIPS build.',
1001  Error);
1002E('ERR_CRYPTO_HASH_FINALIZED', 'Digest already called', Error);
1003E('ERR_CRYPTO_HASH_UPDATE_FAILED', 'Hash update failed', Error);
1004E('ERR_CRYPTO_INCOMPATIBLE_KEY', 'Incompatible %s: %s', Error);
1005E('ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS', 'The selected key encoding %s %s.',
1006  Error);
1007E('ERR_CRYPTO_INVALID_DIGEST', 'Invalid digest: %s', TypeError);
1008E('ERR_CRYPTO_INVALID_JWK', 'Invalid JWK data', TypeError);
1009E('ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE',
1010  'Invalid key object type %s, expected %s.', TypeError);
1011E('ERR_CRYPTO_INVALID_STATE', 'Invalid state for operation %s', Error);
1012E('ERR_CRYPTO_PBKDF2_ERROR', 'PBKDF2 error', Error);
1013E('ERR_CRYPTO_SCRYPT_INVALID_PARAMETER', 'Invalid scrypt parameter', Error);
1014E('ERR_CRYPTO_SCRYPT_NOT_SUPPORTED', 'Scrypt algorithm not supported', Error);
1015// Switch to TypeError. The current implementation does not seem right.
1016E('ERR_CRYPTO_SIGN_KEY_REQUIRED', 'No key provided to sign', Error);
1017E('ERR_DEBUGGER_ERROR', '%s', Error);
1018E('ERR_DEBUGGER_STARTUP_ERROR', '%s', Error);
1019E('ERR_DIR_CLOSED', 'Directory handle was closed', Error);
1020E('ERR_DIR_CONCURRENT_OPERATION',
1021  'Cannot do synchronous work on directory handle with concurrent ' +
1022  'asynchronous operations', Error);
1023E('ERR_DNS_SET_SERVERS_FAILED', 'c-ares failed to set servers: "%s" [%s]',
1024  Error);
1025E('ERR_DOMAIN_CALLBACK_NOT_AVAILABLE',
1026  'A callback was registered through ' +
1027     'process.setUncaughtExceptionCaptureCallback(), which is mutually ' +
1028     'exclusive with using the `domain` module',
1029  Error);
1030E('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE',
1031  'The `domain` module is in use, which is mutually exclusive with calling ' +
1032     'process.setUncaughtExceptionCaptureCallback()',
1033  Error);
1034E('ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION',
1035  'Deserialize main function is already configured.', Error);
1036E('ERR_ENCODING_INVALID_ENCODED_DATA', function(encoding, ret) {
1037  this.errno = ret;
1038  return `The encoded data was not valid for encoding ${encoding}`;
1039}, TypeError);
1040E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported',
1041  RangeError);
1042E('ERR_EVAL_ESM_CANNOT_PRINT', '--print cannot be used with ESM input', Error);
1043E('ERR_EVENT_RECURSION', 'The event "%s" is already being dispatched', Error);
1044E('ERR_FALSY_VALUE_REJECTION', function(reason) {
1045  this.reason = reason;
1046  return 'Promise was rejected with falsy value';
1047}, Error);
1048E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM',
1049  'The feature %s is unavailable on the current platform' +
1050  ', which is being used to run Node.js',
1051  TypeError);
1052E('ERR_FS_CP_DIR_TO_NON_DIR',
1053  'Cannot overwrite directory with non-directory', SystemError);
1054E('ERR_FS_CP_EEXIST', 'Target already exists', SystemError);
1055E('ERR_FS_CP_EINVAL', 'Invalid src or dest', SystemError);
1056E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe', SystemError);
1057E('ERR_FS_CP_NON_DIR_TO_DIR',
1058  'Cannot overwrite non-directory with directory', SystemError);
1059E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file', SystemError);
1060E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY',
1061  'Cannot overwrite symlink in subdirectory of self', SystemError);
1062E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type', SystemError);
1063E('ERR_FS_EISDIR', 'Path is a directory', SystemError);
1064E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GiB', RangeError);
1065E('ERR_FS_INVALID_SYMLINK_TYPE',
1066  'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
1067  Error); // Switch to TypeError. The current implementation does not seem right
1068E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
1069  'HTTP/2 ALTSVC frames require a valid origin', TypeError);
1070E('ERR_HTTP2_ALTSVC_LENGTH',
1071  'HTTP/2 ALTSVC frames are limited to 16382 bytes', TypeError);
1072E('ERR_HTTP2_CONNECT_AUTHORITY',
1073  ':authority header is required for CONNECT requests', Error);
1074E('ERR_HTTP2_CONNECT_PATH',
1075  'The :path header is forbidden for CONNECT requests', Error);
1076E('ERR_HTTP2_CONNECT_SCHEME',
1077  'The :scheme header is forbidden for CONNECT requests', Error);
1078E('ERR_HTTP2_GOAWAY_SESSION',
1079  'New streams cannot be created after receiving a GOAWAY', Error);
1080E('ERR_HTTP2_HEADERS_AFTER_RESPOND',
1081  'Cannot specify additional headers after response initiated', Error);
1082E('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.', Error);
1083E('ERR_HTTP2_HEADER_SINGLE_VALUE',
1084  'Header field "%s" must only have a single value', TypeError);
1085E('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED',
1086  'Informational status codes cannot be used', RangeError);
1087E('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
1088  'HTTP/1 Connection specific headers are forbidden: "%s"', TypeError);
1089E('ERR_HTTP2_INVALID_HEADER_VALUE',
1090  'Invalid value "%s" for header "%s"', TypeError);
1091E('ERR_HTTP2_INVALID_INFO_STATUS',
1092  'Invalid informational status code: %s', RangeError);
1093E('ERR_HTTP2_INVALID_ORIGIN',
1094  'HTTP/2 ORIGIN frames require a valid origin', TypeError);
1095E('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH',
1096  'Packed settings length must be a multiple of six', RangeError);
1097E('ERR_HTTP2_INVALID_PSEUDOHEADER',
1098  '"%s" is an invalid pseudoheader or is used incorrectly', TypeError);
1099E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed', Error);
1100E('ERR_HTTP2_INVALID_SETTING_VALUE',
1101  // Using default arguments here is important so the arguments are not counted
1102  // towards `Function#length`.
1103  function(name, actual, min = undefined, max = undefined) {
1104    this.actual = actual;
1105    if (min !== undefined) {
1106      this.min = min;
1107      this.max = max;
1108    }
1109    return `Invalid value for setting "${name}": ${actual}`;
1110  }, TypeError, RangeError);
1111E('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed', Error);
1112E('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK',
1113  'Maximum number of pending settings acknowledgements', Error);
1114E('ERR_HTTP2_NESTED_PUSH',
1115  'A push stream cannot initiate another push stream.', Error);
1116E('ERR_HTTP2_NO_MEM', 'Out of memory', Error);
1117E('ERR_HTTP2_NO_SOCKET_MANIPULATION',
1118  'HTTP/2 sockets should not be directly manipulated (e.g. read and written)',
1119  Error);
1120E('ERR_HTTP2_ORIGIN_LENGTH',
1121  'HTTP/2 ORIGIN frames are limited to 16382 bytes', TypeError);
1122E('ERR_HTTP2_OUT_OF_STREAMS',
1123  'No stream ID is available because maximum stream ID has been reached',
1124  Error);
1125E('ERR_HTTP2_PAYLOAD_FORBIDDEN',
1126  'Responses with %s status must not have a payload', Error);
1127E('ERR_HTTP2_PING_CANCEL', 'HTTP2 ping cancelled', Error);
1128E('ERR_HTTP2_PING_LENGTH', 'HTTP2 ping payload must be 8 bytes', RangeError);
1129E('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED',
1130  'Cannot set HTTP/2 pseudo-headers', TypeError);
1131E('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams', Error);
1132E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error);
1133E('ERR_HTTP2_SEND_FILE_NOSEEK',
1134  'Offset or length can only be specified for regular files', Error);
1135E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error);
1136E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error);
1137E('ERR_HTTP2_SOCKET_BOUND',
1138  'The socket is already bound to an Http2Session', Error);
1139E('ERR_HTTP2_SOCKET_UNBOUND',
1140  'The socket has been disconnected from the Http2Session', Error);
1141E('ERR_HTTP2_STATUS_101',
1142  'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2', Error);
1143E('ERR_HTTP2_STATUS_INVALID', 'Invalid status code: %s', RangeError);
1144E('ERR_HTTP2_STREAM_CANCEL', function(error) {
1145  let msg = 'The pending stream has been canceled';
1146  if (error) {
1147    this.cause = error;
1148    if (typeof error.message === 'string')
1149      msg += ` (caused by: ${error.message})`;
1150  }
1151  return msg;
1152}, Error);
1153E('ERR_HTTP2_STREAM_ERROR', 'Stream closed with error code %s', Error);
1154E('ERR_HTTP2_STREAM_SELF_DEPENDENCY',
1155  'A stream cannot depend on itself', Error);
1156E('ERR_HTTP2_TOO_MANY_INVALID_FRAMES', 'Too many invalid HTTP/2 frames', Error);
1157E('ERR_HTTP2_TRAILERS_ALREADY_SENT',
1158  'Trailing headers have already been sent', Error);
1159E('ERR_HTTP2_TRAILERS_NOT_READY',
1160  'Trailing headers cannot be sent until after the wantTrailers event is ' +
1161  'emitted', Error);
1162E('ERR_HTTP2_UNSUPPORTED_PROTOCOL', 'protocol "%s" is unsupported.', Error);
1163E('ERR_HTTP_BODY_NOT_ALLOWED',
1164  'Adding content for this request method or response status is not allowed.', Error);
1165E('ERR_HTTP_CONTENT_LENGTH_MISMATCH',
1166  'Response body\'s content-length of %s byte(s) does not match the content-length of %s byte(s) set in header', Error);
1167E('ERR_HTTP_HEADERS_SENT',
1168  'Cannot %s headers after they are sent to the client', Error);
1169E('ERR_HTTP_INVALID_HEADER_VALUE',
1170  'Invalid value "%s" for header "%s"', TypeError);
1171E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s', RangeError);
1172E('ERR_HTTP_REQUEST_TIMEOUT', 'Request timeout', Error);
1173E('ERR_HTTP_SOCKET_ASSIGNED',
1174  'ServerResponse has an already assigned socket', Error);
1175E('ERR_HTTP_SOCKET_ENCODING',
1176  'Changing the socket encoding is not allowed per RFC7230 Section 3.', Error);
1177E('ERR_HTTP_TRAILER_INVALID',
1178  'Trailers are invalid with this transfer encoding', Error);
1179E('ERR_ILLEGAL_CONSTRUCTOR', 'Illegal constructor', TypeError);
1180E('ERR_IMPORT_ASSERTION_TYPE_FAILED',
1181  'Module "%s" is not of type "%s"', TypeError);
1182E('ERR_IMPORT_ASSERTION_TYPE_MISSING',
1183  'Module "%s" needs an import assertion of type "%s"', TypeError);
1184E('ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED',
1185  'Import assertion type "%s" is unsupported', TypeError);
1186E('ERR_INCOMPATIBLE_OPTION_PAIR',
1187  'Option "%s" cannot be used in combination with option "%s"', TypeError);
1188E('ERR_INPUT_TYPE_NOT_ALLOWED', '--input-type can only be used with string ' +
1189  'input via --eval, --print, or STDIN', Error);
1190E('ERR_INSPECTOR_ALREADY_ACTIVATED',
1191  'Inspector is already activated. Close it with inspector.close() ' +
1192  'before activating it again.',
1193  Error);
1194E('ERR_INSPECTOR_ALREADY_CONNECTED', '%s is already connected', Error);
1195E('ERR_INSPECTOR_CLOSED', 'Session was closed', Error);
1196E('ERR_INSPECTOR_COMMAND', 'Inspector error %d: %s', Error);
1197E('ERR_INSPECTOR_NOT_ACTIVE', 'Inspector is not active', Error);
1198E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available', Error);
1199E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected', Error);
1200E('ERR_INSPECTOR_NOT_WORKER', 'Current thread is not a worker', Error);
1201E('ERR_INTERNAL_ASSERTION', (message) => {
1202  const suffix = 'This is caused by either a bug in Node.js ' +
1203    'or incorrect usage of Node.js internals.\n' +
1204    'Please open an issue with this stack trace at ' +
1205    'https://github.com/nodejs/node/issues\n';
1206  return message === undefined ? suffix : `${message}\n${suffix}`;
1207}, Error);
1208E('ERR_INVALID_ADDRESS_FAMILY', function(addressType, host, port) {
1209  this.host = host;
1210  this.port = port;
1211  return `Invalid address family: ${addressType} ${host}:${port}`;
1212}, RangeError);
1213E('ERR_INVALID_ARG_TYPE',
1214  (name, expected, actual) => {
1215    assert(typeof name === 'string', "'name' must be a string");
1216    if (!ArrayIsArray(expected)) {
1217      expected = [expected];
1218    }
1219
1220    let msg = 'The ';
1221    if (StringPrototypeEndsWith(name, ' argument')) {
1222      // For cases like 'first argument'
1223      msg += `${name} `;
1224    } else {
1225      const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument';
1226      msg += `"${name}" ${type} `;
1227    }
1228    msg += 'must be ';
1229
1230    const types = [];
1231    const instances = [];
1232    const other = [];
1233
1234    for (const value of expected) {
1235      assert(typeof value === 'string',
1236             'All expected entries have to be of type string');
1237      if (ArrayPrototypeIncludes(kTypes, value)) {
1238        ArrayPrototypePush(types, StringPrototypeToLowerCase(value));
1239      } else if (RegExpPrototypeExec(classRegExp, value) !== null) {
1240        ArrayPrototypePush(instances, value);
1241      } else {
1242        assert(value !== 'object',
1243               'The value "object" should be written as "Object"');
1244        ArrayPrototypePush(other, value);
1245      }
1246    }
1247
1248    // Special handle `object` in case other instances are allowed to outline
1249    // the differences between each other.
1250    if (instances.length > 0) {
1251      const pos = ArrayPrototypeIndexOf(types, 'object');
1252      if (pos !== -1) {
1253        ArrayPrototypeSplice(types, pos, 1);
1254        ArrayPrototypePush(instances, 'Object');
1255      }
1256    }
1257
1258    if (types.length > 0) {
1259      msg += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(types, 'or')}`;
1260      if (instances.length > 0 || other.length > 0)
1261        msg += ' or ';
1262    }
1263
1264    if (instances.length > 0) {
1265      msg += `an instance of ${formatList(instances, 'or')}`;
1266      if (other.length > 0)
1267        msg += ' or ';
1268    }
1269
1270    if (other.length > 0) {
1271      if (other.length > 1) {
1272        msg += `one of ${formatList(other, 'or')}`;
1273      } else {
1274        if (StringPrototypeToLowerCase(other[0]) !== other[0])
1275          msg += 'an ';
1276        msg += `${other[0]}`;
1277      }
1278    }
1279
1280    msg += `. Received ${determineSpecificType(actual)}`;
1281
1282    return msg;
1283  }, TypeError);
1284E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
1285  let inspected = lazyInternalUtilInspect().inspect(value);
1286  if (inspected.length > 128) {
1287    inspected = `${StringPrototypeSlice(inspected, 0, 128)}...`;
1288  }
1289  const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument';
1290  return `The ${type} '${name}' ${reason}. Received ${inspected}`;
1291}, TypeError, RangeError);
1292E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s', RangeError);
1293E('ERR_INVALID_BUFFER_SIZE',
1294  'Buffer size must be a multiple of %s', RangeError);
1295E('ERR_INVALID_CHAR',
1296  // Using a default argument here is important so the argument is not counted
1297  // towards `Function#length`.
1298  (name, field = undefined) => {
1299    let msg = `Invalid character in ${name}`;
1300    if (field !== undefined) {
1301      msg += ` ["${field}"]`;
1302    }
1303    return msg;
1304  }, TypeError);
1305E('ERR_INVALID_CURSOR_POS',
1306  'Cannot set cursor row without setting its column', TypeError);
1307E('ERR_INVALID_FD',
1308  '"fd" must be a positive integer: %s', RangeError);
1309E('ERR_INVALID_FD_TYPE', 'Unsupported fd type: %s', TypeError);
1310E('ERR_INVALID_FILE_URL_HOST',
1311  'File URL host must be "localhost" or empty on %s', TypeError);
1312E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s', TypeError);
1313E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent', TypeError);
1314E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]', TypeError);
1315E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s', TypeError);
1316E('ERR_INVALID_MIME_SYNTAX', (production, str, invalidIndex) => {
1317  const msg = invalidIndex !== -1 ? ` at ${invalidIndex}` : '';
1318  return `The MIME syntax for a ${production} in "${str}" is invalid` + msg;
1319}, TypeError);
1320E('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => {
1321  return `Invalid module "${request}" ${reason}${base ?
1322    ` imported from ${base}` : ''}`;
1323}, TypeError);
1324E('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => {
1325  return `Invalid package config ${path}${base ? ` while importing ${base}` :
1326    ''}${message ? `. ${message}` : ''}`;
1327}, Error);
1328E('ERR_INVALID_PACKAGE_TARGET',
1329  (pkgPath, key, target, isImport = false, base = undefined) => {
1330    const relError = typeof target === 'string' && !isImport &&
1331      target.length && !StringPrototypeStartsWith(target, './');
1332    if (key === '.') {
1333      assert(isImport === false);
1334      return `Invalid "exports" main target ${JSONStringify(target)} defined ` +
1335        `in the package config ${pkgPath}package.json${base ?
1336          ` imported from ${base}` : ''}${relError ?
1337          '; targets must start with "./"' : ''}`;
1338    }
1339    return `Invalid "${isImport ? 'imports' : 'exports'}" target ${
1340      JSONStringify(target)} defined for '${key}' in the package config ${
1341      pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ?
1342      '; targets must start with "./"' : ''}`;
1343  }, Error);
1344E('ERR_INVALID_PROTOCOL',
1345  'Protocol "%s" not supported. Expected "%s"',
1346  TypeError);
1347E('ERR_INVALID_REPL_EVAL_CONFIG',
1348  'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', TypeError);
1349E('ERR_INVALID_REPL_INPUT', '%s', TypeError);
1350E('ERR_INVALID_RETURN_PROPERTY', (input, name, prop, value) => {
1351  return `Expected a valid ${input} to be returned for the "${prop}" from the` +
1352         ` "${name}" function but got ${value}.`;
1353}, TypeError);
1354E('ERR_INVALID_RETURN_PROPERTY_VALUE', (input, name, prop, value) => {
1355  let type;
1356  if (value?.constructor?.name) {
1357    type = `instance of ${value.constructor.name}`;
1358  } else {
1359    type = `type ${typeof value}`;
1360  }
1361  return `Expected ${input} to be returned for the "${prop}" from the` +
1362         ` "${name}" function but got ${type}.`;
1363}, TypeError);
1364E('ERR_INVALID_RETURN_VALUE', (input, name, value) => {
1365  const type = determineSpecificType(value);
1366
1367  return `Expected ${input} to be returned from the "${name}"` +
1368         ` function but got ${type}.`;
1369}, TypeError, RangeError);
1370E('ERR_INVALID_STATE', 'Invalid state: %s', Error, TypeError, RangeError);
1371E('ERR_INVALID_SYNC_FORK_INPUT',
1372  'Asynchronous forks do not support ' +
1373    'Buffer, TypedArray, DataView or string input: %s',
1374  TypeError);
1375E('ERR_INVALID_THIS', 'Value of "this" must be of type %s', TypeError);
1376E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple', TypeError);
1377E('ERR_INVALID_URI', 'URI malformed', URIError);
1378E('ERR_INVALID_URL', function(input) {
1379  this.input = input;
1380  // Don't include URL in message.
1381  // (See https://github.com/nodejs/node/pull/38614)
1382  return 'Invalid URL';
1383}, TypeError);
1384E('ERR_INVALID_URL_SCHEME',
1385  (expected) => {
1386    if (typeof expected === 'string')
1387      expected = [expected];
1388    assert(expected.length <= 2);
1389    const res = expected.length === 2 ?
1390      `one of scheme ${expected[0]} or ${expected[1]}` :
1391      `of scheme ${expected[0]}`;
1392    return `The URL must be ${res}`;
1393  }, TypeError);
1394E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error);
1395E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error);
1396E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error);
1397E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error);
1398E(
1399  'ERR_LOADER_CHAIN_INCOMPLETE',
1400  '"%s" did not call the next hook in its chain and did not' +
1401  ' explicitly signal a short circuit. If this is intentional, include' +
1402  ' `shortCircuit: true` in the hook\'s return.',
1403  Error,
1404);
1405E('ERR_MANIFEST_ASSERT_INTEGRITY',
1406  (moduleURL, realIntegrities) => {
1407    let msg = `The content of "${
1408      moduleURL
1409    }" does not match the expected integrity.`;
1410    if (realIntegrities.size) {
1411      const sri = ArrayPrototypeJoin(
1412        ArrayFrom(realIntegrities.entries(),
1413                  ({ 0: alg, 1: dgs }) => `${alg}-${dgs}`),
1414        ' ',
1415      );
1416      msg += ` Integrities found are: ${sri}`;
1417    } else {
1418      msg += ' The resource was not found in the policy.';
1419    }
1420    return msg;
1421  }, Error);
1422E('ERR_MANIFEST_DEPENDENCY_MISSING',
1423  'Manifest resource %s does not list %s as a dependency specifier for ' +
1424  'conditions: %s',
1425  Error);
1426E('ERR_MANIFEST_INTEGRITY_MISMATCH',
1427  'Manifest resource %s has multiple entries but integrity lists do not match',
1428  SyntaxError);
1429E('ERR_MANIFEST_INVALID_RESOURCE_FIELD',
1430  'Manifest resource %s has invalid property value for %s',
1431  TypeError);
1432E('ERR_MANIFEST_INVALID_SPECIFIER',
1433  'Manifest resource %s has invalid dependency mapping %s',
1434  TypeError);
1435E('ERR_MANIFEST_TDZ', 'Manifest initialization has not yet run', Error);
1436E('ERR_MANIFEST_UNKNOWN_ONERROR',
1437  'Manifest specified unknown error behavior "%s".',
1438  SyntaxError);
1439E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error);
1440E('ERR_MISSING_ARGS',
1441  (...args) => {
1442    assert(args.length > 0, 'At least one arg needs to be specified');
1443    let msg = 'The ';
1444    const len = args.length;
1445    const wrap = (a) => `"${a}"`;
1446    args = ArrayPrototypeMap(
1447      args,
1448      (a) => (ArrayIsArray(a) ?
1449        ArrayPrototypeJoin(ArrayPrototypeMap(a, wrap), ' or ') :
1450        wrap(a)),
1451    );
1452    msg += `${formatList(args)} argument${len > 1 ? 's' : ''}`;
1453    return `${msg} must be specified`;
1454  }, TypeError);
1455E('ERR_MISSING_OPTION', '%s is required', TypeError);
1456E('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => {
1457  return `Cannot find ${type} '${path}' imported from ${base}`;
1458}, Error);
1459E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error);
1460E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function', TypeError);
1461E('ERR_NAPI_INVALID_DATAVIEW_ARGS',
1462  'byte_offset + byte_length should be less than or equal to the size in ' +
1463    'bytes of the array passed in',
1464  RangeError);
1465E('ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT',
1466  'start offset of %s should be a multiple of %s', RangeError);
1467E('ERR_NAPI_INVALID_TYPEDARRAY_LENGTH',
1468  'Invalid typed array length', RangeError);
1469E('ERR_NETWORK_IMPORT_BAD_RESPONSE',
1470  "import '%s' received a bad response: %s", Error);
1471E('ERR_NETWORK_IMPORT_DISALLOWED',
1472  "import of '%s' by %s is not supported: %s", Error);
1473E('ERR_NOT_BUILDING_SNAPSHOT',
1474  'Operation cannot be invoked when not building startup snapshot', Error);
1475E('ERR_NO_CRYPTO',
1476  'Node.js is not compiled with OpenSSL crypto support', Error);
1477E('ERR_NO_ICU',
1478  '%s is not supported on Node.js compiled without ICU', TypeError);
1479E('ERR_OPERATION_FAILED', 'Operation failed: %s', Error, TypeError);
1480E('ERR_OUT_OF_RANGE',
1481  (str, range, input, replaceDefaultBoolean = false) => {
1482    assert(range, 'Missing "range" argument');
1483    let msg = replaceDefaultBoolean ? str :
1484      `The value of "${str}" is out of range.`;
1485    let received;
1486    if (NumberIsInteger(input) && MathAbs(input) > 2 ** 32) {
1487      received = addNumericalSeparator(String(input));
1488    } else if (typeof input === 'bigint') {
1489      received = String(input);
1490      if (input > 2n ** 32n || input < -(2n ** 32n)) {
1491        received = addNumericalSeparator(received);
1492      }
1493      received += 'n';
1494    } else {
1495      received = lazyInternalUtilInspect().inspect(input);
1496    }
1497    msg += ` It must be ${range}. Received ${received}`;
1498    return msg;
1499  }, RangeError);
1500E('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => {
1501  return `Package import specifier "${specifier}" is not defined${packagePath ?
1502    ` in package ${packagePath}package.json` : ''} imported from ${base}`;
1503}, TypeError);
1504E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
1505  if (subpath === '.')
1506    return `No "exports" main defined in ${pkgPath}package.json${base ?
1507      ` imported from ${base}` : ''}`;
1508  return `Package subpath '${subpath}' is not defined by "exports" in ${
1509    pkgPath}package.json${base ? ` imported from ${base}` : ''}`;
1510}, Error);
1511E('ERR_PARSE_ARGS_INVALID_OPTION_VALUE', '%s', TypeError);
1512E('ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL', "Unexpected argument '%s'. This " +
1513  'command does not take positional arguments', TypeError);
1514E('ERR_PARSE_ARGS_UNKNOWN_OPTION', (option, allowPositionals) => {
1515  const suggestDashDash = allowPositionals ? '. To specify a positional ' +
1516    "argument starting with a '-', place it at the end of the command after " +
1517    `'--', as in '-- ${JSONStringify(option)}` : '';
1518  return `Unknown option '${option}'${suggestDashDash}`;
1519}, TypeError);
1520E('ERR_PERFORMANCE_INVALID_TIMESTAMP',
1521  '%d is not a valid timestamp', TypeError);
1522E('ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS', '%s', TypeError);
1523E('ERR_REQUIRE_ESM',
1524  function(filename, hasEsmSyntax, parentPath = null, packageJsonPath = null) {
1525    hideInternalStackFrames(this);
1526    let msg = `require() of ES Module ${filename}${parentPath ? ` from ${
1527      parentPath}` : ''} not supported.`;
1528    if (!packageJsonPath) {
1529      if (StringPrototypeEndsWith(filename, '.mjs'))
1530        msg += `\nInstead change the require of ${filename} to a dynamic ` +
1531            'import() which is available in all CommonJS modules.';
1532      return msg;
1533    }
1534    const path = require('path');
1535    const basename = parentPath && path.basename(filename) ===
1536      path.basename(parentPath) ? filename : path.basename(filename);
1537    if (hasEsmSyntax) {
1538      msg += `\nInstead change the require of ${basename} in ${parentPath} to` +
1539        ' a dynamic import() which is available in all CommonJS modules.';
1540      return msg;
1541    }
1542    msg += `\n${basename} is treated as an ES module file as it is a .js ` +
1543      'file whose nearest parent package.json contains "type": "module" ' +
1544      'which declares all .js files in that package scope as ES modules.' +
1545      `\nInstead rename ${basename} to end in .cjs, change the requiring ` +
1546      'code to use dynamic import() which is available in all CommonJS ' +
1547      'modules, or change "type": "module" to "type": "commonjs" in ' +
1548      `${packageJsonPath} to treat all .js files as CommonJS (using .mjs for ` +
1549      'all ES modules instead).\n';
1550    return msg;
1551  }, Error);
1552E('ERR_SCRIPT_EXECUTION_INTERRUPTED',
1553  'Script execution was interrupted by `SIGINT`', Error);
1554E('ERR_SERVER_ALREADY_LISTEN',
1555  'Listen method has been called more than once without closing.', Error);
1556E('ERR_SERVER_NOT_RUNNING', 'Server is not running.', Error);
1557E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound', Error);
1558E('ERR_SOCKET_BAD_BUFFER_SIZE',
1559  'Buffer size must be a positive integer', TypeError);
1560E('ERR_SOCKET_BAD_PORT', (name, port, allowZero = true) => {
1561  assert(typeof allowZero === 'boolean',
1562         "The 'allowZero' argument must be of type boolean.");
1563  const operator = allowZero ? '>=' : '>';
1564  return `${name} should be ${operator} 0 and < 65536. Received ${determineSpecificType(port)}.`;
1565}, RangeError);
1566E('ERR_SOCKET_BAD_TYPE',
1567  'Bad socket type specified. Valid types are: udp4, udp6', TypeError);
1568E('ERR_SOCKET_BUFFER_SIZE',
1569  'Could not get or set buffer size',
1570  SystemError);
1571E('ERR_SOCKET_CLOSED', 'Socket is closed', Error);
1572E('ERR_SOCKET_CLOSED_BEFORE_CONNECTION',
1573  'Socket closed before the connection was established',
1574  Error);
1575E('ERR_SOCKET_DGRAM_IS_CONNECTED', 'Already connected', Error);
1576E('ERR_SOCKET_DGRAM_NOT_CONNECTED', 'Not connected', Error);
1577E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running', Error);
1578E('ERR_SRI_PARSE',
1579  'Subresource Integrity string %j had an unexpected %j at position %d',
1580  SyntaxError);
1581E('ERR_STREAM_ALREADY_FINISHED',
1582  'Cannot call %s after a stream was finished',
1583  Error);
1584E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error);
1585E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error);
1586E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
1587E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error);
1588E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error);
1589E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT',
1590  'stream.unshift() after end event', Error);
1591E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error);
1592E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error);
1593E('ERR_SYNTHETIC', 'JavaScript Callstack', Error);
1594E('ERR_SYSTEM_ERROR', 'A system error occurred', SystemError);
1595E('ERR_TAP_LEXER_ERROR', function(errorMsg) {
1596  hideInternalStackFrames(this);
1597  return errorMsg;
1598}, Error);
1599E('ERR_TAP_PARSER_ERROR', function(errorMsg, details, tokenCausedError, source) {
1600  hideInternalStackFrames(this);
1601  this.cause = tokenCausedError;
1602  const { column, line, start, end } = tokenCausedError.location;
1603  const errorDetails = `${details} at line ${line}, column ${column} (start ${start}, end ${end})`;
1604  return errorMsg + errorDetails;
1605}, SyntaxError);
1606E('ERR_TAP_VALIDATION_ERROR', function(errorMsg) {
1607  hideInternalStackFrames(this);
1608  return errorMsg;
1609}, Error);
1610E('ERR_TEST_FAILURE', function(error, failureType) {
1611  hideInternalStackFrames(this);
1612  assert(typeof failureType === 'string' || typeof failureType === 'symbol',
1613         "The 'failureType' argument must be of type string or symbol.");
1614
1615  let msg = error?.message ?? error;
1616
1617  if (typeof msg !== 'string') {
1618    msg = inspectWithNoCustomRetry(msg);
1619  }
1620
1621  this.failureType = failureType;
1622  this.cause = error;
1623  return msg;
1624}, Error);
1625E('ERR_TLS_CERT_ALTNAME_FORMAT', 'Invalid subject alternative name string',
1626  SyntaxError);
1627E('ERR_TLS_CERT_ALTNAME_INVALID', function(reason, host, cert) {
1628  this.reason = reason;
1629  this.host = host;
1630  this.cert = cert;
1631  return `Hostname/IP does not match certificate's altnames: ${reason}`;
1632}, Error);
1633E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048', Error);
1634E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout', Error);
1635E('ERR_TLS_INVALID_CONTEXT', '%s must be a SecureContext', TypeError);
1636E('ERR_TLS_INVALID_PROTOCOL_VERSION',
1637  '%j is not a valid %s TLS protocol version', TypeError);
1638E('ERR_TLS_INVALID_STATE', 'TLS socket connection must be securely established',
1639  Error);
1640E('ERR_TLS_PROTOCOL_VERSION_CONFLICT',
1641  'TLS protocol version %j conflicts with secureProtocol %j', TypeError);
1642E('ERR_TLS_RENEGOTIATION_DISABLED',
1643  'TLS session renegotiation disabled for this socket', Error);
1644
1645// This should probably be a `TypeError`.
1646E('ERR_TLS_REQUIRED_SERVER_NAME',
1647  '"servername" is required parameter for Server.addContext', Error);
1648E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected', Error);
1649E('ERR_TLS_SNI_FROM_SERVER',
1650  'Cannot issue SNI from a TLS server-side socket', Error);
1651E('ERR_TRACE_EVENTS_CATEGORY_REQUIRED',
1652  'At least one category is required', TypeError);
1653E('ERR_TRACE_EVENTS_UNAVAILABLE', 'Trace events are unavailable', Error);
1654
1655// This should probably be a `RangeError`.
1656E('ERR_TTY_INIT_FAILED', 'TTY initialization failed', SystemError);
1657E('ERR_UNAVAILABLE_DURING_EXIT', 'Cannot call function in process exit ' +
1658  'handler', Error);
1659E('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET',
1660  '`process.setupUncaughtExceptionCapture()` was called while a capture ' +
1661    'callback was already active',
1662  Error);
1663E('ERR_UNESCAPED_CHARACTERS', '%s contains unescaped characters', TypeError);
1664E('ERR_UNHANDLED_ERROR',
1665  // Using a default argument here is important so the argument is not counted
1666  // towards `Function#length`.
1667  (err = undefined) => {
1668    const msg = 'Unhandled error.';
1669    if (err === undefined) return msg;
1670    return `${msg} (${err})`;
1671  }, Error);
1672E('ERR_UNKNOWN_BUILTIN_MODULE', 'No such built-in module: %s', Error);
1673E('ERR_UNKNOWN_CREDENTIAL', '%s identifier does not exist: %s', Error);
1674E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError);
1675E('ERR_UNKNOWN_FILE_EXTENSION', (ext, path, suggestion) => {
1676  let msg = `Unknown file extension "${ext}" for ${path}`;
1677  if (suggestion) {
1678    msg += `. ${suggestion}`;
1679  }
1680  return msg;
1681}, TypeError);
1682E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s for URL %s',
1683  RangeError);
1684E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError);
1685E('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " +
1686'resolving ES modules imported from %s', Error);
1687E('ERR_UNSUPPORTED_ESM_URL_SCHEME', (url, supported) => {
1688  let msg = `Only URLs with a scheme in: ${formatList(supported)} are supported by the default ESM loader`;
1689  if (isWindows && url.protocol.length === 2) {
1690    msg +=
1691      '. On Windows, absolute paths must be valid file:// URLs';
1692  }
1693  msg += `. Received protocol '${url.protocol}'`;
1694  return msg;
1695}, Error);
1696E('ERR_USE_AFTER_CLOSE', '%s was closed', Error);
1697
1698// This should probably be a `TypeError`.
1699E('ERR_VALID_PERFORMANCE_ENTRY_TYPE',
1700  'At least one valid performance entry type is required', Error);
1701E('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING',
1702  'A dynamic import callback was not specified.', TypeError);
1703E('ERR_VM_MODULE_ALREADY_LINKED', 'Module has already been linked', Error);
1704E('ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
1705  'Cached data cannot be created for a module which has been evaluated', Error);
1706E('ERR_VM_MODULE_DIFFERENT_CONTEXT',
1707  'Linked modules must use the same context', Error);
1708E('ERR_VM_MODULE_LINK_FAILURE', function(message, cause) {
1709  this.cause = cause;
1710  return message;
1711}, Error);
1712E('ERR_VM_MODULE_NOT_MODULE',
1713  'Provided module is not an instance of Module', Error);
1714E('ERR_VM_MODULE_STATUS', 'Module status %s', Error);
1715E('ERR_WASI_ALREADY_STARTED', 'WASI instance has already started', Error);
1716E('ERR_WEBASSEMBLY_RESPONSE', 'WebAssembly response %s', TypeError);
1717E('ERR_WORKER_INIT_FAILED', 'Worker initialization failure: %s', Error);
1718E('ERR_WORKER_INVALID_EXEC_ARGV', (errors, msg = 'invalid execArgv flags') =>
1719  `Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors, ', ')}`,
1720  Error);
1721E('ERR_WORKER_NOT_RUNNING', 'Worker instance not running', Error);
1722E('ERR_WORKER_OUT_OF_MEMORY',
1723  'Worker terminated due to reaching memory limit: %s', Error);
1724E('ERR_WORKER_PATH', (filename) =>
1725  'The worker script or module filename must be an absolute path or a ' +
1726  'relative path starting with \'./\' or \'../\'.' +
1727  (StringPrototypeStartsWith(filename, 'file://') ?
1728    ' Wrap file:// URLs with `new URL`.' : ''
1729  ) +
1730  (StringPrototypeStartsWith(filename, 'data:text/javascript') ?
1731    ' Wrap data: URLs with `new URL`.' : ''
1732  ) +
1733  ` Received "${filename}"`,
1734  TypeError);
1735E('ERR_WORKER_UNSERIALIZABLE_ERROR',
1736  'Serializing an uncaught exception failed', Error);
1737E('ERR_WORKER_UNSUPPORTED_OPERATION',
1738  '%s is not supported in workers', TypeError);
1739E('ERR_ZLIB_INITIALIZATION_FAILED', 'Initialization failed', Error);
1740