Sources/OrgApp/JavaScriptBlocks.swift

702b2432b070f1428ff34e8d5ae3d141ba29a007
orgstar/Sources/OrgApp/JavaScriptBlocks.swift

1332 lines · 71539 bytes

   1#if canImport(JavaScriptCore)
   2import Foundation
   3import JavaScriptCore
   4import OrgCore
   5
   6/// js and javascript blocks in JavaScriptCore, as `node` runs them, for builds that can't start
   7/// node. Node's `require('util')`, `require('process')`, `console` and timers are written in
   8/// JavaScript below; a block that uses anything else of Node's, or prints a value whose text
   9/// can't be made the same as Node's, is refused rather than given a different result.
  10///
  11/// The public JavaScriptCore API can't stop a running script. A run that is canceled or times
  12/// out ends at once, but a script that never finishes keeps its thread busy until the app quits.
  13public enum JavaScriptBlocks {
  14    /// Runs `job` when it is a js block, in `directory` or its `:dir`; nil for other languages.
  15    /// `:cmd` is ignored.
  16    public static func run(_ job: BabelJob, directory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput? {
  17        guard job.language == "js" || job.language == "javascript" else { return nil }
  18        let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
  19        switch job.runner {
  20        case .process:
  21            guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
  22            return try await evaluate(timeout: timeout) { run in try Engine().main(job.input, run: run) }
  23        case .session(let name, _, .node):
  24            guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
  25            // One context per file folder and session name; a stopped run's context is dropped.
  26            let key = folder.path + "\u{1}" + name
  27            let engine = sessions.engine(key)
  28            do {
  29                return try await evaluate(timeout: timeout) { run in try engine.session(job.input, value: !job.finish.output, run: run) }
  30            } catch let error where error is CancellationError || error is Stopped {
  31                sessions.drop(key, engine)
  32                throw error
  33            }
  34        default:
  35            return nil
  36        }
  37    }
  38
  39    struct Stopped: Error, CustomStringConvertible {
  40        let description: String
  41    }
  42
  43    /// Runs `body` on a thread of its own, which a cancel or the timeout leaves behind.
  44    private static func evaluate(timeout: Duration, _ body: @escaping @Sendable (Run) throws -> BabelOutput) async throws -> BabelOutput {
  45        let run = Run()
  46        let thread = Thread { run.end(Result { try body(run) }) }
  47        thread.stackSize = 8 << 20
  48        thread.start()
  49        let limit = Task {
  50            try await Task.sleep(for: timeout)
  51            run.end(.failure(Stopped(description: "The block took longer than \(timeout) and was stopped.")))
  52        }
  53        defer { limit.cancel() }
  54        return try await withTaskCancellationHandler {
  55            try await withCheckedThrowingContinuation { run.wait($0) }
  56        } onCancel: {
  57            run.end(.failure(CancellationError()))
  58        }
  59    }
  60
  61    /// A run, which ends once: with the script's output, a cancel or the timeout.
  62    final class Run: @unchecked Sendable {
  63        private let lock = NSLock()
  64        private var result: Result<BabelOutput, Error>?
  65        private var continuation: CheckedContinuation<BabelOutput, Error>?
  66        private let wake = DispatchSemaphore(value: 0)
  67
  68        var stopped: Bool { lock.withLock { result != nil } }
  69
  70        func end(_ outcome: Result<BabelOutput, Error>) {
  71            let (first, waiting) = lock.withLock { () -> (Bool, CheckedContinuation<BabelOutput, Error>?) in
  72                guard result == nil else { return (false, nil) }
  73                result = outcome
  74                defer { continuation = nil }
  75                return (true, continuation)
  76            }
  77            guard first else { return }
  78            waiting?.resume(with: outcome)
  79            wake.signal()
  80        }
  81
  82        func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) {
  83            let done = lock.withLock { () -> Result<BabelOutput, Error>? in
  84                if result == nil { self.continuation = continuation }
  85                return result
  86            }
  87            if let done { continuation.resume(with: done) }
  88        }
  89
  90        /// Waits for a timer, or until the run ends.
  91        func sleep(milliseconds: Double) {
  92            _ = wake.wait(timeout: .now() + .milliseconds(Int(milliseconds.rounded(.up))))
  93        }
  94    }
  95
  96    private static let sessions = Sessions()
  97
  98    final class Sessions: @unchecked Sendable {
  99        private let lock = NSLock()
 100        private var engines: [String: Engine] = [:]
 101
 102        func engine(_ key: String) -> Engine {
 103            lock.withLock {
 104                if let engine = engines[key] { return engine }
 105                let engine = Engine()
 106                engines[key] = engine
 107                return engine
 108            }
 109        }
 110
 111        func drop(_ key: String, _ engine: Engine) {
 112            lock.withLock { if engines[key] === engine { engines[key] = nil } }
 113        }
 114    }
 115
 116    /// A context with Node's globals, and what its scripts wrote.
 117    final class Engine: @unchecked Sendable {
 118        private final class Output {
 119            var stdout = ""
 120            var stderr = ""
 121            var exception: JSValue?
 122        }
 123
 124        private let context: JSContext
 125        private let node: JSValue
 126        private let output: Output
 127        private let lock = NSLock()
 128
 129        init() {
 130            let output = Output()
 131            self.output = output
 132            context = JSContext()
 133            let write: @convention(block) (Int32, String) -> Void = { fd, text in
 134                if fd == 1 { output.stdout += text } else { output.stderr += text }
 135            }
 136            context.exceptionHandler = { _, exception in output.exception = exception }
 137            node = context.evaluateScript(Self.shim).call(withArguments: [write])
 138        }
 139
 140        /// Runs `source` as node runs a script on standard input, then its timers.
 141        func main(_ source: String, run: Run) throws -> BabelOutput {
 142            node.invokeMethod("main", withArguments: [source])
 143            runTimers(run)
 144            return try finish(result: nil)
 145        }
 146
 147        /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does;
 148        /// with `value`, the result is its completion value as `util.inspect` prints it.
 149        func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput {
 150            try lock.withLock {
 151                output.stdout = ""
 152                output.stderr = ""
 153                output.exception = nil
 154                node.invokeMethod("begin", withArguments: [])
 155                let completion = context.evaluateScript(source)
 156                var result: String?
 157                if let exception = output.exception {
 158                    node.invokeMethod("failed", withArguments: [exception])
 159                } else if value, let completion {
 160                    result = node.invokeMethod("inspect", withArguments: [completion]).toString()
 161                }
 162                runTimers(run)
 163                return try finish(result: result)
 164            }
 165        }
 166
 167        private func runTimers(_ run: Run) {
 168            while !run.stopped, let wait = node.invokeMethod("tick", withArguments: [])?.toDouble(), wait >= 0 {
 169                if wait > 0 { run.sleep(milliseconds: wait) }
 170            }
 171        }
 172
 173        private func finish(result: String?) throws -> BabelOutput {
 174            if let refused = node.forProperty("refused")?.toString(), !refused.isEmpty {
 175                throw Babel.Failure.message("This block uses \(refused), which runs only in node.")
 176            }
 177            guard let error = node.forProperty("error"), !error.isUndefined else {
 178                return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr)
 179            }
 180            return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr + (error.toString() ?? "") + "\n", status: 1)
 181        }
 182
 183        /// Node's globals and modules; `util.inspect` and `util.format` are ported from Node 26's
 184        /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the
 185        /// runner's controls.
 186        static let shim = #"""
 187            (function (write) {
 188              'use strict';
 189              const evaluate = eval;
 190              const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now() };
 191
 192              function refuse(what) {
 193                if (!state.refused) state.refused = what;
 194                throw new Error(`${what} isn't available`);
 195              }
 196              function out(fd, text) {
 197                if (!state.dead) write(fd, text.toWellFormed());
 198              }
 199              // Members a script may use; any other is refused rather than answered differently.
 200              const guarded = new WeakSet();
 201              function guard(target, name) {
 202                const proxy = new Proxy(target, {
 203                  get(t, key, receiver) {
 204                    if (typeof key === 'symbol' || key in t) return Reflect.get(t, key, receiver);
 205                    refuse(`${name}.${key}`);
 206                  },
 207                });
 208                guarded.add(proxy);
 209                return proxy;
 210              }
 211              // The script's proxies, target and handler, or null once revoked: JavaScriptCore can't tell
 212              // a proxy, and Node shows one.
 213              const proxies = new WeakMap();
 214              const RealProxy = Proxy;
 215              function revocable(target, handler) {
 216                const made = RealProxy.revocable(target, handler);
 217                proxies.set(made.proxy, [target, handler]);
 218                return { proxy: made.proxy, revoke: [() => { proxies.set(made.proxy, null); made.revoke(); }][0] };
 219              }
 220              const ProxyConstructor = new RealProxy(RealProxy, {
 221                construct(target, args, newTarget) {
 222                  const proxy = Reflect.construct(target, args, newTarget);
 223                  proxies.set(proxy, [args[0], args[1]]);
 224                  return proxy;
 225                },
 226                get(target, key, receiver) {
 227                  return key === 'revocable' ? revocable : Reflect.get(target, key, receiver);
 228                },
 229              });
 230
 231              // util.inspect and util.format, after Node's lib/internal/util/inspect.js.
 232              const kObjectType = 0, kArrayType = 1, kArrayExtrasType = 2;
 233              const defaults = {
 234                showHidden: false, depth: 2, colors: false, customInspect: true, showProxy: false, maxArrayLength: 100,
 235                maxStringLength: 10000, breakLength: 80, compact: 3, sorted: false, getters: false, numericSeparator: false,
 236              };
 237              const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
 238              const builtInObjects = new Set(Object.getOwnPropertyNames(globalThis).filter((e) => /^[A-Z][a-zA-Z0-9]+$/.test(e)));
 239              const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
 240              const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
 241              const strEscapeSequencesRegExpSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
 242              const strEscapeSequencesReplacerSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
 243              const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
 244              const numberRegExp = /^(0|[1-9][0-9]*)$/;
 245              const classRegExp = /^(\s+[^(]*?)\s*{/;
 246              const stripCommentsRegExp = /(\/\/.*?\n)|(\/\*(.|\n)*?\*\/)/g;
 247              const kMinLineLength = 16;
 248              const meta = [
 249                '\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07',
 250                '\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F',
 251                '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17',
 252                '\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F',
 253                '', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '',
 254                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 255                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 256                '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '',
 257                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 258                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F',
 259                '\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87',
 260                '\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F',
 261                '\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97',
 262                '\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F',
 263              ];
 264
 265              // Type checks through the built-ins' own brand checks.
 266              function branded(fn, value) {
 267                try { fn.call(value); return true; } catch { return false; }
 268              }
 269              const getter = (proto, key) => Object.getOwnPropertyDescriptor(proto, key).get;
 270              const typedArrayProto = Object.getPrototypeOf(Int8Array.prototype);
 271              const typedArrayTag = getter(typedArrayProto, Symbol.toStringTag);
 272              const isSet = (v) => branded(getter(Set.prototype, 'size'), v);
 273              const isMap = (v) => branded(getter(Map.prototype, 'size'), v);
 274              const isTypedArray = (v) => typedArrayTag.call(v) !== undefined;
 275              const isArrayBuffer = (v) => branded(getter(ArrayBuffer.prototype, 'byteLength'), v);
 276              const isDataView = (v) => branded(getter(DataView.prototype, 'byteLength'), v);
 277              const isRegExp = (v) => v !== RegExp.prototype && branded(getter(RegExp.prototype, 'source'), v);
 278              const isDate = (v) => branded(Date.prototype.getTime, v);
 279              const isWeakMap = (v) => branded(function () { WeakMap.prototype.has.call(this, {}); }, v);
 280              const isWeakSet = (v) => branded(function () { WeakSet.prototype.has.call(this, {}); }, v);
 281              const isPromise = (v) => Object.prototype.toString.call(v) === '[object Promise]' && v instanceof Promise;
 282              const isError = (v) => v instanceof Error || Object.prototype.toString.call(v) === '[object Error]';
 283              const isArgumentsObject = (v) => Object.prototype.toString.call(v) === '[object Arguments]';
 284              const iteratorTags = ['[object Map Iterator]', '[object Set Iterator]', '[object Array Iterator]', '[object String Iterator]', '[object Generator]', '[object Iterator Helper]'];
 285              const generatorFunctionProto = Object.getPrototypeOf(function* () {});
 286              const asyncFunctionProto = Object.getPrototypeOf(async function () {});
 287              const asyncGeneratorFunctionProto = Object.getPrototypeOf(async function* () {});
 288              const boxes = [
 289                ['Number', Number.prototype.valueOf], ['String', String.prototype.valueOf], ['Boolean', Boolean.prototype.valueOf],
 290                ['BigInt', BigInt.prototype.valueOf], ['Symbol', Symbol.prototype.valueOf],
 291              ];
 292              const boxType = (v) => boxes.find(([, fn]) => branded(fn, v));
 293              const internalGetConstructorName = (v) => Object.prototype.toString.call(v).slice(8, -1);
 294
 295              // Width as a terminal shows it; text beyond ASCII is measured by ICU in Node.
 296              function getStringWidth(str) {
 297                let width = 0;
 298                for (let i = 0; i < str.length; i++) {
 299                  const code = str.charCodeAt(i);
 300                  if (code >= 127) refuse('lining up text beyond ASCII in util.inspect');
 301                  width += code >= 32 ? 1 : 0;
 302                }
 303                return width;
 304              }
 305
 306              function inspect(value, opts) {
 307                const ctx = { budget: {}, indentationLvl: 0, seen: [], currentDepth: 0, ...defaults };
 308                if (arguments.length > 1) {
 309                  if (arguments.length > 2) {
 310                    if (arguments[2] !== undefined) ctx.depth = arguments[2];
 311                    if (arguments.length > 3 && arguments[3] !== undefined) ctx.colors = arguments[3];
 312                  }
 313                  if (typeof opts === 'boolean') {
 314                    ctx.showHidden = opts;
 315                  } else if (opts) {
 316                    for (const key of Object.keys(opts)) {
 317                      if (Object.prototype.hasOwnProperty.call(defaults, key)) ctx[key] = opts[key];
 318                      else if (key === 'stylize') refuse('util.inspect with stylize');
 319                      else if (ctx.userOptions === undefined) ctx.userOptions = opts;
 320                    }
 321                  }
 322                }
 323                if (ctx.colors) refuse('util.inspect with colors');
 324                if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
 325                if (ctx.maxStringLength === null) ctx.maxStringLength = Infinity;
 326                return formatValue(ctx, value, 0);
 327              }
 328              inspect.custom = customInspectSymbol;
 329              Object.defineProperty(inspect, 'defaultOptions', { get() { refuse('util.inspect.defaultOptions'); } });
 330
 331              const stylize = (str) => str;
 332
 333              function getUserOptions(ctx) {
 334                const ret = { stylize };
 335                for (const key of Object.keys(defaults)) ret[key] = ctx[key];
 336                return { ...ret, ...ctx.userOptions };
 337              }
 338
 339              function formatValue(ctx, value, recurseTimes, typedArray) {
 340                if (typeof value !== 'object' && typeof value !== 'function') return formatPrimitive(value, ctx);
 341                if (value === null) return 'null';
 342                if (guarded.has(value)) refuse('util.inspect of console, process or util');
 343                const context = value;
 344                let proxyCount = 0;
 345                let proxy = proxies.get(value);
 346                if (proxy !== undefined) {
 347                  if (ctx.showProxy) return proxy === null ? '<Revoked Proxy>' : formatProxy(ctx, proxy, recurseTimes);
 348                  do {
 349                    if (proxy === null) return 'Proxy('.repeat(proxyCount) + '<Revoked Proxy>' + ')'.repeat(proxyCount);
 350                    value = proxy[0];
 351                    proxy = proxies.get(value);
 352                    proxyCount += 1;
 353                  } while (proxy !== undefined);
 354                }
 355                const formatted = formatUnwrapped(ctx, value, context, recurseTimes, typedArray);
 356                return 'Proxy('.repeat(proxyCount) + formatted + ')'.repeat(proxyCount);
 357              }
 358
 359              function formatProxy(ctx, proxy, recurseTimes) {
 360                if (recurseTimes > ctx.depth && ctx.depth !== null) return 'Proxy [Array]';
 361                recurseTimes += 1;
 362                ctx.indentationLvl += 2;
 363                const res = [formatValue(ctx, proxy[0], recurseTimes), formatValue(ctx, proxy[1], recurseTimes)];
 364                ctx.indentationLvl -= 2;
 365                return reduceToSingleString(ctx, res, '', ['Proxy [', ']'], kArrayExtrasType, recurseTimes);
 366              }
 367
 368              function formatUnwrapped(ctx, value, context, recurseTimes, typedArray) {
 369                if (ctx.customInspect) {
 370                  const maybeCustom = value[customInspectSymbol];
 371                  if (typeof maybeCustom === 'function' && maybeCustom !== inspect &&
 372                      Object.getOwnPropertyDescriptor(value, 'constructor')?.value?.prototype !== value) {
 373                    const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
 374                    const ret = maybeCustom.call(context, depth, getUserOptions(ctx), inspect);
 375                    if (ret !== context) {
 376                      if (typeof ret !== 'string') return formatValue(ctx, ret, recurseTimes);
 377                      return ret.replaceAll('\n', `\n${' '.repeat(ctx.indentationLvl)}`);
 378                    }
 379                  }
 380                }
 381                if (ctx.seen.includes(value)) {
 382                  let index = 1;
 383                  if (ctx.circular === undefined) {
 384                    ctx.circular = new Map();
 385                    ctx.circular.set(value, index);
 386                  } else {
 387                    index = ctx.circular.get(value);
 388                    if (index === undefined) {
 389                      index = ctx.circular.size + 1;
 390                      ctx.circular.set(value, index);
 391                    }
 392                  }
 393                  return `[Circular *${index}]`;
 394                }
 395                return formatRaw(ctx, value, recurseTimes, typedArray);
 396              }
 397
 398              function getConstructorName(obj, ctx, recurseTimes, protoProps) {
 399                let firstProto;
 400                const tmp = obj;
 401                while (obj) {
 402                  const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
 403                  if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '' &&
 404                      isInstanceof(tmp, descriptor.value)) {
 405                    if (protoProps !== undefined && (firstProto !== obj || !builtInObjects.has(descriptor.value.name))) {
 406                      addPrototypeProperties(ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
 407                    }
 408                    return String(descriptor.value.name);
 409                  }
 410                  obj = Object.getPrototypeOf(obj);
 411                  if (firstProto === undefined) firstProto = obj;
 412                }
 413                if (firstProto === null) return null;
 414                const res = internalGetConstructorName(tmp);
 415                if (recurseTimes > ctx.depth && ctx.depth !== null) return `${res} <Complex prototype>`;
 416                const protoConstr = getConstructorName(firstProto, ctx, recurseTimes + 1, protoProps);
 417                if (protoConstr === null) {
 418                  return `${res} <${inspect(firstProto, { ...ctx, customInspect: false, depth: -1 })}>`;
 419                }
 420                return `${res} <${protoConstr}>`;
 421              }
 422
 423              function isInstanceof(object, proto) {
 424                try { return object instanceof proto; } catch { return false; }
 425              }
 426
 427              function addPrototypeProperties(ctx, main, obj, recurseTimes, output) {
 428                let depth = 0;
 429                let keys;
 430                let keySet;
 431                do {
 432                  if (depth !== 0 || main === obj) {
 433                    obj = Object.getPrototypeOf(obj);
 434                    if (obj === null) return;
 435                    const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
 436                    if (descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name)) return;
 437                  }
 438                  if (depth === 0) {
 439                    keySet = new Set();
 440                  } else {
 441                    keys.forEach((key) => keySet.add(key));
 442                  }
 443                  keys = Reflect.ownKeys(obj);
 444                  ctx.seen.push(main);
 445                  for (const key of keys) {
 446                    if (key === 'constructor' || Object.prototype.hasOwnProperty.call(main, key) || (depth !== 0 && keySet.has(key))) continue;
 447                    const desc = Object.getOwnPropertyDescriptor(obj, key);
 448                    if (typeof desc.value === 'function') continue;
 449                    output.push(formatProperty(ctx, obj, recurseTimes, key, kObjectType, desc, main));
 450                  }
 451                  ctx.seen.pop();
 452                } while (++depth !== 3);
 453              }
 454
 455              function getPrefix(constructor, tag, fallback, size = '') {
 456                if (constructor === null) {
 457                  if (tag !== '' && fallback !== tag) return `[${fallback}${size}: null prototype] [${tag}] `;
 458                  return `[${fallback}${size}: null prototype] `;
 459                }
 460                if (tag !== '') {
 461                  const dot = tag.lastIndexOf('.');
 462                  if (constructor === (dot >= 1 ? tag.slice(dot + 1) : tag)) return `${tag}${size} `;
 463                  return `${constructor}${size} [${tag}] `;
 464                }
 465                return `${constructor}${size} `;
 466              }
 467
 468              function getKeys(value, showHidden) {
 469                let keys;
 470                const symbols = Object.getOwnPropertySymbols(value);
 471                if (showHidden) {
 472                  keys = Object.getOwnPropertyNames(value);
 473                  if (symbols.length !== 0) keys.push(...symbols);
 474                } else {
 475                  keys = Object.keys(value);
 476                  if (symbols.length !== 0) keys.push(...symbols.filter((key) => Object.prototype.propertyIsEnumerable.call(value, key)));
 477                }
 478                return keys;
 479              }
 480
 481              function isIndex(key) {
 482                return typeof key === 'string' && numberRegExp.test(key) && Number(key) < 2 ** 32 - 1;
 483              }
 484
 485              function getOwnNonIndexProperties(value, showHidden) {
 486                const keys = Reflect.ownKeys(value).filter((key) => !isIndex(key) &&
 487                  (showHidden || Object.prototype.propertyIsEnumerable.call(value, key)));
 488                return [...keys.filter((key) => typeof key === 'string'), ...keys.filter((key) => typeof key === 'symbol')];
 489              }
 490
 491              function getCtxStyle(value, constructor, tag) {
 492                let fallback = '';
 493                if (constructor === null) {
 494                  fallback = internalGetConstructorName(value);
 495                  if (fallback === tag) fallback = 'Object';
 496                }
 497                return getPrefix(constructor, tag, fallback);
 498              }
 499
 500              function formatRaw(ctx, value, recurseTimes, typedArray) {
 501                let keys;
 502                let protoProps;
 503                if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) protoProps = [];
 504                const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
 505                if (protoProps !== undefined && protoProps.length === 0) protoProps = undefined;
 506                let tag = '';
 507                try { tag = value[Symbol.toStringTag]; } catch {}
 508                if (typeof tag !== 'string' || (tag !== '' && (ctx.showHidden ? Object.prototype.hasOwnProperty
 509                  : Object.prototype.propertyIsEnumerable).call(value, Symbol.toStringTag))) {
 510                  tag = '';
 511                }
 512                let base = '';
 513                let formatter = () => [];
 514                let braces;
 515                let noIterator = true;
 516                let extrasType = kObjectType;
 517                let extraKeys;
 518
 519                if (Symbol.iterator in value || constructor === null) {
 520                  noIterator = false;
 521                  if (Array.isArray(value)) {
 522                    const prefix = (constructor !== 'Array' || tag !== '') ? getPrefix(constructor, tag, 'Array', `(${value.length})`) : '';
 523                    keys = getOwnNonIndexProperties(value, ctx.showHidden);
 524                    braces = [`${prefix}[`, ']'];
 525                    if (value.length === 0 && keys.length === 0 && protoProps === undefined) return `${braces[0]}]`;
 526                    extrasType = kArrayExtrasType;
 527                    formatter = formatArray;
 528                  } else if (isSet(value)) {
 529                    const size = getter(Set.prototype, 'size').call(value);
 530                    const prefix = getPrefix(constructor, tag, 'Set', `(${size})`);
 531                    keys = getKeys(value, ctx.showHidden);
 532                    formatter = (ctx, v, recurseTimes) => formatSet(value, ctx, recurseTimes);
 533                    if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
 534                    braces = [`${prefix}{`, '}'];
 535                  } else if (isMap(value)) {
 536                    const size = getter(Map.prototype, 'size').call(value);
 537                    const prefix = getPrefix(constructor, tag, 'Map', `(${size})`);
 538                    keys = getKeys(value, ctx.showHidden);
 539                    formatter = (ctx, v, recurseTimes) => formatMap(value, ctx, recurseTimes);
 540                    if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
 541                    braces = [`${prefix}{`, '}'];
 542                  } else if (isTypedArray(value)) {
 543                    keys = getOwnNonIndexProperties(value, ctx.showHidden);
 544                    const fallback = constructor === null ? typedArrayTag.call(value) : '';
 545                    const size = getter(typedArrayProto, 'length').call(value);
 546                    const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
 547                    braces = [`${prefix}[`, ']'];
 548                    if (value.length === 0 && keys.length === 0 && !ctx.showHidden) return `${braces[0]}]`;
 549                    formatter = (ctx) => formatTypedArray(value, size, ctx);
 550                    extrasType = kArrayExtrasType;
 551                    if (ctx.showHidden) {
 552                      extraKeys = ['BYTES_PER_ELEMENT', 'length', 'byteLength', 'byteOffset', 'buffer'];
 553                      typedArray = true;
 554                    }
 555                  } else if (iteratorTags.includes(Object.prototype.toString.call(value))) {
 556                    refuse('util.inspect of an iterator');
 557                  } else {
 558                    noIterator = true;
 559                  }
 560                }
 561                if (noIterator) {
 562                  keys = getKeys(value, ctx.showHidden);
 563                  braces = ['{', '}'];
 564                  if (typeof value === 'function') {
 565                    base = getFunctionBase(ctx, value, constructor, tag);
 566                    if (keys.length === 0 && protoProps === undefined) return base;
 567                  } else if (constructor === 'Object') {
 568                    if (isArgumentsObject(value)) {
 569                      braces[0] = '[Arguments] {';
 570                    } else if (tag !== '') {
 571                      braces[0] = `${getPrefix(constructor, tag, 'Object')}{`;
 572                    }
 573                    if (keys.length === 0 && protoProps === undefined) return `${braces[0]}}`;
 574                  } else if (isRegExp(value)) {
 575                    base = RegExp.prototype.toString.call(constructor !== null ? value : new RegExp(value));
 576                    const prefix = getPrefix(constructor, tag, 'RegExp');
 577                    if (prefix !== 'RegExp ') base = `${prefix}${base}`;
 578                    if ((keys.length === 0 && protoProps === undefined) || (recurseTimes > ctx.depth && ctx.depth !== null)) return base;
 579                  } else if (isDate(value)) {
 580                    base = Number.isNaN(Date.prototype.getTime.call(value)) ? Date.prototype.toString.call(value) : Date.prototype.toISOString.call(value);
 581                    const prefix = getPrefix(constructor, tag, 'Date');
 582                    if (prefix !== 'Date ') base = `${prefix}${base}`;
 583                    if (keys.length === 0 && protoProps === undefined) return base;
 584                  } else if (isError(value)) {
 585                    refuse('util.inspect of an Error');
 586                  } else if (isArrayBuffer(value)) {
 587                    const prefix = getPrefix(constructor, tag, 'ArrayBuffer');
 588                    if (typedArray === undefined) {
 589                      formatter = formatArrayBuffer;
 590                    } else if (keys.length === 0 && protoProps === undefined) {
 591                      return prefix + `{ [byteLength]: ${formatNumber(value.byteLength, false)} }`;
 592                    }
 593                    braces[0] = `${prefix}{`;
 594                    extraKeys = ['byteLength'];
 595                  } else if (isDataView(value)) {
 596                    braces[0] = `${getPrefix(constructor, tag, 'DataView')}{`;
 597                    extraKeys = ['byteLength', 'byteOffset', 'buffer'];
 598                  } else if (isPromise(value)) {
 599                    refuse('util.inspect of a Promise');
 600                  } else if (isWeakSet(value) || isWeakMap(value)) {
 601                    if (ctx.showHidden) refuse('util.inspect of WeakMap or WeakSet entries');
 602                    braces[0] = `${getPrefix(constructor, tag, isWeakSet(value) ? 'WeakSet' : 'WeakMap')}{`;
 603                    formatter = () => ['<items unknown>'];
 604                  } else if (typeof value === 'object' && boxType(value)) {
 605                    base = getBoxedBase(value, ctx, keys, constructor, tag);
 606                    if (keys.length === 0 && protoProps === undefined) return base;
 607                  } else {
 608                    if (keys.length === 0 && protoProps === undefined) return `${getCtxStyle(value, constructor, tag)}{}`;
 609                    braces[0] = `${getCtxStyle(value, constructor, tag)}{`;
 610                  }
 611                }
 612
 613                if (recurseTimes > ctx.depth && ctx.depth !== null) {
 614                  let constructorName = getCtxStyle(value, constructor, tag).slice(0, -1);
 615                  if (constructor !== null) constructorName = `[${constructorName}]`;
 616                  return constructorName;
 617                }
 618                recurseTimes += 1;
 619                ctx.seen.push(value);
 620                ctx.currentDepth = recurseTimes;
 621                const output = formatter(ctx, value, recurseTimes);
 622                if (extraKeys !== undefined) {
 623                  for (const key of extraKeys) output.push(formatExtraProperties(ctx, value, recurseTimes, key, typedArray));
 624                }
 625                for (const key of keys) output.push(formatProperty(ctx, value, recurseTimes, key, extrasType));
 626                if (protoProps !== undefined) output.push(...protoProps);
 627                if (ctx.circular !== undefined) {
 628                  const index = ctx.circular.get(value);
 629                  if (index !== undefined) {
 630                    const reference = `<ref *${index}>`;
 631                    if (ctx.compact !== true) {
 632                      base = base === '' ? reference : `${reference} ${base}`;
 633                    } else {
 634                      braces[0] = `${reference} ${braces[0]}`;
 635                    }
 636                  }
 637                }
 638                ctx.seen.pop();
 639                if (ctx.sorted) {
 640                  const comparator = ctx.sorted === true ? undefined : ctx.sorted;
 641                  if (extrasType === kObjectType) {
 642                    output.sort(comparator);
 643                  } else if (keys.length > 1) {
 644                    const sorted = output.slice(output.length - keys.length).sort(comparator);
 645                    output.splice(output.length - keys.length, keys.length, ...sorted);
 646                  }
 647                }
 648                const res = reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value);
 649                const newLength = (ctx.budget[ctx.indentationLvl] || 0) + res.length;
 650                ctx.budget[ctx.indentationLvl] = newLength;
 651                if (newLength > 2 ** 27) ctx.depth = -1;
 652                return res;
 653              }
 654
 655              function getBoxedBase(value, ctx, keys, constructor, tag) {
 656                const [type, fn] = boxType(value);
 657                if (type === 'String') keys.splice(0, value.length);
 658                let base = `[${type}`;
 659                if (type !== constructor) base += constructor === null ? ' (null prototype)' : ` (${constructor})`;
 660                base += `: ${formatPrimitive(fn.call(value), ctx)}]`;
 661                if (tag !== '' && tag !== constructor) base += ` [${tag}]`;
 662                return base;
 663              }
 664
 665              function getClassBase(value, constructor, tag) {
 666                const hasName = Object.prototype.hasOwnProperty.call(value, 'name');
 667                const name = (hasName && value.name) || '(anonymous)';
 668                let base = `class ${name}`;
 669                if (constructor !== 'Function' && constructor !== null) base += ` [${constructor}]`;
 670                if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
 671                if (constructor !== null) {
 672                  const superName = Object.getPrototypeOf(value).name;
 673                  if (superName) base += ` extends ${superName}`;
 674                } else {
 675                  base += ' extends [null prototype]';
 676                }
 677                return `[${base}]`;
 678              }
 679
 680              function getFunctionBase(ctx, value, constructor, tag) {
 681                const stringified = Function.prototype.toString.call(value);
 682                if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') {
 683                  const slice = stringified.slice(5, -1);
 684                  const bracketIndex = slice.indexOf('{');
 685                  if (bracketIndex !== -1 && (!slice.slice(0, bracketIndex).includes('(') ||
 686                      classRegExp.exec(slice.replace(stripCommentsRegExp, '')) !== null)) {
 687                    return getClassBase(value, constructor, tag);
 688                  }
 689                }
 690                const proto = Object.getPrototypeOf(value);
 691                let type = 'Function';
 692                if (proto === generatorFunctionProto || proto === asyncGeneratorFunctionProto) type = `Generator${type}`;
 693                if (proto === asyncFunctionProto || proto === asyncGeneratorFunctionProto) type = `Async${type}`;
 694                let base = `[${type}`;
 695                if (constructor === null) base += ' (null prototype)';
 696                if (value.name === '') {
 697                  base += ' (anonymous)';
 698                } else {
 699                  base += `: ${typeof value.name === 'string' ? value.name : formatValue(ctx, value.name)}`;
 700                }
 701                base += ']';
 702                if (constructor !== type && constructor !== null) base += ` ${constructor}`;
 703                if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
 704                return base;
 705              }
 706
 707              function addQuotes(str, quotes) {
 708                if (quotes === -1) return `"${str}"`;
 709                if (quotes === -2) return `\`${str}\``;
 710                return `'${str}'`;
 711              }
 712
 713              function escapeFn(str) {
 714                const charCode = str.charCodeAt(0);
 715                return meta.length > charCode ? meta[charCode] : `\\u${charCode.toString(16)}`;
 716              }
 717
 718              function strEscape(str) {
 719                let escapeTest = strEscapeSequencesRegExp;
 720                let escapeReplace = strEscapeSequencesReplacer;
 721                let singleQuote = 39;
 722                if (str.includes("'")) {
 723                  if (!str.includes('"')) {
 724                    singleQuote = -1;
 725                  } else if (!str.includes('`') && !str.includes('${')) {
 726                    singleQuote = -2;
 727                  }
 728                  if (singleQuote !== 39) {
 729                    escapeTest = strEscapeSequencesRegExpSingle;
 730                    escapeReplace = strEscapeSequencesReplacerSingle;
 731                  }
 732                }
 733                if (str.length < 5000 && escapeTest.exec(str) === null) return addQuotes(str, singleQuote);
 734                if (str.length > 100) {
 735                  str = str.replace(escapeReplace, escapeFn);
 736                  return addQuotes(str, singleQuote);
 737                }
 738                let result = '';
 739                let last = 0;
 740                for (let i = 0; i < str.length; i++) {
 741                  const point = str.charCodeAt(i);
 742                  if (point === singleQuote || point === 92 || point < 32 || (point > 126 && point < 160)) {
 743                    result += last === i ? meta[point] : `${str.slice(last, i)}${meta[point]}`;
 744                    last = i + 1;
 745                  } else if (point >= 0xd800 && point <= 0xdfff) {
 746                    if (point <= 0xdbff && i + 1 < str.length) {
 747                      const next = str.charCodeAt(i + 1);
 748                      if (next >= 0xdc00 && next <= 0xdfff) {
 749                        i++;
 750                        continue;
 751                      }
 752                    }
 753                    result += `${str.slice(last, i)}\\u${point.toString(16)}`;
 754                    last = i + 1;
 755                  }
 756                }
 757                if (last !== str.length) result += str.slice(last);
 758                return addQuotes(result, singleQuote);
 759              }
 760
 761              function addNumericSeparator(integerString) {
 762                let result = '';
 763                let i = integerString.length;
 764                const start = integerString[0] === '-' ? 1 : 0;
 765                for (; i >= start + 4; i -= 3) result = `_${integerString.slice(i - 3, i)}${result}`;
 766                return i === integerString.length ? integerString : `${integerString.slice(0, i)}${result}`;
 767              }
 768
 769              function addNumericSeparatorEnd(integerString) {
 770                let result = '';
 771                let i = 0;
 772                for (; i < integerString.length - 3; i += 3) result += `${integerString.slice(i, i + 3)}_`;
 773                return i === 0 ? integerString : `${result}${integerString.slice(i)}`;
 774              }
 775
 776              const remainingText = (remaining) => `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
 777
 778              function formatNumber(number, numericSeparator) {
 779                if (Object.is(number, -0)) return '-0';
 780                if (!numericSeparator) return `${number}`;
 781                const numberString = String(number);
 782                const integer = Math.trunc(number);
 783                if (integer === number) {
 784                  if (!Number.isFinite(number) || numberString.includes('e')) return numberString;
 785                  return addNumericSeparator(numberString);
 786                }
 787                if (Number.isNaN(number) || numberString.includes('e')) return numberString;
 788                const decimalIndex = numberString.indexOf('.');
 789                return `${addNumericSeparator(numberString.slice(0, decimalIndex))}.${addNumericSeparatorEnd(numberString.slice(decimalIndex + 1))}`;
 790              }
 791
 792              function formatBigInt(bigint, numericSeparator) {
 793                const string = String(bigint);
 794                return numericSeparator ? `${addNumericSeparator(string)}n` : `${string}n`;
 795              }
 796
 797              function formatPrimitive(value, ctx) {
 798                if (typeof value === 'string') {
 799                  let trailer = '';
 800                  if (value.length > ctx.maxStringLength) {
 801                    const remaining = value.length - ctx.maxStringLength;
 802                    value = value.slice(0, ctx.maxStringLength);
 803                    trailer = `... ${remaining} more character${remaining > 1 ? 's' : ''}`;
 804                  }
 805                  if (ctx.compact !== true && value.length > kMinLineLength && value.length > ctx.breakLength - ctx.indentationLvl - 4) {
 806                    return value.split(/(?<=\n)/).map((line) => strEscape(line)).join(` +\n${' '.repeat(ctx.indentationLvl + 2)}`) + trailer;
 807                  }
 808                  return strEscape(value) + trailer;
 809                }
 810                if (typeof value === 'number') return formatNumber(value, ctx.numericSeparator);
 811                if (typeof value === 'bigint') return formatBigInt(value, ctx.numericSeparator);
 812                if (typeof value === 'boolean') return `${value}`;
 813                if (typeof value === 'undefined') return 'undefined';
 814                return Symbol.prototype.toString.call(value);
 815              }
 816
 817              function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) {
 818                const keys = Object.keys(value);
 819                let index = i;
 820                for (; i < keys.length && output.length < maxLength; i++) {
 821                  const key = keys[i];
 822                  const tmp = +key;
 823                  if (tmp > 2 ** 32 - 2) break;
 824                  if (`${index}` !== key) {
 825                    if (numberRegExp.exec(key) === null) break;
 826                    const emptyItems = tmp - index;
 827                    output.push(`<${emptyItems} empty item${emptyItems > 1 ? 's' : ''}>`);
 828                    index = tmp;
 829                    if (output.length === maxLength) break;
 830                  }
 831                  output.push(formatProperty(ctx, value, recurseTimes, key, kArrayType));
 832                  index++;
 833                }
 834                const remaining = value.length - index;
 835                if (output.length !== maxLength) {
 836                  if (remaining > 0) output.push(`<${remaining} empty item${remaining > 1 ? 's' : ''}>`);
 837                } else if (remaining > 0) {
 838                  output.push(remainingText(remaining));
 839                }
 840                return output;
 841              }
 842
 843              function formatArrayBuffer(ctx, value) {
 844                const buffer = new Uint8Array(value);
 845                const shown = Array.from(buffer.subarray(0, Math.min(ctx.maxArrayLength, buffer.length)), (b) => b.toString(16).padStart(2, '0'));
 846                let str = shown.join(' ');
 847                const remaining = buffer.length - ctx.maxArrayLength;
 848                if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
 849                return [`[Uint8Contents]: <${str}>`];
 850              }
 851
 852              function formatArray(ctx, value, recurseTimes) {
 853                const valLen = value.length;
 854                const len = Math.min(Math.max(0, ctx.maxArrayLength), valLen);
 855                const remaining = valLen - len;
 856                const output = [];
 857                for (let i = 0; i < len; i++) {
 858                  const desc = Object.getOwnPropertyDescriptor(value, i);
 859                  if (desc === undefined) return formatSpecialArray(ctx, value, recurseTimes, len, output, i);
 860                  output.push(formatProperty(ctx, value, recurseTimes, i, kArrayType, desc));
 861                }
 862                if (remaining > 0) output.push(remainingText(remaining));
 863                return output;
 864              }
 865
 866              function formatTypedArray(value, length, ctx) {
 867                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 868                const remaining = value.length - maxLength;
 869                const output = new Array(maxLength);
 870                const elementFormatter = value.length > 0 && typeof value[0] === 'number' ? formatNumber : formatBigInt;
 871                for (let i = 0; i < maxLength; ++i) output[i] = elementFormatter(value[i], ctx.numericSeparator);
 872                if (remaining > 0) output[maxLength] = remainingText(remaining);
 873                return output;
 874              }
 875
 876              function formatSet(value, ctx, recurseTimes) {
 877                const length = value.size;
 878                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 879                const remaining = length - maxLength;
 880                const output = [];
 881                ctx.indentationLvl += 2;
 882                let i = 0;
 883                for (const v of Set.prototype.values.call(value)) {
 884                  if (i >= maxLength) break;
 885                  output.push(formatValue(ctx, v, recurseTimes));
 886                  i++;
 887                }
 888                if (remaining > 0) output.push(remainingText(remaining));
 889                ctx.indentationLvl -= 2;
 890                return output;
 891              }
 892
 893              function formatMap(value, ctx, recurseTimes) {
 894                const length = value.size;
 895                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 896                const remaining = length - maxLength;
 897                const output = [];
 898                ctx.indentationLvl += 2;
 899                let i = 0;
 900                for (const { 0: k, 1: v } of Map.prototype.entries.call(value)) {
 901                  if (i >= maxLength) break;
 902                  output.push(`${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`);
 903                  i++;
 904                }
 905                if (remaining > 0) output.push(remainingText(remaining));
 906                ctx.indentationLvl -= 2;
 907                return output;
 908              }
 909
 910              function formatExtraProperties(ctx, value, recurseTimes, key, typedArray) {
 911                const extraValue = value[key];
 912                ctx.indentationLvl += 2;
 913                const str = formatValue(ctx, extraValue, recurseTimes, typedArray);
 914                ctx.indentationLvl -= 2;
 915                return `[${key}]: ${str}`;
 916              }
 917
 918              function formatProperty(ctx, value, recurseTimes, key, type, desc, original = value) {
 919                let name, str;
 920                let extra = ' ';
 921                desc ??= Object.getOwnPropertyDescriptor(value, key);
 922                if (desc.value !== undefined) {
 923                  const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3;
 924                  ctx.indentationLvl += diff;
 925                  str = formatValue(ctx, desc.value, recurseTimes);
 926                  if (diff === 3 && ctx.breakLength < getStringWidth(str)) extra = `\n${' '.repeat(ctx.indentationLvl)}`;
 927                  ctx.indentationLvl -= diff;
 928                } else if (desc.get !== undefined) {
 929                  const label = desc.set !== undefined ? 'Getter/Setter' : 'Getter';
 930                  if (ctx.getters && (ctx.getters === true || (ctx.getters === 'get' && desc.set === undefined) ||
 931                      (ctx.getters === 'set' && desc.set !== undefined))) {
 932                    ctx.indentationLvl += 2;
 933                    try {
 934                      const tmp = desc.get.call(original);
 935                      if (tmp === null) {
 936                        str = `[${label}: null]`;
 937                      } else if (typeof tmp === 'object' || typeof tmp === 'function') {
 938                        str = `[${label}] ${formatValue(ctx, tmp, recurseTimes)}`;
 939                      } else {
 940                        str = `[${label}: ${formatPrimitive(tmp, ctx)}]`;
 941                      }
 942                    } catch (err) {
 943                      str = `[${label}: <Inspection threw (${formatValue(ctx, err, recurseTimes)})>]`;
 944                    }
 945                    ctx.indentationLvl -= 2;
 946                  } else {
 947                    str = `[${label}]`;
 948                  }
 949                } else if (desc.set !== undefined) {
 950                  str = '[Setter]';
 951                } else {
 952                  str = 'undefined';
 953                }
 954                if (type === kArrayType) return str;
 955                if (typeof key === 'symbol') {
 956                  name = Symbol.prototype.toString.call(key).replace(strEscapeSequencesReplacer, escapeFn);
 957                } else if (keyStrRegExp.exec(key) !== null) {
 958                  name = key === '__proto__' ? "['__proto__']" : key;
 959                } else {
 960                  name = strEscape(key);
 961                }
 962                if (desc.enumerable === false) name = `[${name}]`;
 963                return `${name}:${extra}${str}`;
 964              }
 965
 966              function groupArrayElements(ctx, output, value) {
 967                let totalLength = 0;
 968                let maxLength = 0;
 969                let i = 0;
 970                let outputLength = output.length;
 971                if (ctx.maxArrayLength < output.length) outputLength--;
 972                const separatorSpace = 2;
 973                const dataLen = new Array(outputLength);
 974                for (; i < outputLength; i++) {
 975                  const len = getStringWidth(output[i]);
 976                  dataLen[i] = len;
 977                  totalLength += len + separatorSpace;
 978                  if (maxLength < len) maxLength = len;
 979                }
 980                const actualMax = maxLength + separatorSpace;
 981                if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength && (totalLength / actualMax > 5 || maxLength <= 6)) {
 982                  const approxCharHeights = 2.5;
 983                  const averageBias = Math.sqrt(actualMax - totalLength / output.length);
 984                  const biasedMax = Math.max(actualMax - 3 - averageBias, 1);
 985                  const columns = Math.min(
 986                    Math.round(Math.sqrt(approxCharHeights * biasedMax * outputLength) / biasedMax),
 987                    Math.floor((ctx.breakLength - ctx.indentationLvl) / actualMax),
 988                    ctx.compact * 4,
 989                    15,
 990                  );
 991                  if (columns <= 1) return output;
 992                  const tmp = [];
 993                  const maxLineLength = [];
 994                  for (let i = 0; i < columns; i++) {
 995                    let lineMaxLength = 0;
 996                    for (let j = i; j < output.length; j += columns) {
 997                      if (dataLen[j] > lineMaxLength) lineMaxLength = dataLen[j];
 998                    }
 999                    maxLineLength[i] = lineMaxLength + separatorSpace;
1000                  }
1001                  let padStart = true;
1002                  if (value !== undefined) {
1003                    for (let i = 0; i < output.length; i++) {
1004                      if (typeof value[i] !== 'number' && typeof value[i] !== 'bigint') {
1005                        padStart = false;
1006                        break;
1007                      }
1008                    }
1009                  }
1010                  for (let i = 0; i < outputLength; i += columns) {
1011                    const max = Math.min(i + columns, outputLength);
1012                    let str = '';
1013                    let j = i;
1014                    for (; j < max - 1; j++) {
1015                      const padding = maxLineLength[j - i] + output[j].length - dataLen[j];
1016                      str += padStart ? `${output[j]}, `.padStart(padding, ' ') : `${output[j]}, `.padEnd(padding, ' ');
1017                    }
1018                    if (padStart) {
1019                      str += output[j].padStart(maxLineLength[j - i] + output[j].length - dataLen[j] - separatorSpace, ' ');
1020                    } else {
1021                      str += output[j];
1022                    }
1023                    tmp.push(str);
1024                  }
1025                  if (ctx.maxArrayLength < output.length) tmp.push(output[outputLength]);
1026                  output = tmp;
1027                }
1028                return output;
1029              }
1030
1031              function isBelowBreakLength(ctx, output, start, base) {
1032                if (ctx.breakLength === Infinity) {
1033                  if (base !== '' && base.includes('\n')) return false;
1034                  return !output.some((entry) => typeof entry === 'string' && entry.includes('\n'));
1035                }
1036                let totalLength = output.length + start;
1037                if (totalLength + output.length > ctx.breakLength) return false;
1038                for (let i = 0; i < output.length; i++) {
1039                  totalLength += output[i].length;
1040                  if (totalLength > ctx.breakLength) return false;
1041                }
1042                return base === '' || !base.includes('\n');
1043              }
1044
1045              function reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value) {
1046                if (ctx.compact !== true) {
1047                  if (typeof ctx.compact === 'number' && ctx.compact >= 1) {
1048                    const entries = output.length;
1049                    if (extrasType === kArrayExtrasType && entries > 6) output = groupArrayElements(ctx, output, value);
1050                    if (ctx.currentDepth - recurseTimes < ctx.compact && entries === output.length) {
1051                      const start = output.length + ctx.indentationLvl + braces[0].length + base.length + 10;
1052                      if (isBelowBreakLength(ctx, output, start, base)) {
1053                        const joinedOutput = output.join(', ');
1054                        if (!joinedOutput.includes('\n')) return `${base ? `${base} ` : ''}${braces[0]} ${joinedOutput}` + ` ${braces[1]}`;
1055                      }
1056                    }
1057                  }
1058                  const indentation = `\n${' '.repeat(ctx.indentationLvl)}`;
1059                  return `${base ? `${base} ` : ''}${braces[0]}${indentation}  ${output.join(`,${indentation}  `)}${indentation}${braces[1]}`;
1060                }
1061                if (isBelowBreakLength(ctx, output, 0, base)) return `${braces[0]}${base ? ` ${base}` : ''} ${output.join(', ')} ` + braces[1];
1062                const indentation = ' '.repeat(ctx.indentationLvl);
1063                const ln = base === '' && braces[0].length === 1 ? ' ' : `${base ? ` ${base}` : ''}\n${indentation}  `;
1064                return `${braces[0]}${ln}${output.join(`,\n${indentation}  `)} ${braces[1]}`;
1065              }
1066
1067              function hasBuiltInToString(value) {
1068                let hasOwnToString = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1069                let hasOwnToPrimitive = hasOwnToString;
1070                if (typeof value.toString !== 'function') {
1071                  if (typeof value[Symbol.toPrimitive] !== 'function') return true;
1072                  if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) return false;
1073                  hasOwnToString = () => false;
1074                } else if (Object.prototype.hasOwnProperty.call(value, 'toString')) {
1075                  return false;
1076                } else if (typeof value[Symbol.toPrimitive] !== 'function') {
1077                  hasOwnToPrimitive = () => false;
1078                } else if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) {
1079                  return false;
1080                }
1081                let pointer = value;
1082                do {
1083                  pointer = Object.getPrototypeOf(pointer);
1084                } while (!hasOwnToString(pointer, 'toString') && !hasOwnToPrimitive(pointer, Symbol.toPrimitive));
1085                const descriptor = Object.getOwnPropertyDescriptor(pointer, 'constructor');
1086                return descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name);
1087              }
1088
1089              let circularErrorMessage;
1090              function tryStringify(arg) {
1091                try {
1092                  return JSON.stringify(arg);
1093                } catch (err) {
1094                  if (!circularErrorMessage) {
1095                    try {
1096                      const a = {};
1097                      a.a = a;
1098                      JSON.stringify(a);
1099                    } catch (circularError) {
1100                      circularErrorMessage = circularError.message.split('\n', 1)[0];
1101                    }
1102                  }
1103                  if (err.name === 'TypeError' && err.message.split('\n', 1)[0] === circularErrorMessage) return '[Circular]';
1104                  throw err;
1105                }
1106              }
1107
1108              function formatWithOptions(inspectOptions, args) {
1109                const first = args[0];
1110                let a = 0;
1111                let str = '';
1112                let join = '';
1113                if (typeof first === 'string') {
1114                  if (args.length === 1) return first;
1115                  let tempStr;
1116                  let lastPos = 0;
1117                  for (let i = 0; i < first.length - 1; i++) {
1118                    if (first.charCodeAt(i) === 37) {
1119                      const nextChar = first.charCodeAt(++i);
1120                      if (a + 1 !== args.length) {
1121                        switch (nextChar) {
1122                          case 115: {
1123                            const tempArg = args[++a];
1124                            if (typeof tempArg === 'number') {
1125                              tempStr = formatNumber(tempArg, inspectOptions?.numericSeparator);
1126                            } else if (typeof tempArg === 'bigint') {
1127                              tempStr = formatBigInt(tempArg, inspectOptions?.numericSeparator);
1128                            } else if (typeof tempArg !== 'object' || tempArg === null || !hasBuiltInToString(tempArg)) {
1129                              tempStr = String(tempArg);
1130                            } else {
1131                              tempStr = inspect(tempArg, { ...inspectOptions, compact: 3, colors: false, depth: 0 });
1132                            }
1133                            break;
1134                          }
1135                          case 106:
1136                            tempStr = tryStringify(args[++a]);
1137                            break;
1138                          case 100: {
1139                            const tempNum = args[++a];
1140                            if (typeof tempNum === 'bigint') tempStr = formatBigInt(tempNum, inspectOptions?.numericSeparator);
1141                            else if (typeof tempNum === 'symbol') tempStr = 'NaN';
1142                            else tempStr = formatNumber(Number(tempNum), inspectOptions?.numericSeparator);
1143                            break;
1144                          }
1145                          case 79:
1146                            tempStr = inspect(args[++a], inspectOptions);
1147                            break;
1148                          case 111:
1149                            tempStr = inspect(args[++a], { ...inspectOptions, showHidden: true, showProxy: true, depth: 4 });
1150                            break;
1151                          case 105: {
1152                            const tempInteger = args[++a];
1153                            if (typeof tempInteger === 'bigint') tempStr = formatBigInt(tempInteger, inspectOptions?.numericSeparator);
1154                            else if (typeof tempInteger === 'symbol') tempStr = 'NaN';
1155                            else tempStr = formatNumber(Number.parseInt(tempInteger), inspectOptions?.numericSeparator);
1156                            break;
1157                          }
1158                          case 102: {
1159                            const tempFloat = args[++a];
1160                            if (typeof tempFloat === 'symbol') tempStr = 'NaN';
1161                            else tempStr = formatNumber(Number.parseFloat(tempFloat), inspectOptions?.numericSeparator);
1162                            break;
1163                          }
1164                          case 99:
1165                            a += 1;
1166                            tempStr = '';
1167                            break;
1168                          case 37:
1169                            str += first.slice(lastPos, i);
1170                            lastPos = i + 1;
1171                            continue;
1172                          default:
1173                            continue;
1174                        }
1175                        if (lastPos !== i - 1) str += first.slice(lastPos, i - 1);
1176                        str += tempStr;
1177                        lastPos = i + 1;
1178                      } else if (nextChar === 37) {
1179                        str += first.slice(lastPos, i);
1180                        lastPos = i + 1;
1181                      }
1182                    }
1183                  }
1184                  if (lastPos !== 0) {
1185                    a++;
1186                    join = ' ';
1187                    if (lastPos < first.length) str += first.slice(lastPos);
1188                  }
1189                }
1190                while (a < args.length) {
1191                  const value = args[a];
1192                  str += join;
1193                  str += typeof value !== 'string' ? inspect(value, inspectOptions) : value;
1194                  join = ' ';
1195                  a++;
1196                }
1197                return str;
1198              }
1199
1200              // Node's globals, as far as they go without files, processes or the network.
1201              function stream(fd, name) {
1202                return guard({
1203                  write(chunk, ...rest) {
1204                    if (typeof chunk !== 'string' || rest.length !== 0) refuse(`${name}.write with anything but text`);
1205                    out(fd, chunk);
1206                    return true;
1207                  },
1208                }, name);
1209              }
1210              const process = guard({ stdout: stream(1, 'process.stdout'), stderr: stream(2, 'process.stderr') }, 'process');
1211              const util = guard({
1212                inspect,
1213                format: (...args) => formatWithOptions(undefined, args),
1214                formatWithOptions: (options, ...args) => formatWithOptions(options, args),
1215              }, 'util');
1216              const modules = { process, util };
1217              function require(id) {
1218                const name = typeof id === 'string' && id.startsWith('node:') ? id.slice(5) : id;
1219                if (Object.prototype.hasOwnProperty.call(modules, name)) return modules[name];
1220                const error = new Error(`Cannot find module '${id}'`);
1221                error.code = 'MODULE_NOT_FOUND';
1222                throw error;
1223              }
1224              const print = (fd) => (...args) => out(fd, formatWithOptions(undefined, args) + '\n');
1225              const console = guard({
1226                log: print(1), info: print(1), debug: print(1), warn: print(2), error: print(2),
1227                dir(object, options) { out(1, inspect(object, { customInspect: false, ...options }) + '\n'); },
1228              }, 'console');
1229
1230              // Timers run after the script, in order of when they are due, as Node's event loop runs them.
1231              class Timeout {
1232                constructor(timer) { this[timerKey] = timer; }
1233                ref() { this[timerKey].ref = true; return this; }
1234                unref() { this[timerKey].ref = false; return this; }
1235                hasRef() { return this[timerKey].ref; }
1236                [Symbol.toPrimitive]() { return this[timerKey].id; }
1237                [customInspectSymbol]() { refuse('util.inspect of a Timeout'); }
1238              }
1239              const timerKey = Symbol('timer');
1240              function schedule(callback, delay, args, repeat) {
1241                if (typeof callback !== 'function') {
1242                  const error = new TypeError(`The "callback" argument must be of type function. Received ${inspect(callback)}`);
1243                  error.code = 'ERR_INVALID_ARG_TYPE';
1244                  throw error;
1245                }
1246                delay *= 1;
1247                if (!(delay >= 1 && delay <= 2 ** 31 - 1)) delay = 1;
1248                const timer = { id: ++state.seq, seq: state.seq, due: state.now + delay, delay, callback, args, repeat, ref: true };
1249                timer.timeout = new Timeout(timer);
1250                state.timers.push(timer);
1251                return timer.timeout;
1252              }
1253              function clear(timeout) {
1254                const timer = timeout && typeof timeout === 'object' ? timeout[timerKey]
1255                  : state.timers.find((t) => t.id === Number(timeout));
1256                state.timers = state.timers.filter((t) => t !== timer);
1257              }
1258              function uncaught(error) {
1259                if (state.error === undefined) state.error = describe(error);
1260                state.dead = true;
1261              }
1262              function describe(error) {
1263                if (error instanceof Error) {
1264                  let message = String(error.message);
1265                  const missing = /^Can't find variable: (.*)$/.exec(message);
1266                  if (error.name === 'ReferenceError' && missing) message = `${missing[1]} is not defined`;
1267                  return message === '' ? String(error.name) : `${error.name}: ${message}`;
1268                }
1269                try { return `Uncaught ${inspect(error)}`; } catch { return 'Uncaught exception'; }
1270              }
1271
1272              const globals = {
1273                require, console, process, global: globalThis, Proxy: ProxyConstructor, module: { exports: {} }, __filename: '[stdin]', __dirname: '.',
1274                setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false),
1275                setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true),
1276                clearTimeout: clear, clearInterval: clear,
1277                queueMicrotask(callback) {
1278                  if (typeof callback !== 'function') throw new TypeError('The "callback" argument must be of type function.');
1279                  Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } });
1280                },
1281              };
1282              globals.exports = globals.module.exports;
1283              for (const [name, value] of Object.entries(globals)) {
1284                Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
1285              }
1286              for (const name of ['Buffer', 'setImmediate', 'clearImmediate', 'structuredClone', 'atob', 'btoa', 'performance', 'fetch',
1287                'crypto', 'navigator', 'URL', 'URLSearchParams', 'TextEncoder', 'TextDecoder', 'AbortController', 'AbortSignal',
1288                'Event', 'EventTarget', 'Blob', 'Headers', 'Request', 'Response', 'FormData', 'WebSocket', 'MessageChannel',
1289                'BroadcastChannel']) {
1290                if (!(name in globalThis)) {
1291                  Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true });
1292                }
1293              }
1294
1295              return {
1296                // A script run as `node` runs standard input; an uncaught error ends it.
1297                main(source) {
1298                  try { evaluate(source); } catch (error) { uncaught(error); }
1299                },
1300                begin() {
1301                  state.dead = false;
1302                  state.error = undefined;
1303                  state.refused = '';
1304                  state.now = Date.now();
1305                },
1306                // After a session's script: its error, or its value as the session writes it.
1307                failed(error) { uncaught(error); },
1308                inspect(value) { return inspect(value); },
1309                // Runs the next timer that is due: the milliseconds until one is, 0 after running one,
1310                // or -1 when none is left to wait for.
1311                tick() {
1312                  if (state.dead || !state.timers.some((t) => t.ref)) return -1;
1313                  state.now = Date.now();
1314                  const next = state.timers.reduce((a, b) => (b.due < a.due || (b.due === a.due && b.seq < a.seq) ? b : a));
1315                  if (next.due > state.now) return next.due - state.now;
1316                  if (next.repeat) {
1317                    next.due = state.now + next.delay;
1318                    next.seq = ++state.seq;
1319                  } else {
1320                    clear(next.timeout);
1321                  }
1322                  try { next.callback.apply(next.timeout, next.args); } catch (error) { uncaught(error); }
1323                  return 0;
1324                },
1325                get error() { return state.error; },
1326                get refused() { return state.refused; },
1327              };
1328            })
1329            """#
1330    }
1331}
1332#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form