Sources/OrgApp/JavaScriptBlocks.swift

586bad784d2cb2ad1bb43da0e63f0819913ed1dc
orgstar/Sources/OrgApp/JavaScriptBlocks.swift

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