@poe-platform/safe-js 0.1.728 → 0.1.729

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/dist/safe-js/chunks/{chunk-GZT57PW4.js → chunk-2S4YRXI6.js} +2 -2
  3. package/dist/safe-js/chunks/{chunk-EBNKJYZV.js → chunk-EA7AHM2X.js} +2 -2
  4. package/dist/safe-js/chunks/{chunk-EZEB4AIH.js → chunk-EN724VH3.js} +3 -3
  5. package/dist/safe-js/chunks/{chunk-4QDOJTAL.js → chunk-LRSWTDIV.js} +6 -5
  6. package/dist/safe-js/chunks/chunk-LRSWTDIV.js.map +7 -0
  7. package/dist/safe-js/chunks/{chunk-IZX26NC7.js → chunk-MRULOD5J.js} +2 -2
  8. package/dist/safe-js/chunks/{chunk-VW2VLHK2.js → chunk-MVLDRXWS.js} +2 -2
  9. package/dist/safe-js/chunks/{chunk-ZSIY6K54.js → chunk-S5YDMMM3.js} +64 -58
  10. package/dist/safe-js/chunks/{chunk-ZSIY6K54.js.map → chunk-S5YDMMM3.js.map} +3 -3
  11. package/dist/safe-js/chunks/{chunk-ZTKMQHXB.js → chunk-VIMROAQA.js} +2 -2
  12. package/dist/safe-js/chunks/{chunk-TFLQJ5NE.js → chunk-W3IY6FKO.js} +2 -2
  13. package/dist/safe-js/chunks/{chunk-RXESEKV6.js → chunk-XX57YCGZ.js} +6 -7
  14. package/dist/safe-js/chunks/chunk-XX57YCGZ.js.map +7 -0
  15. package/dist/safe-js/chunks/{cli-runtime-OZPDDD6M.js → cli-runtime-6VVBO2SS.js} +10 -10
  16. package/dist/safe-js/chunks/{dump-3TMEMH6D.js → dump-UNYK24YS.js} +3 -3
  17. package/dist/safe-js/chunks/{fs-YSBEA2WW.js → fs-AOV77RQC.js} +3 -3
  18. package/dist/safe-js/chunks/{harness-YC3FLN5N.js → harness-ZIEO7NAV.js} +3 -3
  19. package/dist/safe-js/chunks/{mcp-3GOG43VR.js → mcp-WBM7ZOAN.js} +3 -3
  20. package/dist/safe-js/chunks/{migration-file-IFKOIPNA.js → migration-file-3SWGNDS2.js} +4 -4
  21. package/dist/safe-js/chunks/{restore-ZOAQTM7X.js → restore-FCTWPLU3.js} +4 -4
  22. package/dist/safe-js/chunks/{run-XH62V323.js → run-ESJHEXCE.js} +6 -6
  23. package/dist/safe-js/chunks/{runtime-modules-BUR3QGOJ.js → runtime-modules-7V6BWCRK.js} +3 -3
  24. package/dist/safe-js/cli.js +2 -2
  25. package/dist/safe-js/core.js +5 -5
  26. package/dist/safe-js/index.js +11 -12
  27. package/dist/safe-js/index.js.map +2 -2
  28. package/package.json +3 -2
  29. package/dist/safe-js/chunks/chunk-4QDOJTAL.js.map +0 -7
  30. package/dist/safe-js/chunks/chunk-RXESEKV6.js.map +0 -7
  31. /package/dist/safe-js/chunks/{chunk-GZT57PW4.js.map → chunk-2S4YRXI6.js.map} +0 -0
  32. /package/dist/safe-js/chunks/{chunk-EBNKJYZV.js.map → chunk-EA7AHM2X.js.map} +0 -0
  33. /package/dist/safe-js/chunks/{chunk-EZEB4AIH.js.map → chunk-EN724VH3.js.map} +0 -0
  34. /package/dist/safe-js/chunks/{chunk-IZX26NC7.js.map → chunk-MRULOD5J.js.map} +0 -0
  35. /package/dist/safe-js/chunks/{chunk-VW2VLHK2.js.map → chunk-MVLDRXWS.js.map} +0 -0
  36. /package/dist/safe-js/chunks/{chunk-ZTKMQHXB.js.map → chunk-VIMROAQA.js.map} +0 -0
  37. /package/dist/safe-js/chunks/{chunk-TFLQJ5NE.js.map → chunk-W3IY6FKO.js.map} +0 -0
  38. /package/dist/safe-js/chunks/{cli-runtime-OZPDDD6M.js.map → cli-runtime-6VVBO2SS.js.map} +0 -0
  39. /package/dist/safe-js/chunks/{dump-3TMEMH6D.js.map → dump-UNYK24YS.js.map} +0 -0
  40. /package/dist/safe-js/chunks/{fs-YSBEA2WW.js.map → fs-AOV77RQC.js.map} +0 -0
  41. /package/dist/safe-js/chunks/{harness-YC3FLN5N.js.map → harness-ZIEO7NAV.js.map} +0 -0
  42. /package/dist/safe-js/chunks/{mcp-3GOG43VR.js.map → mcp-WBM7ZOAN.js.map} +0 -0
  43. /package/dist/safe-js/chunks/{migration-file-IFKOIPNA.js.map → migration-file-3SWGNDS2.js.map} +0 -0
  44. /package/dist/safe-js/chunks/{restore-ZOAQTM7X.js.map → restore-FCTWPLU3.js.map} +0 -0
  45. /package/dist/safe-js/chunks/{run-XH62V323.js.map → run-ESJHEXCE.js.map} +0 -0
  46. /package/dist/safe-js/chunks/{runtime-modules-BUR3QGOJ.js.map → runtime-modules-7V6BWCRK.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/realm.ts", "../../src/modules/source-graph.ts", "../../src/random.ts", "../../src/snapshot/backend.ts", "../../src/snapshot/scheduler.ts", "../../src/snapshot/serialize.ts", "../../src/snapshot/replay-inputs.ts", "../../src/run.ts"],
4
+ "sourcesContent": ["import { denyGuestStringCompilation } from \"./interp/string-compilation.js\";\nimport { arrayBufferDetached, arrayBufferLength, arrayBufferOptions, isSandboxArrayBuffer } from \"./interp/array-buffer.js\";\nimport {hashParsedAst} from \"./parse/hash.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { types } from \"node:util\";\nimport { guestProxyStates } from \"./interp/guest-proxy.js\";\nimport { callGuestProxy } from \"./interp/guest-proxy-call.js\";\nimport { sandboxGetProperty } from \"./interp/guest-proxy-get.js\";\nimport { invokeBuiltinClosure } from \"./interp/builtin-call.js\";\nimport { Budget, SandboxError } from \"./interp/budget.js\";\nimport { CompileScope } from \"./interp/regex/compile-guard.js\";\nimport { createBuiltinBindings } from \"./interp/globals.js\";\nimport { getRealmGlobalObject } from \"./interp/intrinsics.js\";\nimport { releaseObjectPrototype } from \"./interp/object-model.js\";\nimport { interpret, Scope, type InterpreterResult } from \"./interp/interpreter.js\";\nimport { attachExecutionControl, SandboxJobQueue, runAsyncPrefix, suspendJob, type ExecutionControl } from \"./interp/jobs.js\";\nimport { withCancellationSignal, awaitSandboxValue } from \"./interp/cancel.js\";\nimport { enterRunningState } from \"./interp/running-state.js\";\nimport { retainValues, runResources, type RunResources } from \"./interp/resources.js\";\nimport {\n createSandboxPromiseRejectionTracker,\n withSandboxPromiseRejectionTracker\n} from \"./interp/promise-tracker.js\";\nimport {\n copyHostValueToSandbox,\n wrapCallerInjectedBindings,\n type CallerInjectedBinding,\n type HostBridgeOptions,\n type RealmBridge\n} from \"./interp/host-bridge.js\";\nimport {\n createLiveHostObject,\n hostObjectGuestRoot,\n createGuestReference,\n exportHostCapability,\n readGuestReference,\n readGuestCallback,\n registerGuestCallback,\n revokeGuestCallback,\n revokeHostObject,\n revokeGuestReference,\n type GuestReference,\n type HostObjectDefinition,\n type HostObject\n} from \"./interp/host-capabilities.js\";\nimport {\n deepCopyFromSandbox,\n isSandboxClosure,\n isSandboxPromise,\n measureSandboxData,\n reconcileCompiledValues,\n type SandboxClosure,\n type SandboxCallContext,\n type SandboxValue\n} from \"./interp/values.js\";\nimport {\n getExtensionSetup,\n readDataRecord,\n readStringList,\n type CallbackOptions,\n type CallbackInvocation,\n type ExtensionContext,\n type ExtensionExports,\n type HostOperation,\n type SafeJSExtension\n} from \"./extensions.js\";\nimport {SourceModuleGraph, type SourceResolver} from \"./modules/source-graph.js\";\nimport { attachSourceLoader, createImmutableEmptyModuleEnvironment, createModuleEnvironment, resolveModuleImports, type ModuleRegistry } from \"./modules/registry.js\";\nimport { parseExecutableModule } from \"./parse/parser.js\";\nimport { createEvalSource } from \"./parse/dynamic-source.js\";\nimport { createReplayableRandom } from \"./random.js\";\nimport { hashSource } from \"./parse/hash.js\";\nimport { describeThrownValue } from \"./error/shape.js\";\nimport { encodeReplayData } from \"./snapshot/replay-data.js\";\nimport type { ConsoleSink } from \"./interp/globals/console-json.js\";\nimport type { RunClock, RunOptions, RunResult } from \"./run.js\";\n\nconst retainedArrayPrototype = Array.prototype;\nconst nativeRetainedArrayPrototype = Object.setPrototypeOf;\nconst nativeRetainedArrayAppend = Function.prototype.call.bind(Array.prototype.push) as (\n values: SandboxValue[],\n value: SandboxValue\n) => number;\n\nexport type RealmLimits = {\n extensions?: number;\n hostObjects?: number;\n callbacks?: number;\n guestReferences?: number;\n cleanups?: number;\n nestedEvaluations?: number;\n};\nexport type RealmOptions = {\n stringCompilation?: \"allow\" | \"deny\";\n classicScripts?: boolean;\n classicScriptErrors?: \"fatal\" | \"report\";\n callbackScheduling?: \"after-prefix\";\n sourceResolver?: SourceResolver;\n /** Elapsed host-time limit per dynamic import; expiry revokes the whole realm. */\n sourceImportTimeoutMs?: number;\n clock?: RunClock;\n bindings?: Record<string, CallerInjectedBinding>;\n modules?: ModuleRegistry;\n extensions?: readonly SafeJSExtension[];\n builtinOverrides?: { console?: string };\n grants?: readonly string[];\n budget?: Budget;\n signal?: AbortSignal;\n sink?: ConsoleSink;\n randomSeed?: number;\n limits?: RealmLimits;\n};\nexport type RealmResult =\n | (Omit<Extract<InterpreterResult, { ok: true }>, \"snapshot\" | \"returnValue\"> & {\n returnValue?: unknown;\n })\n | (Omit<Extract<InterpreterResult, { ok: false }>, \"snapshot\"> & { recoverable?: true });\nexport type SafeJSRealm = ExecutionControl & {\n readonly stringCompilation: \"allow\" | \"deny\";\n readonly classicScriptErrors: \"fatal\" | \"report\";\n readonly supportsDiscardResult: true;\n readonly sourceImportTimeoutMs?: number;\n readonly extensions: readonly SafeJSExtension[\"manifest\"][];\n evaluate(source: string, options?: { filename?: string; sourceType?: \"module\"; discardResult?: boolean }): Promise<RealmResult>;\n startCallback(callback: unknown, options?: CallbackOptions): CallbackInvocation;\n invokeCallback(callback: unknown, options?: CallbackOptions): Promise<unknown>;\n releaseCallback(callback: unknown): void;\n releaseGuestReference(reference: unknown): void;\n sourceModuleStatus(): ReturnType<SourceModuleGraph[\"sourceModuleStatus\"]>;\n close(): Promise<void>;\n};\n\ntype HostPhase = {\n active: boolean;\n extension?: SafeJSExtension;\n evaluating: boolean;\n pending: Set<Promise<void>>;\n failure?: { reason: unknown };\n};\ntype Callback = (...args: readonly unknown[]) => Promise<unknown>;\n\nconst freezeSourceReference = Object.freeze;\n\nclass RealmState {\n readonly budget: Budget;\n readonly lease: ReturnType<Budget[\"acquireCompileOwner\"]>;\n readonly compilation: CompileScope;\n readonly controller = new AbortController();\n readonly phase = new AsyncLocalStorage<HostPhase>();\n readonly queue: SandboxJobQueue;\n readonly tracker = createSandboxPromiseRejectionTracker();\n readonly bridge: RealmBridge;\n readonly limits: Required<RealmLimits>;\n readonly extensions: readonly SafeJSExtension[];\n readonly consoleExtension?: string;\n readonly cleanups: Array<() => void | Promise<void>> = [];\n readonly referenceReleases = new Set<() => void>();\n readonly resources: RunResources;\n readonly callbacks = new Map<Callback, SandboxClosure>();\n readonly pendingCallbacks = new Set<{ closure: SandboxClosure; prefixComplete: boolean; promise?: Promise<unknown> }>();\n readonly pendingWork = new Set<Promise<unknown>>();\n releaseReconciliation?: () => void;\n readonly callbackCache = new WeakMap<SandboxClosure, Callback>();\n readonly hostObjects = new Set<HostObject>();\n readonly guestReferences = new Map<GuestReference, [SandboxValue]>();\n readonly retainedOperations = new WeakMap<\n HostOperation,\n { from: number; extension: SafeJSExtension }\n >();\n readonly nestedOperations = new WeakMap<HostOperation, SafeJSExtension>();\n readonly callbackOperations = new WeakMap<HostOperation, SafeJSExtension>();\n readonly convertedModules = new Map<string, Record<string, SandboxValue>>();\n readonly nativeConversions = { seen: new WeakMap<object, SandboxValue>() };\n readonly modules: Record<string, Record<string, CallerInjectedBinding>>;\n readonly globals: Record<string, CallerInjectedBinding>;\n readonly builtinBindings: ReturnType<typeof createBuiltinBindings>;\n scope?: Scope;\n sourceGraph?: SourceModuleGraph;\n sourceModuleHash?: string;\n active?: Promise<unknown>;\n disposal?: Promise<void>;\n closed = false;\n initialized = false;\n nestedDepth = 0;\n failure?: { reason: unknown };\n\n constructor(readonly options: RealmOptions, queue = new SandboxJobQueue()) {\n if (options.classicScripts !== undefined && typeof options.classicScripts !== \"boolean\")\n throw new TypeError(\"Realm classicScripts must be a boolean.\");\n this.queue = queue;\n const limitInput = readDataRecord(options.limits ?? {}, \"Realm limits\");\n this.limits = {\n extensions: 32,\n hostObjects: 1024,\n callbacks: 1024,\n guestReferences: 1024,\n cleanups: 1024,\n nestedEvaluations: 16\n };\n for (const [name, value] of Object.entries(limitInput)) {\n if (!Object.hasOwn(this.limits, name) || !Number.isSafeInteger(value) || Number(value) < 1)\n throw new TypeError(\"Realm limits must be positive safe integers with supported names.\");\n this.limits[name as keyof RealmLimits] = Number(value);\n }\n if (\n options.extensions !== undefined &&\n (!Array.isArray(options.extensions) || types.isProxy(options.extensions))\n )\n throw new TypeError(\"Extensions must be a registration array.\");\n const registrations = options.extensions ?? [];\n const extensions: SafeJSExtension[] = [];\n if (registrations.length > this.limits.extensions)\n throw new RangeError(\"Realm extension limit exceeded.\");\n for (let index = 0; index < registrations.length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(registrations, String(index));\n if (descriptor === undefined || !(\"value\" in descriptor))\n throw new TypeError(\"Extension registrations require data properties, not accessors.\");\n extensions.push(descriptor.value);\n }\n if (Reflect.ownKeys(registrations).length !== extensions.length + 1)\n throw new TypeError(\"Extension registrations have unsupported fields.\");\n this.extensions = Object.freeze(extensions);\n if (this.extensions.length > this.limits.extensions)\n throw new RangeError(\"Realm extension limit exceeded.\");\n this.globals = readDataRecord(options.bindings ?? {}, \"Realm bindings\") as Record<\n string,\n CallerInjectedBinding\n >;\n if (options.classicScripts && [\"this\", \"globalThis\"].some(name => Object.hasOwn(this.globals, name)))\n throw new TypeError(\"Classic Script receiver bindings cannot be replaced.\");\n this.modules = readModules(options.modules);\n const grants = new Set(readStringList(options.grants ?? [], \"Realm grants\"));\n for (const extension of this.extensions) getExtensionSetup(extension);\n const overrides = readDataRecord(options.builtinOverrides === undefined ? {} : options.builtinOverrides, \"Builtin overrides\");\n for (const [name, extensionName] of Object.entries(overrides)) {\n if (name !== \"console\" || typeof extensionName !== \"string\" || extensionName.length === 0 || extensionName.length > 256)\n throw new TypeError(\"Builtin overrides only supports console with a nonempty extension name.\");\n if (!this.extensions.some(extension => extension.manifest.name === extensionName && extension.manifest.globals?.includes(name)))\n throw new TypeError(\"Console override requires a registered extension declaring console.\");\n this.consoleExtension = extensionName;\n }\n this.budget = options.budget ?? new Budget({ maxCallDepth: 1000 });\n this.lease = this.budget.acquireRealmOwner();\n this.compilation = new CompileScope(this.lease.owner);\n this.bridge = {\n owner: this,\n assertActive: this.assertOpen,\n wrapCallback: this.wrapCallback,\n captureArguments: this.captureArguments,\n invoke: this.invokeHost,\n awaitResult: (operation) => this.nestedOperations.has(operation)\n };\n this.resources = {\n signal: this.controller.signal,\n referenceReleases: this.referenceReleases,\n add: this.onCleanup,\n reportError: reason => this.poison(reason)\n };\n try {\n this.builtinBindings = createBuiltinBindings({\n budget: this.budget,\n compileOwner: this.lease.owner,\n sink: options.sink,\n clock: options.clock,\n random: createReplayableRandom({ seed: options.randomSeed }).next\n });\n const names = new Set<string>();\n const globals = new Set([\n ...Object.keys(this.builtinBindings).filter(name => name !== \"console\" || this.consoleExtension === undefined),\n ...Object.keys(this.globals)\n ]);\n const modules = new Map(\n Object.entries(this.modules).map(([name, exports]) => [name, new Set(Object.keys(exports))])\n );\n for (const extension of this.extensions) {\n const manifest = extension.manifest;\n if (options.classicScripts && manifest.globals?.some(name => name === \"this\" || name === \"globalThis\"))\n throw new TypeError(\"Classic Script receiver bindings cannot be replaced.\");\n if (names.has(manifest.name))\n throw new TypeError(`Duplicate extension '${manifest.name}'.`);\n names.add(manifest.name);\n for (const capability of manifest.capabilities ?? []) {\n if (!grants.has(capability))\n throw new TypeError(`Missing grant '${capability}' for extension '${manifest.name}'.`);\n }\n for (const name of manifest.globals ?? []) {\n if (name === \"console\" && this.consoleExtension !== undefined && manifest.name !== this.consoleExtension)\n throw new TypeError(`Conflicting global 'console': replacement is authorized only for '${this.consoleExtension}'.`);\n if (globals.has(name)) throw new TypeError(`Conflicting global '${name}'.`);\n globals.add(name);\n }\n for (const [name, exports] of Object.entries(manifest.modules ?? {})) {\n const occupied = modules.get(name) ?? new Set<string>();\n for (const key of exports) {\n if (occupied.has(key)) throw new TypeError(`Conflicting export '${name}.${key}'.`);\n occupied.add(key);\n }\n modules.set(name, occupied);\n }\n }\n this.controller.signal.addEventListener(\"abort\", () => this.queue.interrupt(this.controller.signal.reason), { once: true });\n options.signal?.addEventListener(\"abort\", this.abort, { once: true });\n if (options.signal?.aborted) this.abort();\n this.budget.setRetainedValues(this, this.retainedRoots);\n this.tracker.onFatalRejection((error) => this.poison(error));\n } catch (error) {\n releaseObjectPrototype(this.budget);\n this.compilation.dispose();\n this.lease.release();\n throw error;\n }\n }\n\n bridgeOptions = (): HostBridgeOptions => ({\n budget: this.budget,\n compileOwner: this.lease.owner,\n signal: this.controller.signal,\n realm: this.bridge\n });\n\n retainedRoots = (): SandboxValue[] => {\n // Capture the complete ordered snapshot before accounting visits callbacks.\n // Pinned own-slot writes avoid later Array hooks and inherited index setters.\n const roots: SandboxValue[] = nativeRetainedArrayPrototype([], null);\n for (const object of this.hostObjects) {\n const root = hostObjectGuestRoot(object);\n if (root !== undefined) nativeRetainedArrayAppend(roots, root);\n }\n for (const closure of this.callbacks.values()) nativeRetainedArrayAppend(roots, closure);\n for (const pending of this.pendingCallbacks) nativeRetainedArrayAppend(roots, pending.closure);\n for (const reference of this.guestReferences.values()) nativeRetainedArrayAppend(roots, reference);\n return nativeRetainedArrayPrototype(roots, retainedArrayPrototype);\n };\n\n captureArguments: RealmBridge[\"captureArguments\"] = (operation, args, copy) => {\n const from = this.retainedOperations.get(operation)?.from ?? args.length;\n const owned = this.callbackOperations.has(operation) ? new Map<SandboxClosure, Callback>() : undefined;\n const captured: GuestReference[] = [];\n const rollback = () => {\n for (const reference of captured) {\n revokeGuestReference(reference, this);\n this.guestReferences.delete(reference);\n }\n for (const callback of owned?.values() ?? []) {\n revokeGuestCallback(callback, this);\n this.callbacks.delete(callback);\n }\n };\n try {\n // One copy preserves aliases within this call. Separate calls receive\n // separate revocation handles, even when they capture the same closure.\n const values = copy(args.slice(0, from), owned === undefined ? undefined : closure => {\n let callback = owned.get(closure);\n if (callback === undefined) {\n callback = this.wrapCallback(closure, true);\n owned.set(closure, callback);\n }\n return callback;\n });\n for (const value of args.slice(from)) {\n this.checkCollection(\n this.guestReferences.size + 1,\n this.limits.guestReferences,\n \"guest reference\"\n );\n const root: [SandboxValue] = [value];\n const reference = createGuestReference(root, this, this.assertOpen);\n this.guestReferences.set(reference, root);\n captured.push(reference);\n values.push(reference);\n }\n if (captured.length > 0)\n this.budget.reconcileDataUsage(\n measureSandboxData([...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots(), ...this.budget.retainedValues()])\n );\n return { args: values, rollback };\n } catch (error) {\n rollback();\n if (error instanceof SandboxError) this.poison(error);\n throw error;\n }\n };\n\n createArrayBufferReference = (buffer: ArrayBuffer): GuestReference => {\n this.assertOpen();\n if (\n !isSandboxArrayBuffer(buffer) ||\n arrayBufferDetached(buffer) ||\n arrayBufferOptions(buffer) !== undefined ||\n Reflect.ownKeys(buffer).length !== 0\n )\n throw new TypeError(\n \"Live buffer references require a fixed, attached, plain ArrayBuffer without metadata.\",\n );\n let reference: GuestReference | undefined;\n try {\n this.budget.allocateArrayLength(arrayBufferLength(buffer));\n this.checkCollection(\n this.guestReferences.size + 1,\n this.limits.guestReferences,\n \"guest reference\",\n );\n const root: [SandboxValue] = [buffer];\n reference = createGuestReference(root, this, this.assertOpen);\n this.guestReferences.set(reference, root);\n this.budget.reconcileDataUsage(\n measureSandboxData([\n ...(this.scope?.retainedDataRoots() ?? []),\n ...this.retainedRoots(),\n ...this.budget.retainedValues(),\n ]),\n );\n return reference;\n } catch (error) {\n if (reference !== undefined) {\n revokeGuestReference(reference, this);\n this.guestReferences.delete(reference);\n }\n if (error instanceof SandboxError) this.poison(error);\n throw error;\n }\n };\n\n releaseGuestReference = (reference: unknown): void => {\n readGuestReference(reference, this);\n revokeGuestReference(reference as GuestReference, this);\n this.guestReferences.delete(reference as GuestReference);\n if (this.active === undefined)\n reconcileCompiledValues(\n this.budget,\n [...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots()],\n this.compilation\n );\n };\n\n assertOpen = (): void => {\n if (this.failure !== undefined) throw this.failure.reason;\n if (this.closed) throw new Error(\"SafeJS realm is closed; capabilities are revoked.\");\n this.controller.signal.throwIfAborted();\n };\n\n abort = (): void => {\n this.poison(this.options.signal?.reason ?? new SandboxError(\"aborted\"));\n void this.close().catch(() => undefined);\n };\n\n poison(reason: unknown): void {\n this.failure ??= { reason };\n this.controller.abort(reason);\n if (this.active === undefined)\n queueMicrotask(() => {\n void this.dispose().catch(() => undefined);\n });\n }\n\n trackWork<Result>(pending: Promise<Result>): Promise<Result> {\n this.pendingWork.add(pending);\n void pending.then(\n () => { this.pendingWork.delete(pending); },\n () => { this.pendingWork.delete(pending); }\n );\n return pending;\n }\n\n reconcileWhenIdle(): void {\n if (this.closed || this.active !== undefined || this.pendingCallbacks.size > 0) return;\n this.releaseReconciliation?.();\n this.releaseReconciliation = undefined;\n try {\n reconcileCompiledValues(\n this.budget,\n [...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots()],\n this.compilation\n );\n } catch (error) {\n this.poison(error);\n void this.dispose().catch(() => undefined);\n throw error;\n }\n }\n\n chargeWork = (units = 1): void => {\n this.assertOpen();\n if (!Number.isSafeInteger(units) || units < 0)\n throw new TypeError(\"Work charges must be non-negative safe integers.\");\n try {\n for (let index = 0; index < units; index++) this.budget.visitNode();\n } catch (error) {\n this.poison(error);\n throw error;\n }\n };\n\n onCleanup = (cleanup: () => void | Promise<void>): (() => void) => {\n this.assertOpen();\n if (typeof cleanup !== \"function\") throw new TypeError(\"Cleanup must be a function.\");\n this.checkCollection(this.cleanups.length + 1, this.limits.cleanups, \"cleanup\");\n // Each registration has its own identity even when callbacks are reused.\n const registration = () => cleanup();\n this.cleanups.push(registration);\n return () => {\n const index = this.cleanups.indexOf(registration);\n if (index !== -1) this.cleanups.splice(index,1);\n };\n };\n\n checkCollection(count: number, limit: number, name: string): void {\n this.assertOpen();\n try {\n this.budget.allocateCollectionEntries(count);\n } catch (error) {\n this.poison(error);\n throw error;\n }\n if (count > limit) throw new RangeError(`Realm ${name} limit exceeded.`);\n }\n\n invokeHost = (operation: HostOperation, call: () => unknown): unknown => {\n this.assertOpen();\n const phase: HostPhase = {\n active: true,\n extension: this.nestedOperations.get(operation),\n evaluating: false,\n pending: new Set()\n };\n return this.phase.run(phase, () => {\n try {\n const result = call();\n if (types.isPromise(result) || phase.pending.size > 0 || phase.failure !== undefined) {\n return Promise.resolve(result)\n .then(\n async (value) => {\n await Promise.allSettled(phase.pending);\n if (phase.failure !== undefined) throw phase.failure.reason;\n this.assertOpen();\n return value;\n },\n async (error) => {\n if (error instanceof SandboxError || phase.pending.size > 0) this.poison(error);\n await Promise.allSettled(phase.pending);\n throw error;\n }\n )\n .finally(() => {\n phase.active = false;\n });\n }\n this.assertOpen();\n phase.active = false;\n return result;\n } catch (error) {\n phase.active = false;\n if (error instanceof SandboxError) this.poison(error);\n if (phase.pending.size > 0) {\n this.poison(error);\n return Promise.allSettled(phase.pending).then(() => {\n throw error;\n });\n }\n throw error;\n }\n });\n };\n\n importValue(value: unknown): SandboxValue {\n return copyHostValueToSandbox(\n value,\n [],\n this.bridgeOptions(),\n { seen: new WeakMap() },\n \"<realm>\"\n );\n }\n\n exportValue(value: SandboxValue): unknown {\n return deepCopyFromSandbox(value, {\n compilation: this.compilation,\n wrapClosure: this.wrapCallback,\n unwrapHostObject: (object) => exportHostCapability(object, this)\n });\n }\n\n createHostObject = (definition: HostObjectDefinition): HostObject => {\n this.checkCollection(this.hostObjects.size + 1, this.limits.hostObjects, \"host object\");\n const object = createLiveHostObject(definition, {\n owner: this,\n assertActive: this.assertOpen,\n chargeWork: this.chargeWork,\n chargeGuestData: (units) => this.budget.chargeDataUsage(units),\n checkLength: (length) => this.budget.allocateArrayLength(length),\n checkString: (value) => { this.budget.allocateString(value); },\n checkTemporaryDataSize: (size) => {\n const temporary = {};\n try {\n this.budget.setRetainedDataUsage(temporary, size);\n } finally {\n this.budget.setRetainedDataUsage(temporary, 0);\n }\n },\n read: (operation, validate) => {\n const value = this.invokeHost(operation, operation);\n if (types.isPromise(value)) {\n void Promise.resolve(value).catch(() => undefined);\n throw new TypeError(\"Live property operations must be synchronous.\");\n }\n return this.importValue(validate === undefined ? value : validate(value));\n },\n write: (operation, value) => {\n const result = this.invokeHost(operation, () => operation(this.exportValue(value)));\n if (types.isPromise(result)) {\n void Promise.resolve(result).catch(() => undefined);\n throw new TypeError(\"Live property setters must be synchronous.\");\n }\n },\n method: (operation) => {\n const value = copyHostValueToSandbox(\n operation,\n [],\n this.bridgeOptions(),\n this.nativeConversions,\n \"<host-method>\"\n );\n if (!isSandboxClosure(value)) throw new TypeError(\"Invalid host method.\");\n return value;\n }\n });\n this.hostObjects.add(object);\n try {\n this.budget.chargeDataUsage(1);\n } catch (error) {\n this.poison(error);\n throw error;\n }\n return object;\n };\n\n wrapCallback = (closure: SandboxClosure, owned = false): Callback => {\n this.assertOpen();\n const existing = owned ? undefined : this.callbackCache.get(closure);\n if (existing !== undefined && this.callbacks.has(existing)) return existing;\n this.checkCollection(this.callbacks.size + 1, this.limits.callbacks, \"callback\");\n const invokeCallback = this.invokeCallback;\n const callback = function (this: unknown, ...args: readonly unknown[]) {\n return invokeCallback(callback, { args, thisValue: this });\n };\n this.callbacks.set(callback, closure);\n if (!owned) this.callbackCache.set(closure, callback);\n registerGuestCallback(callback, {\n owner: this,\n closure,\n assertActive: () => {\n this.assertOpen();\n if (!this.callbacks.has(callback)) throw new TypeError(\"Guest callback is revoked.\");\n }\n });\n try {\n this.budget.reconcileDataUsage(\n measureSandboxData([...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots(), ...this.budget.retainedValues()])\n );\n } catch (error) {\n this.poison(error);\n throw error;\n }\n return callback;\n };\n\n releaseCallback = (callback: unknown): void => {\n readGuestCallback(callback, this);\n revokeGuestCallback(callback as object, this);\n this.callbacks.delete(callback as Callback);\n if (this.active === undefined)\n reconcileCompiledValues(\n this.budget,\n [...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots()],\n this.compilation\n );\n };\n\n startCallback = (callback: unknown, options: CallbackOptions = {}): CallbackInvocation => {\n let complete!: () => void;\n let fail!: (reason: unknown) => void;\n const synchronous = new Promise<void>((resolve, reject) => {\n complete = resolve;\n fail = reject;\n });\n const result = this.executeCallback(callback, options, complete);\n void result.catch(fail);\n void synchronous.catch(() => undefined);\n return Object.freeze({ synchronous, result });\n };\n\n invokeCallback = this.executeCallback.bind(this);\n\n private async executeCallback(\n callback: unknown,\n options: CallbackOptions = {},\n completeSynchronous?: () => void\n ): Promise<unknown> {\n if ((this.closed || this.failure !== undefined) && this.options.callbackScheduling !== \"after-prefix\")\n await this.dispose();\n this.assertOpen();\n const closure = readGuestCallback(callback, this);\n this.checkCollection(this.pendingCallbacks.size + 1, this.limits.callbacks, \"pending callback\");\n const scheduled = this.options.callbackScheduling === \"after-prefix\";\n const record: { closure: SandboxClosure; prefixComplete: boolean; promise?: Promise<unknown> } = {\n closure, prefixComplete: false\n };\n this.pendingCallbacks.add(record);\n if (scheduled) this.releaseReconciliation ??= this.budget.deferReconciliation();\n const rejectionOwner = scheduled ? this.tracker.startOperation() : undefined;\n const invoke = async () => {\n this.assertOpen();\n readGuestCallback(callback, this);\n const leave = enterRunningState(closure);\n const leaveCall = this.budget.enterCall();\n try {\n const values = this.importValue([\n options.thisValue,\n [...(options.args ?? [])]\n ]) as SandboxValue[];\n const callerContext: SandboxCallContext = {\n thisValue: values[0],\n compilation: this.compilation,\n stack: [],\n getProperty: (object, key) => sandboxGetProperty(object, key, object, this.budget, bridge)\n };\n const bridge: SandboxCallContext = {\n ...callerContext,\n invokeClosure: (target, args, receiver, construct, newTarget) =>\n invokeBuiltinClosure(target, args, this.budget, callerContext, receiver, construct, newTarget)\n };\n const value = await (guestProxyStates.has(closure)\n ? callGuestProxy(closure, values[1] as SandboxValue[], this.budget, bridge, values[0])\n : closure.call(values[1] as SandboxValue[], {\n thisValue: values[0], compilation: this.compilation, stack: []\n }));\n const settlement = awaitSandboxValue(value, this.controller.signal, this.budget);\n void settlement.catch(() => undefined);\n if (isSandboxPromise(value) && value.synchronousPrefix !== undefined)\n await value.synchronousPrefix;\n this.assertOpen();\n record.prefixComplete = true;\n completeSynchronous?.();\n const settled = await suspendJob(settlement);\n return this.exportValue(settled);\n } finally {\n leaveCall();\n leave();\n }\n };\n try {\n const active = this.active !== undefined || (scheduled && this.phase.getStore()?.active === true);\n const execute = () => this.tracker.withOperation(rejectionOwner, () =>\n withSandboxPromiseRejectionTracker(this.tracker, () =>\n runResources.run(this.resources, () =>\n withCancellationSignal(this.controller.signal, () =>\n active && this.phase.getStore()?.active\n ? runAsyncPrefix(invoke, completeSynchronous === undefined && this.phase.getStore()?.extension !== undefined)\n : this.queue.run(invoke)\n )\n )\n )\n );\n const pending = scheduled && this.sourceGraph !== undefined\n ? this.sourceGraph.withoutImportGroup(execute) : execute();\n record.promise = scheduled ? this.trackWork(pending) : active ? pending : this.perform(() => pending);\n const result = await record.promise;\n if (scheduled) {\n await this.checkUnhandledRejection(rejectionOwner);\n this.assertOpen();\n }\n return result;\n } catch (error) {\n if (scheduled || error instanceof SandboxError) this.poison(error);\n if (scheduled) void this.dispose().catch(() => undefined);\n throw error;\n } finally {\n this.tracker.finishOperation(rejectionOwner);\n this.pendingCallbacks.delete(record);\n if (scheduled) this.reconcileWhenIdle();\n else if (!this.closed && this.active === undefined)\n reconcileCompiledValues(\n this.budget,\n [...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots()],\n this.compilation\n );\n }\n }\n\n initialize(): void {\n if (this.initialized) return;\n this.assertOpen();\n this.initialized = true;\n for (const extension of this.extensions) {\n const context: ExtensionContext = Object.freeze({\n signal: this.controller.signal,\n // Detachment is internal, not an extension capability.\n onCleanup: cleanup => { this.onCleanup(cleanup); },\n chargeWork: this.chargeWork,\n createHostObject: this.createHostObject,\n createArrayBufferReference: buffer => {\n this.assertOpen();\n if (!extension.manifest.capabilities?.includes(\"array-buffer:share\"))\n throw new TypeError(\"Live buffers require the array-buffer:share grant.\");\n return this.createArrayBufferReference(buffer);\n },\n startCallback: this.startCallback,\n invokeCallback: this.invokeCallback,\n releaseCallback: this.releaseCallback,\n releaseGuestReference: this.releaseGuestReference,\n retainCallbackArguments: <Operation extends HostOperation>(operation: Operation): Operation => {\n this.assertOpen();\n if (!extension.manifest.capabilities?.includes(\"guest:retain\"))\n throw new TypeError(\"Retaining callbacks requires the guest:retain grant.\");\n if (typeof operation !== \"function\")\n throw new TypeError(\"Retained callback operation must be a function.\");\n if (this.scope !== undefined)\n throw new TypeError(\"Retained callback operations must be registered during setup.\");\n const owner = this.callbackOperations.get(operation);\n if (owner !== undefined && owner !== extension)\n throw new TypeError(\"Retained callback operation already belongs to another extension.\");\n this.callbackOperations.set(operation, extension);\n return operation;\n },\n retainGuestArguments: <Operation extends HostOperation>(\n operation: Operation,\n from: number\n ): Operation => {\n this.assertOpen();\n if (!extension.manifest.capabilities?.includes(\"guest:retain\"))\n throw new TypeError(\"Retaining arguments requires the guest:retain grant.\");\n if (typeof operation !== \"function\")\n throw new TypeError(\"Retained operation must be a function.\");\n if (!Number.isSafeInteger(from) || from < 0)\n throw new TypeError(\"Argument index must be a non-negative safe integer.\");\n if (this.scope !== undefined)\n throw new TypeError(\"Retained operations must be registered during setup.\");\n const previous = this.retainedOperations.get(operation);\n if (\n previous !== undefined &&\n (previous.extension !== extension || previous.from !== from)\n )\n throw new TypeError(\"Conflicting retained operation declaration.\");\n this.retainedOperations.set(operation, { extension, from });\n return operation;\n },\n nestedOperation: <Operation extends HostOperation>(operation: Operation): Operation => {\n this.assertOpen();\n if (!extension.manifest.capabilities?.includes(\"source:nested\"))\n throw new TypeError(\"Nested source requires the source:nested grant.\");\n if (typeof operation !== \"function\")\n throw new TypeError(\"Nested operation must be a function.\");\n if (this.scope !== undefined)\n throw new TypeError(\"Nested operations must be registered during setup.\");\n const owner = this.nestedOperations.get(operation);\n if (owner !== undefined && owner !== extension)\n throw new TypeError(\"Nested operation already belongs to another extension.\");\n this.nestedOperations.set(operation, extension);\n return operation;\n },\n evaluateNested: (source) => {\n const phase = this.phase.getStore();\n if (\n !extension.manifest.capabilities?.includes(\"source:nested\") ||\n !phase?.active ||\n phase.extension !== extension ||\n phase.evaluating\n ) {\n const error = new SandboxError(\"reentry\");\n this.poison(error);\n const rejected = Promise.reject<void>(error);\n void rejected.catch(() => undefined);\n return rejected;\n }\n const pending = this.evaluateNested(source, extension);\n phase.pending.add(pending);\n void pending.then(\n () => {\n phase.pending.delete(pending);\n },\n (reason) => {\n phase.pending.delete(pending);\n phase.failure ??= { reason };\n }\n );\n return pending;\n }\n });\n const output = getExtensionSetup(extension)(context);\n if (types.isPromise(output)) {\n void Promise.resolve(output).catch(() => undefined);\n throw new TypeError(\"Extension setup must be synchronous.\");\n }\n const exports = readDataRecord(output, \"Extension exports\");\n if (Object.keys(exports).some((key) => key !== \"globals\" && key !== \"modules\"))\n throw new TypeError(\"Unknown extension export field.\");\n const globals = readDataRecord(\n exports.globals ?? {},\n \"Extension globals\"\n ) as ExtensionExports[\"globals\"] & {};\n const modules = readModules(exports.modules as ModuleRegistry | undefined);\n assertNames(Object.keys(globals), extension.manifest.globals ?? [], \"global\");\n if (extension.manifest.name === this.consoleExtension && !this.hostObjects.has(globals.console as HostObject))\n throw new TypeError(\"Console replacement must be a host object created in this realm.\");\n assertNames(Object.keys(modules), Object.keys(extension.manifest.modules ?? {}), \"module\");\n for (const [name, values] of Object.entries(modules)) {\n assertNames(Object.keys(values), extension.manifest.modules?.[name] ?? [], \"module export\");\n this.modules[name] ??= Object.create(null) as Record<string, CallerInjectedBinding>;\n Object.assign(this.modules[name], values);\n }\n Object.assign(this.globals, globals);\n }\n const bindings = wrapCallerInjectedBindings(this.globals, this.bridgeOptions());\n this.scope = new Scope(this.builtinBindings, undefined, undefined, { chargeData: false }).child(\n bindings,\n this.options.classicScripts ? { globalEnvironment: true } : { functionBoundary: true }\n );\n if (this.options.classicScripts)\n this.scope.declare(\"this\", \"const\", getRealmGlobalObject(this.budget));\n if (this.options.stringCompilation === \"deny\") denyGuestStringCompilation(this.scope);\n }\n\n sourceModuleStatus = (): ReturnType<SourceModuleGraph[\"sourceModuleStatus\"]> => {\n this.assertOpen();\n return this.sourceGraph?.sourceModuleStatus() ?? Object.freeze({\n pendingImports: 0,\n preparedModules: 0,\n fulfilledImports: 0,\n rejectedImports: 0\n });\n };\n\n private ensureSourceGraph(): SourceModuleGraph {\n this.assertOpen();\n this.initialize();\n if (this.sourceGraph !== undefined) return this.sourceGraph;\n const moduleOptions = {...this.bridgeOptions(), wrappedModules: this.convertedModules};\n const modules = Object.keys(this.modules).length === 0 && this.convertedModules.size === 0\n ? createImmutableEmptyModuleEnvironment(moduleOptions)\n : createModuleEnvironment(this.modules, moduleOptions);\n return (this.sourceGraph ??= new SourceModuleGraph({\n resolver: this.options.sourceResolver ?? (() => undefined),\n scope: this.scope!,\n modules,\n budget: this.budget,\n compilation: this.compilation,\n signal: this.controller.signal,\n jobs: this.queue,\n assertActive: this.assertOpen,\n surfaceUnhandledThrows: true,\n serializePreparation: this.options.callbackScheduling === \"after-prefix\",\n ...(this.options.sourceImportTimeoutMs === undefined\n ? {}\n : {\n importDeadline: {\n timeoutMs: this.options.sourceImportTimeoutMs,\n abort: (reason: unknown) => {\n this.poison(reason);\n void this.close().catch(() => undefined);\n }\n }\n })\n }));\n }\n\n async evaluateRaw(\n source: string,\n filename = \"<realm>\",\n nested = false,\n sourceType?: \"module\",\n reportUnhandledThrows = false\n ): Promise<InterpreterResult> {\n this.assertOpen();\n if (typeof source !== \"string\") throw new TypeError(\"Realm source must be a string.\");\n if (sourceType === \"module\") {\n const prepare = () => {\n this.ensureSourceGraph();\n };\n const scheduled = this.options.callbackScheduling === \"after-prefix\";\n if (scheduled) await this.queue.run(prepare);\n else prepare();\n const graph = this.sourceGraph!;\n const before = graph.stats.nodeVisits;\n const evaluate = async () => {\n const namespace = await graph.evaluateSource({id:filename,source}, module => {\n this.sourceModuleHash = hashParsedAst(module);\n });\n if (!scheduled) await graph.settle();\n return namespace;\n };\n const namespace = scheduled ? await graph.withImportGroup(evaluate) : await evaluate();\n return {ok:true,returnValue:namespace,snapshot:{bindings:{}},stats:{nodeVisits:graph.stats.nodeVisits - before,currentDataSize:this.budget.currentDataSize,peakDataSize:this.budget.peakDataSize}};\n }\n const script = this.options.classicScripts ? createEvalSource(source, {}, this.lease.owner, filename, {compactAst: true}) : undefined;\n // Each Script owns a charged identity that survives through its saved closures.\n const sourceReference = script && this.options.sourceResolver !== undefined\n ? freezeSourceReference({ referrer: filename }) : undefined;\n const releaseSource = script ? retainValues(this.budget, () => [script.source, sourceReference]) : undefined;\n try {\n if (script) this.budget.chargeDataUsage(measureSandboxData([script.source]));\n if (sourceReference) this.budget.chargeDataUsage(measureSandboxData([sourceReference]));\n const module = script?.node ?? parseExecutableModule(source, filename, this.lease.owner);\n this.initialize();\n const moduleOptions = {...this.bridgeOptions(), wrappedModules: this.convertedModules};\n const moduleEnvironment = script && Object.keys(this.modules).length === 0 && this.convertedModules.size === 0\n ? createImmutableEmptyModuleEnvironment(moduleOptions)\n : createModuleEnvironment(this.modules, moduleOptions);\n if (sourceReference)\n attachSourceLoader(moduleEnvironment,\n (specifier, referrer) => this.ensureSourceGraph().import(specifier, referrer),\n { preserveImmutableNamespaces: true });\n const imports = script ? {} : resolveModuleImports(module, this.modules, {\n environment: moduleEnvironment,\n ...this.bridgeOptions(),\n wrappedModules: this.convertedModules\n });\n this.scope!.moduleEnvironment = moduleEnvironment;\n for (const [name, value] of Object.entries(imports)) {\n const binding = this.scope!.lookup(name);\n if (!binding.found) this.scope!.declare(name, \"const\", value);\n else if (binding.value !== value) throw new TypeError(`Conflicting import '${name}'.`);\n }\n const result = await interpret(\n {\n type: \"BlockStatement\",\n body: module.body.filter((statement) => statement.type !== \"ImportDeclaration\"),\n span: module.span\n },\n {\n ...(script ? { script: { strict: script.strict } } : {}),\n sourceReference,\n scope: this.scope,\n useScopeDirectly: true,\n budget: this.budget,\n compilation: this.compilation,\n signal: this.controller.signal,\n surfaceUnhandledThrows: true,\n reportUnhandledThrows: script !== undefined && reportUnhandledThrows,\n jobs: this.queue,\n nested,\n assertActive: this.assertOpen\n }\n );\n this.assertOpen();\n return result;\n } finally {\n releaseSource?.();\n }\n }\n\n evaluateNested = async (source: string, extension: SafeJSExtension): Promise<void> => {\n this.assertOpen();\n const phase = this.phase.getStore();\n if (\n !phase?.active ||\n phase.extension !== extension ||\n phase.evaluating ||\n (this.active === undefined && !(this.options.callbackScheduling === \"after-prefix\" && this.pendingCallbacks.size > 0))\n )\n throw new SandboxError(\"reentry\");\n const leave = this.budget.enterCall();\n phase.evaluating = true;\n try {\n if (++this.nestedDepth > this.limits.nestedEvaluations) {\n const error = new SandboxError({\n budget: \"callDepth\",\n current: this.nestedDepth,\n limit: this.limits.nestedEvaluations\n });\n this.poison(error);\n throw error;\n }\n const result = await this.evaluateRaw(source, \"<nested>\", true);\n if (!result.ok) throw new Error(result.error.message);\n } finally {\n this.nestedDepth--;\n phase.evaluating = false;\n leave();\n }\n };\n\n evaluate = async (source: string, options: { filename?: string; sourceType?: \"module\"; discardResult?: boolean } = {}): Promise<RealmResult> =>\n this.perform<RealmResult>(async () => {\n const discard = Object.getOwnPropertyDescriptor(options, \"discardResult\");\n if (discard && (!(\"value\" in discard) || (discard.value !== undefined && typeof discard.value !== \"boolean\")))\n throw new TypeError(\"Realm evaluation discardResult must be an own-data boolean.\");\n const scheduled = this.options.callbackScheduling === \"after-prefix\";\n const reportUnhandledThrows = options.sourceType !== \"module\" && this.options.classicScriptErrors === \"report\";\n const result = scheduled && options.sourceType !== \"module\"\n ? await this.queue.run(() => this.evaluateRaw(source, options.filename, true, undefined, reportUnhandledThrows))\n : await this.evaluateRaw(source, options.filename, false, options.sourceType, reportUnhandledThrows);\n if (!result.ok) {\n const recoverable = reportUnhandledThrows && result.error.code === \"UNCAUGHT_EXCEPTION\";\n if (!scheduled && !recoverable) await this.dispose();\n return { ok: false, error: result.error, stats: result.stats, ...(recoverable ? { recoverable: true } : {}) };\n }\n return { ok: true, ...(discard?.value === true ? {} : { returnValue: this.exportValue(result.returnValue) }), stats: result.stats };\n }, result => !result.ok && !result.recoverable);\n\n async checkUnhandledRejection(owner?: object): Promise<void> {\n const unhandled = await this.tracker.findUnhandledRejection(owner);\n if (unhandled !== undefined) {\n const error = new Error(\n `Unhandled guest promise rejection: ${describeThrownValue(unhandled.reason)}`\n );\n error.name = \"UnhandledRejectionError\";\n throw error;\n }\n }\n\n async perform<Result>(task: () => Promise<Result>, failed?: (result: Result) => boolean): Promise<Result> {\n if ((this.closed || this.failure !== undefined) && this.options.callbackScheduling !== \"after-prefix\")\n await this.dispose();\n this.assertOpen();\n if (this.active !== undefined) throw new SandboxError(\"reentry\");\n const scheduled = this.options.callbackScheduling === \"after-prefix\";\n if (scheduled && (this.phase.getStore()?.active || [...this.pendingCallbacks].some(record => !record.prefixComplete)))\n throw new SandboxError(\"reentry\");\n const rejectionOwner = scheduled ? this.tracker.startOperation() : undefined;\n const pending = Promise.resolve().then(() =>\n this.tracker.withOperation(rejectionOwner, () =>\n withSandboxPromiseRejectionTracker(this.tracker, () =>\n runResources.run(this.resources, () =>\n withCancellationSignal(this.controller.signal, task)\n )\n )\n )\n );\n this.active = pending;\n if (scheduled) this.trackWork(pending);\n try {\n const result = await pending;\n if (scheduled && failed?.(result)) {\n this.closed = true;\n this.controller.abort(new Error(\"SafeJS source evaluation failed.\"));\n await this.dispose();\n return result;\n }\n if (scheduled) this.assertOpen();\n await this.queue.drain();\n await this.checkUnhandledRejection(rejectionOwner);\n if (this.failure !== undefined) throw this.failure.reason;\n if (scheduled) this.assertOpen();\n if (!this.closed)\n reconcileCompiledValues(\n this.budget,\n [...(this.scope?.retainedDataRoots() ?? []), ...this.retainedRoots()],\n this.compilation\n );\n return result;\n } catch (error) {\n const reason = this.failure === undefined ? error : this.failure.reason;\n this.poison(reason);\n try {\n await this.dispose();\n } catch (cleanup) {\n throw new AggregateError([reason, cleanup], \"Realm execution and cleanup failed.\");\n }\n throw reason;\n } finally {\n this.tracker.finishOperation(rejectionOwner);\n if (this.active === pending) this.active = undefined;\n if (scheduled) this.reconcileWhenIdle();\n }\n }\n\n close = (): Promise<void> => {\n this.closed = true;\n this.controller.abort(new Error(\"SafeJS realm is closed.\"));\n if (this.options.callbackScheduling === \"after-prefix\") {\n const disposal = this.dispose();\n if (this.phase.getStore()?.active) {\n void disposal.catch(() => undefined);\n return Promise.reject(new SandboxError(\"reentry\"));\n }\n return disposal;\n }\n if (this.phase.getStore()?.active) return this.dispose();\n return Promise.allSettled([\n this.active,\n ...Array.from(this.pendingCallbacks, (pending) => pending.promise)\n ]).then(() => this.dispose());\n };\n\n dispose(): Promise<void> {\n if (this.disposal !== undefined) return this.disposal;\n this.closed = true;\n this.controller.abort(new Error(\"SafeJS realm is closed.\"));\n this.options.signal?.removeEventListener(\"abort\", this.abort);\n if (this.options.callbackScheduling === \"after-prefix\") {\n this.disposal = Promise.resolve().then(async () => {\n while (this.pendingWork.size > 0) await Promise.allSettled([...this.pendingWork]);\n await this.sourceGraph?.settle();\n await this.queue.settle();\n this.releaseReconciliation?.();\n this.releaseReconciliation = undefined;\n await this.releaseResources();\n }).finally(() => this.queue.finish());\n return this.disposal;\n }\n this.disposal = this.releaseResources().finally(() => this.queue.finish());\n return this.disposal;\n }\n\n async releaseResources(): Promise<void> {\n for (const callback of this.callbacks.keys()) revokeGuestCallback(callback, this);\n this.callbacks.clear();\n for (const object of this.hostObjects) revokeHostObject(object, this);\n this.hostObjects.clear();\n for (const reference of this.guestReferences.keys()) revokeGuestReference(reference, this);\n this.guestReferences.clear();\n for (const release of this.referenceReleases) release();\n this.referenceReleases.clear();\n this.budget.setRetainedValues(this, undefined);\n this.sourceGraph?.close();\n releaseObjectPrototype(this.budget);\n const errors: unknown[] = [];\n for (const cleanup of this.cleanups.splice(0).reverse()) {\n try {\n await cleanup();\n } catch (error) {\n errors.push(error);\n }\n }\n this.scope = undefined;\n this.convertedModules.clear();\n for (const key of Object.keys(this.globals)) delete this.globals[key];\n for (const key of Object.keys(this.modules)) delete this.modules[key];\n for (const key of Object.keys(this.builtinBindings))\n Reflect.deleteProperty(this.builtinBindings, key);\n this.nativeConversions.seen = new WeakMap();\n reconcileCompiledValues(this.budget, [], this.compilation);\n this.compilation.dispose();\n this.lease.release();\n if (errors.length > 0) throw new AggregateError(errors, \"Realm cleanup failed.\");\n }\n}\n\nfunction readModules(\n input: ModuleRegistry | undefined\n): Record<string, Record<string, CallerInjectedBinding>> {\n const entries = (value: unknown, label: string): Array<[string, unknown]> => {\n if (types.isMap(value) && !types.isProxy(value)) {\n const result = [...Map.prototype.entries.call(value)] as Array<[string, unknown]>;\n if (\n result.length > 4096 ||\n result.some(([key]) => typeof key !== \"string\" || key.length === 0)\n )\n throw new TypeError(`${label} requires bounded string keys.`);\n return result;\n }\n return Object.entries(readDataRecord(value, label));\n };\n const modules = Object.create(null) as Record<string, Record<string, CallerInjectedBinding>>;\n for (const [name, exports] of entries(input ?? {}, \"Module registry\")) {\n const exported = Object.create(null) as Record<string, CallerInjectedBinding>;\n for (const [key, value] of entries(exports, \"Module exports\"))\n exported[key] = value as CallerInjectedBinding;\n modules[name] = exported;\n }\n return modules;\n}\n\nfunction assertNames(actual: readonly string[], expected: readonly string[], label: string): void {\n if (actual.length !== expected.length || actual.some((name) => !expected.includes(name)))\n throw new TypeError(`Extension ${label} names do not match its manifest.`);\n}\n\nexport function createRealm(options: RealmOptions = {}): SafeJSRealm {\n const state = new RealmState(readRealmOptions(options));\n return Object.freeze(attachExecutionControl({\n stringCompilation: state.options.stringCompilation ?? \"allow\",\n classicScriptErrors: state.options.classicScriptErrors ?? \"fatal\",\n supportsDiscardResult: true as const,\n sourceImportTimeoutMs: state.options.sourceImportTimeoutMs,\n extensions: Object.freeze(state.extensions.map((extension) => extension.manifest)),\n evaluate: state.evaluate,\n startCallback: state.startCallback,\n invokeCallback: state.invokeCallback,\n releaseCallback: state.releaseCallback,\n releaseGuestReference: state.releaseGuestReference,\n sourceModuleStatus: state.sourceModuleStatus,\n close: state.close\n }, state.queue));\n}\n\nexport async function runWithExtensions(source: string, options: RunOptions, jobs?: SandboxJobQueue): Promise<RunResult> {\n if (\n options.snapshot !== undefined ||\n options.snapshotBackend !== undefined ||\n options.snapshotPath !== undefined ||\n options.entryPointArgs !== undefined\n )\n throw new TypeError(\n \"Live extension runs do not support snapshots or entryPointArgs; use a persistent realm.\"\n );\n const state = new RealmState(readRealmOptions(options, true), jobs);\n if (options.sourceLocation !== undefined) state.resources.sourceLocation = options.sourceLocation;\n try {\n const result = await state.perform(() => state.evaluateRaw(source, options.filename, false, options.sourceType));\n if (result.ok && options.sourceType !== \"module\") encodeReplayData(result.returnValue);\n return {\n ...result,\n snapshot: {\n version: 1,\n sourceHash: state.sourceModuleHash ?? hashSource(source),\n bindings: {},\n replayError: \"Live realm state cannot be serialized or replayed.\"\n }\n };\n } catch (error) {\n if (state.disposal === undefined) {\n try {\n await state.close();\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], \"Realm execution and cleanup failed.\");\n }\n }\n throw error;\n } finally {\n if (state.disposal === undefined) await state.close();\n }\n}\n\nfunction readRealmOptions(value: unknown, oneShot = false): RealmOptions {\n const options = readDataRecord(value, \"Realm options\");\n const supported = new Set([\n \"bindings\",\n \"modules\",\n \"sourceResolver\",\n \"extensions\",\n \"builtinOverrides\",\n \"grants\",\n \"budget\",\n \"signal\",\n \"sink\",\n \"randomSeed\",\n \"clock\",\n \"limits\"\n ]);\n if (!oneShot) supported.add(\"stringCompilation\");\n if (!oneShot) supported.add(\"classicScripts\");\n if (!oneShot) supported.add(\"classicScriptErrors\");\n if (!oneShot) supported.add(\"callbackScheduling\");\n if (!oneShot) supported.add(\"sourceImportTimeoutMs\");\n for (const [key, entry] of Object.entries(options)) {\n if (supported.has(key) || (oneShot && (key === \"filename\" || key === \"sourceType\" || key === \"sourceLocation\" || entry === undefined))) continue;\n throw new TypeError(`Unsupported ${oneShot ? \"extension-run\" : \"realm\"} option '${key}'.`);\n }\n if (options.callbackScheduling !== undefined && options.callbackScheduling !== \"after-prefix\")\n throw new TypeError(\"Realm callbackScheduling must be 'after-prefix'.\");\n if (\n options.sourceImportTimeoutMs !== undefined &&\n (!Number.isSafeInteger(options.sourceImportTimeoutMs) ||\n Number(options.sourceImportTimeoutMs) < 1 ||\n Number(options.sourceImportTimeoutMs) > 2147483647)\n )\n throw new TypeError(\"Realm sourceImportTimeoutMs must be an integer between 1 and 2147483647.\");\n if (options.stringCompilation !== undefined && options.stringCompilation !== \"allow\" && options.stringCompilation !== \"deny\")\n throw new TypeError(\"Realm stringCompilation must be 'allow' or 'deny'.\");\n if (options.classicScriptErrors !== undefined && options.classicScriptErrors !== \"fatal\" && options.classicScriptErrors !== \"report\")\n throw new TypeError(\"Realm classicScriptErrors must be 'fatal' or 'report'.\");\n if (options.classicScriptErrors === \"report\" && options.classicScripts !== true)\n throw new TypeError(\"Reporting classic Script errors requires classicScripts:true.\");\n return options as RealmOptions;\n}\n", "import {parseSourceModule, type ParsedSourceModule, type SourceExport, type SourceImport} from \"../parse/source-module.js\";\nimport {AsyncLocalStorage} from \"node:async_hooks\";\nimport type { Module } from \"../parse/parser.js\";\nimport {interpret, type InterpretOptions} from \"../interp/interpreter.js\";\nimport {Scope} from \"../interp/scope.js\";\nimport {createModuleNamespace} from \"../interp/module-namespace.js\";\nimport {setSandboxPrototype} from \"../interp/object-model.js\";\nimport type {SandboxObject} from \"../interp/values.js\";\nimport {awaitWithSignal} from \"../interp/cancel.js\";\nimport {SandboxJobQueue} from \"../interp/jobs.js\";\nimport {SandboxError} from \"../interp/budget.js\";\nimport {attachSourceLoader, resolveModuleNamespace, type ModuleEnvironment} from \"./registry.js\";\n\nexport type SourceModule = {id: string; source: string};\nexport type SourceResolver = (specifier: string, referrer: string, context: {signal?: AbortSignal}) =>\n SourceModule | undefined | Promise<SourceModule | undefined>;\n\ntype RecordEntry = {\n id: string;\n source: string;\n parsed: ParsedSourceModule;\n explicitExports: Map<string, SourceExport>;\n localImports: Map<string, SourceImport>;\n starExports: SourceExport[];\n scope: Scope;\n dependencies: Map<string, RecordEntry | SandboxObject>;\n namespace?: SandboxObject;\n linked?: Promise<void>;\n evaluation?: Promise<void>;\n traversal?: Promise<void>;\n async?: boolean;\n completed?: boolean;\n failure?: {reason: unknown};\n dfsIndex?: number;\n dfsAncestor?: number;\n onStack?: boolean;\n cycleRoot?: RecordEntry;\n};\ntype Binding = {record: RecordEntry; name: string} | {namespace: SandboxObject; name: string; whole?: true};\nconst ambiguous = Symbol(\"ambiguous module export\");\nconst sourceRecords = new WeakSet<object>();\n\n/** Owns one realm's canonical source identities. The resolver is the only source authority. */\nexport class SourceModuleGraph {\n readonly stats = {nodeVisits:0};\n private readonly records = new Map<string, RecordEntry>();\n private readonly requests = new Map<string, Promise<RecordEntry | SandboxObject>>();\n private requestDataSize = 0;\n private lookupDataSize = 0;\n private readonly pendingImports = new Set<Promise<SandboxObject>>();\n private fulfilledImports = 0;\n private rejectedImports = 0;\n private readonly importGroup = new AsyncLocalStorage<Set<Promise<SandboxObject>>>();\n private readonly jobs: SandboxJobQueue;\n private readonly evaluationStack: RecordEntry[] = [];\n private evaluationIndex = 0;\n\n constructor(private readonly options: InterpretOptions & {\n scope: Scope;\n resolver: SourceResolver;\n modules: ModuleEnvironment;\n serializePreparation?: boolean;\n importDeadline?: {timeoutMs: number; abort(reason: unknown): void};\n }) {\n this.jobs = options.jobs ?? new SandboxJobQueue();\n attachSourceLoader(options.modules, this.import.bind(this), { preserveImmutableNamespaces: true });\n options.budget?.setRetainedValues(this, () => [...this.records.values()].flatMap(record =>\n [record.id,record.source,...record.parsed.requests,...record.scope.retainedDataRoots()]));\n }\n\n close(): void {\n this.options.budget?.setRetainedValues(this,undefined);\n this.options.budget?.setRetainedDataUsage(this.requests,0);\n for (const record of this.records.values()) {\n record.explicitExports.clear();\n record.localImports.clear();\n record.starExports.length = 0;\n }\n this.options.budget?.setRetainedDataUsage(this.records,0);\n this.lookupDataSize = 0;\n this.requestDataSize = 0;\n this.records.clear();\n this.requests.clear();\n }\n\n sourceModuleStatus() {\n return Object.freeze({\n pendingImports: this.pendingImports.size,\n preparedModules: this.records.size,\n fulfilledImports: this.fulfilledImports,\n rejectedImports: this.rejectedImports,\n });\n }\n\n import(specifier: string, referrer: string): Promise<SandboxObject> {\n const group = this.importGroup.getStore();\n const cancelDeadline = this.startImportDeadline();\n const pending=(async () => {\n const entry = await this.load(specifier, referrer);\n if (!isRecord(entry)) return entry;\n await this.loadGraph(entry);\n if (this.options.serializePreparation) await this.jobs.run(() => this.link(entry));\n else await this.link(entry);\n await this.evaluate(entry);\n await this.jobs.drain();\n return this.namespace(entry);\n })();\n this.pendingImports.add(pending);\n group?.add(pending);\n const release = () => {\n cancelDeadline();\n this.pendingImports.delete(pending);\n group?.delete(pending);\n };\n void pending.then(\n () => {this.fulfilledImports++; release();},\n () => {this.rejectedImports++; release();}\n );\n return pending;\n }\n\n private startImportDeadline(): () => void {\n const policy = this.options.importDeadline;\n const signal = this.options.signal;\n if (policy === undefined || signal?.aborted) return () => {};\n const deadline = Date.now() + policy.timeoutMs;\n let expired = false;\n const expire = (reason: SandboxError) => {\n if (expired) return;\n expired = true;\n cancel();\n policy.abort(reason);\n };\n const releaseDeadline = this.options.budget?.acquireDeadline(deadline, expire);\n const timer = setTimeout(() => {\n expire(new SandboxError({\n budget: \"deadline\",\n current: Date.now(),\n limit: deadline\n }));\n }, policy.timeoutMs);\n const cancel = () => {\n clearTimeout(timer);\n releaseDeadline?.();\n signal?.removeEventListener(\"abort\", cancel);\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return cancel;\n }\n\n withoutImportGroup<Result>(task: () => Result): Result {\n return this.importGroup.exit(task);\n }\n\n withImportGroup<Result>(task: () => Promise<Result>): Promise<Result> {\n const group = new Set<Promise<SandboxObject>>();\n return this.importGroup.run(group, async () => {\n const result = await task();\n await this.settle(group);\n return result;\n });\n }\n\n async settle(pendingImports = this.pendingImports): Promise<void> {\n do {\n await Promise.allSettled([...pendingImports]);\n await this.jobs.drain();\n } while (pendingImports.size > 0);\n }\n\n async evaluateSource(source: SourceModule, beforeEvaluation?: (module: Module) => void): Promise<SandboxObject> {\n const entry = this.options.serializePreparation\n ? await this.jobs.run(() => this.register(source)) : this.register(source);\n await this.loadGraph(entry);\n if (this.options.serializePreparation) await this.jobs.run(() => this.link(entry));\n else await this.link(entry);\n beforeEvaluation?.(entry.parsed.module);\n await this.evaluate(entry);\n await this.jobs.drain();\n return this.namespace(entry);\n }\n\n private register(source: SourceModule): RecordEntry {\n this.options.assertActive?.();\n this.options.signal?.throwIfAborted();\n const known = this.records.get(source.id);\n if (known !== undefined) {\n if (known.source !== source.source) throw new TypeError(`Source identity '${source.id}' changed within the graph.`);\n return known;\n }\n this.options.budget?.chargeDataUsage(source.source.length + source.id.length + 1);\n const parsed = parseSourceModule(source.source, source.id, this.options.compilation?.owner ?? this.options.compileOwner, { sharedPositions: true, compactAst: true });\n const explicitExports = new Map<string, SourceExport>();\n const localImports = new Map<string, SourceImport>();\n const starExports: SourceExport[] = [];\n for (const entry of parsed.exports) {\n this.options.budget?.visitNode();\n if (entry.exported === undefined) {\n const lookupDataSize = this.lookupDataSize + 1;\n this.options.budget?.setRetainedDataUsage(this.records, lookupDataSize);\n this.lookupDataSize = lookupDataSize;\n starExports.push(entry);\n } else if (!explicitExports.has(entry.exported)) {\n const lookupDataSize = this.lookupDataSize + entry.exported.length + 2;\n this.options.budget?.setRetainedDataUsage(this.records, lookupDataSize);\n this.lookupDataSize = lookupDataSize;\n explicitExports.set(entry.exported, entry);\n }\n }\n for (const entry of parsed.imports) {\n this.options.budget?.visitNode();\n if (!localImports.has(entry.local)) {\n const lookupDataSize = this.lookupDataSize + entry.local.length + 2;\n this.options.budget?.setRetainedDataUsage(this.records, lookupDataSize);\n this.lookupDataSize = lookupDataSize;\n localImports.set(entry.local, entry);\n }\n }\n const importMeta = Object.create(null) as SandboxObject;\n setSandboxPrototype(importMeta,null);\n const record: RecordEntry = {id:source.id, source:source.source, parsed, explicitExports, localImports, starExports,\n scope: new Scope({this:undefined},this.options.scope,importMeta, {functionBoundary:true}), dependencies:new Map()};\n record.scope.moduleEnvironment = this.options.modules;\n record.scope.moduleId = record.id;\n sourceRecords.add(record);\n this.records.set(source.id,record);\n return record;\n }\n\n private load(specifier: string, referrer: string): Promise<RecordEntry | SandboxObject> {\n if (this.options.modules.available.includes(specifier))\n return Promise.resolve(resolveModuleNamespace(this.options.modules, specifier));\n const key = JSON.stringify([referrer, specifier]);\n const cached = this.requests.get(key);\n if (cached !== undefined) return cached;\n // Both successful aliases and denied requests are cached for this realm's\n // lifetime. Reserve their identities before calling the host resolver.\n const requestDataSize = this.requestDataSize + key.length + 1;\n this.options.budget?.setRetainedDataUsage(this.requests,requestDataSize);\n this.requestDataSize = requestDataSize;\n const request = (async () => {\n this.options.signal?.throwIfAborted();\n const source = await awaitWithSignal(Promise.resolve(this.options.resolver(specifier, referrer, {signal:this.options.signal})),this.options.signal);\n this.options.signal?.throwIfAborted();\n if (source === undefined) throw new TypeError(`Source resolver denied '${specifier}' from '${referrer}'.`);\n if (typeof source.id !== \"string\" || source.id.length === 0 || typeof source.source !== \"string\")\n throw new TypeError(\"Source resolver must supply a nonempty identity and source text.\");\n return this.options.serializePreparation\n ? this.jobs.run(() => this.register(source)) : this.register(source);\n })();\n this.requests.set(key,request);\n return request;\n }\n\n private loadGraph(root: RecordEntry): Promise<void> {\n return new Promise((resolve, reject) => {\n const visited = new Set<RecordEntry>();\n let pending = 1;\n let loading = true;\n const fail = (reason: unknown) => {loading = false; reject(reason);};\n const finish = () => {\n if (--pending === 0 && loading) {loading = false; resolve();}\n };\n const visit = (record: RecordEntry) => {\n this.options.budget?.visitNode();\n if (visited.has(record)) return;\n visited.add(record);\n for (const {specifier: request, attributes} of record.parsed.moduleRequests) {\n this.options.budget?.visitNode();\n if (attributes.length > 0) throw new SyntaxError(`Unsupported import attribute '${attributes[0]![0]}'.`);\n pending++;\n // Request every edge without waiting for its peers. Each resolution\n // continues loading its own descendants, including across cycles.\n void this.load(request,record.id).then(dependency => {\n if (!loading) return;\n try {\n record.dependencies.set(request,dependency);\n if (isRecord(dependency)) visit(dependency);\n finish();\n } catch (reason) {fail(reason);}\n }, fail);\n }\n };\n try {visit(root); finish();} catch (reason) {fail(reason);}\n });\n }\n\n private async link(root: RecordEntry): Promise<void> {\n const pending = [root];\n const visited = new Set<RecordEntry>();\n while (pending.length > 0) {\n this.options.budget?.visitNode();\n const record = pending.pop()!;\n if (visited.has(record)) continue;\n visited.add(record);\n for (const dependency of record.dependencies.values()) if (isRecord(dependency)) pending.push(dependency);\n }\n // Instantiate all local cells and hoisted functions before creating any import.\n for (const record of visited) if (record.linked === undefined) {\n record.linked = this.execute(record,\"link\");\n await record.linked;\n } else await record.linked;\n for (const record of visited) {\n for (const entry of record.parsed.exports) {\n this.options.budget?.visitNode();\n if (entry.exported !== undefined && entry.request !== undefined) this.requireExport(record,entry.exported);\n }\n for (const entry of record.parsed.imports) {\n this.options.budget?.visitNode();\n if (record.scope.hasOwnBinding(entry.local)) continue;\n const dependency = record.dependencies.get(entry.request)!;\n if (entry.namespace === true) {\n record.scope.declare(entry.local,\"const\",isRecord(dependency) ? this.namespace(dependency) : dependency);\n continue;\n }\n const binding = isRecord(dependency) ? this.requireExport(dependency,entry.imported)\n : Object.hasOwn(dependency,entry.imported) ? {namespace:dependency,name:entry.imported} : undefined;\n if (binding === undefined) throw new SyntaxError(`Module '${entry.request}' does not export '${entry.imported}'.`);\n if (\"record\" in binding) record.scope.declareImport(entry.local,binding.record.scope,binding.name);\n else record.scope.declare(entry.local,\"const\",binding.whole ? binding.namespace : binding.namespace[binding.name]);\n }\n }\n }\n\n private names(record: RecordEntry, visited = new Set<RecordEntry>()): Set<string> {\n this.options.budget?.visitNode();\n if (visited.has(record)) return new Set();\n const leave = this.options.budget?.enterCall();\n try {\n visited.add(record);\n const names = new Set<string>();\n for (const entry of record.parsed.exports) {\n this.options.budget?.visitNode();\n if (entry.exported !== undefined) names.add(entry.exported);\n else {\n const dependency = record.dependencies.get(entry.request!)!;\n for (const name of isRecord(dependency) ? this.names(dependency,visited) : Object.keys(dependency))\n if (name !== \"default\") names.add(name);\n }\n }\n return names;\n } finally { leave?.(); }\n }\n\n private resolve(record: RecordEntry, name: string, visited = new Set<string>()): Binding | typeof ambiguous | undefined {\n this.options.budget?.visitNode();\n const key = JSON.stringify([record.id,name]);\n if (visited.has(key)) return undefined;\n const leave = this.options.budget?.enterCall();\n try {\n visited.add(key);\n const explicit = record.explicitExports.get(name);\n if (explicit?.local !== undefined) {\n const imported = record.localImports.get(explicit.local);\n if (imported === undefined || imported.namespace === true) return {record,name:explicit.local};\n return this.resolveDependency(record, imported.request, imported.imported,visited);\n }\n if (explicit?.request !== undefined) return this.resolveDependency(record,explicit.request,explicit.imported!,visited,explicit.namespace);\n if (name === \"default\") return undefined;\n let resolved: Binding | undefined;\n for (const entry of record.starExports) {\n this.options.budget?.visitNode();\n const candidate = this.resolveDependency(record,entry.request!,name,visited);\n if (candidate === ambiguous) return ambiguous;\n if (candidate === undefined) continue;\n if (resolved !== undefined && !sameBinding(resolved,candidate)) return ambiguous;\n resolved = candidate;\n }\n return resolved;\n } finally { leave?.(); }\n }\n\n private resolveDependency(record: RecordEntry, request: string, name: string, visited: Set<string>, whole = false): Binding | typeof ambiguous | undefined {\n const dependency = record.dependencies.get(request)!;\n if (whole) {\n if (!isRecord(dependency)) return {namespace:dependency,name:\"\",whole:true};\n const namespace = this.namespace(dependency);\n const local = \"*namespace*\";\n if (!dependency.scope.hasOwnBinding(local)) dependency.scope.declare(local,\"const\",namespace);\n return {record:dependency,name:local};\n }\n return isRecord(dependency) ? this.resolve(dependency,name,visited)\n : Object.hasOwn(dependency,name) ? {namespace:dependency,name} : undefined;\n }\n\n private requireExport(record: RecordEntry, name: string): Binding {\n const resolved = this.resolve(record,name);\n if (resolved === undefined || resolved === ambiguous)\n throw new SyntaxError(`Module '${record.id}' has ${resolved === ambiguous ? \"an ambiguous\" : \"no\"} export '${name}'.`);\n return resolved;\n }\n\n private namespace(record: RecordEntry): SandboxObject {\n if (record.namespace !== undefined) return record.namespace;\n const bindings = new Map<string,Binding>();\n record.namespace = createModuleNamespace(namespace => {\n record.namespace = namespace;\n for (const name of this.names(record)) {\n const resolved = this.resolve(record,name);\n if (resolved !== undefined && resolved !== ambiguous) bindings.set(name,resolved);\n }\n return Object.fromEntries([...bindings.keys()].map(name => [name,undefined]));\n }, name => {\n const binding = bindings.get(name)!;\n if (\"namespace\" in binding) return binding.whole ? binding.namespace : binding.namespace[binding.name];\n const value = binding.record.scope.lookup(binding.name);\n if (!value.found) throw new ReferenceError(`Uninitialized module export '${name}'.`);\n return value.value;\n }, () => record.scope.retainedDataRoots());\n return record.namespace;\n }\n\n private async evaluate(record: RecordEntry): Promise<void> {\n try {\n await this.jobs.run(() => this.start(record));\n await (record.cycleRoot ?? record).evaluation;\n } catch (reason) {\n for (const pending of this.evaluationStack.splice(0)) {\n pending.onStack=false;\n pending.cycleRoot=record;\n pending.failure ??= {reason};\n }\n throw reason;\n }\n }\n\n private start(record: RecordEntry, ancestors = new Set<RecordEntry>()): Promise<void> {\n if (ancestors.has(record)) return Promise.resolve();\n if (record.traversal !== undefined) return record.traversal;\n let fulfilled!: () => void;\n let rejected!: (reason: unknown) => void;\n record.evaluation = new Promise<void>((resolve,reject) => {fulfilled=resolve;rejected=reject;});\n void record.evaluation.catch(() => undefined);\n const complete = () => {record.completed=true;fulfilled();};\n const fail = (reason: unknown) => {record.completed=true;record.failure={reason};rejected(reason);};\n const next = new Set(ancestors).add(record);\n record.traversal = (async () => {\n record.dfsIndex=this.evaluationIndex++;\n record.dfsAncestor=record.dfsIndex;\n record.onStack=true;\n this.evaluationStack.push(record);\n const dependencies: Promise<void>[] = [];\n // Host resolution completion order must not change evaluation order.\n for (const request of record.parsed.requests) {\n const dependency = record.dependencies.get(request)!;\n if (!isRecord(dependency)) continue;\n if (!next.has(dependency)) await this.start(dependency,next);\n if (dependency.onStack) record.dfsAncestor=Math.min(record.dfsAncestor,dependency.dfsAncestor!);\n const required=dependency.onStack ? dependency : dependency.cycleRoot ?? dependency;\n if (required.failure !== undefined) throw required.failure.reason;\n if (required.async && !required.completed) dependencies.push(required.evaluation!);\n }\n record.async = record.parsed.hasTLA || dependencies.length > 0;\n if (dependencies.length > 0) {\n void Promise.all(dependencies).then(() => this.execute(record,\"evaluate\")).then(complete,fail);\n } else if (record.parsed.hasTLA) {\n let suspend!: () => void;\n const prefix = new Promise<void>(resolve => {suspend=resolve;});\n void this.execute(record,\"evaluate\",suspend).then(complete,fail).then(suspend);\n await prefix;\n } else {\n await this.execute(record,\"evaluate\");\n complete();\n }\n if (record.dfsIndex === record.dfsAncestor) {\n for (;;) {\n const member=this.evaluationStack.pop()!;\n member.onStack=false;\n member.cycleRoot=record;\n if (member===record) break;\n }\n }\n })().catch(error => {fail(error);throw error;});\n return record.traversal;\n }\n\n private async execute(record: RecordEntry, modulePhase: \"link\" | \"evaluate\", onSuspend?: () => void): Promise<void> {\n const result = await interpret({type:\"BlockStatement\",body:record.parsed.module.body,span:record.parsed.module.span},\n {...this.options, scope:record.scope, useScopeDirectly:true, captureSnapshot:false, jobs:this.jobs, nested:true,modulePhase,onSuspend});\n this.stats.nodeVisits += result.stats.nodeVisits;\n if (!result.ok) throw new Error(result.error.message);\n }\n}\n\nfunction isRecord(value: RecordEntry | SandboxObject): value is RecordEntry {\n return sourceRecords.has(value);\n}\nfunction sameBinding(left: Binding, right: Binding): boolean {\n return left.name === right.name && (\"record\" in left && \"record\" in right ? left.record === right.record\n : \"namespace\" in left && \"namespace\" in right && left.namespace === right.namespace && left.whole === right.whole);\n}\n", "import { createSeededRandom } from \"./interp/globals/math.js\";\nimport type { SafeJSSnapshot } from \"./restore.js\";\nimport type { RunRandom } from \"./run.js\";\n\nexport type ReplayableRandom = RunRandom & {\n restore: (state: number) => void;\n};\n\nexport function createReplayableRandom(\n options: {\n seed?: number;\n snapshot?: SafeJSSnapshot;\n } = {}\n): ReplayableRandom {\n const snapshot = options.snapshot;\n const saved = snapshot?.random;\n let initialState = options.seed;\n if (saved !== undefined) {\n const hasLoopState =\n typeof snapshot?.loopIterations === \"object\" &&\n snapshot.loopIterations !== null &&\n Object.keys(snapshot.loopIterations).length > 0;\n const replaysFromStart =\n snapshot?.replay !== undefined ||\n (Array.isArray(snapshot?.pendingAwaits) &&\n snapshot.pendingAwaits.length > 0 &&\n !hasLoopState);\n initialState = replaysFromStart\n ? (saved.initialState ?? saved.seed)\n : (saved.resumeState ?? saved.state);\n }\n const generator = createSeededRandom(initialState ?? globalThis.crypto.getRandomValues(new Uint32Array(1))[0]!);\n return { seed: saved?.seed ?? generator.snapshot(), ...generator };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { getOwnErrorCode, hasOwnErrorCode } from \"../error-codes.js\";\nimport type { SafeJSSnapshot } from \"../restore.js\";\nimport { serializeSafeJSSnapshot } from \"./dump-format.js\";\n\nexport type Snapshot = SafeJSSnapshot;\n\nexport interface SnapshotBackend {\n read(): Promise<Snapshot | undefined>;\n write(snapshot: Snapshot): Promise<void>;\n remove(): Promise<void>;\n}\n\nexport type FileSnapshotBackendOptions = {\n writeMaxAttempts?: number;\n writeRetryDelayMs?: number;\n};\n\nconst DEFAULT_WRITE_MAX_ATTEMPTS = 3;\nconst DEFAULT_WRITE_RETRY_DELAY_MS = 100;\nconst LOCKED_FILE_ERROR_CODES = new Set([\"EACCES\", \"EBUSY\", \"EPERM\"]);\nconst pendingOperations = new Map<string, Promise<void>>();\n\nexport class FileSnapshotBackend implements SnapshotBackend {\n readonly #writeMaxAttempts: number;\n readonly #writeRetryDelayMs: number;\n\n constructor(\n readonly path: string,\n options: FileSnapshotBackendOptions = {}\n ) {\n this.#writeMaxAttempts = options.writeMaxAttempts ?? DEFAULT_WRITE_MAX_ATTEMPTS;\n this.#writeRetryDelayMs = options.writeRetryDelayMs ?? DEFAULT_WRITE_RETRY_DELAY_MS;\n }\n\n async read(): Promise<Snapshot | undefined> {\n try {\n return JSON.parse(await readFile(this.path, \"utf8\")) as Snapshot;\n } catch (error) {\n if (hasErrorCode(error, \"ENOENT\")) {\n return undefined;\n }\n\n if (error instanceof SyntaxError) {\n throw new Error(`Failed to parse snapshot at ${this.path}: ${error.message}`);\n }\n\n throw error;\n }\n }\n\n async write(snapshot: Snapshot): Promise<void> {\n await enqueueOperation(this.path, () =>\n writeSnapshotAtomically(this.path, snapshot, {\n maxAttempts: this.#writeMaxAttempts,\n retryDelayMs: this.#writeRetryDelayMs\n })\n );\n }\n\n async remove(): Promise<void> {\n await enqueueOperation(this.path, async () => {\n try {\n await unlink(this.path);\n } catch (error) {\n if (!hasErrorCode(error, \"ENOENT\")) {\n throw error;\n }\n }\n });\n }\n}\n\nasync function writeSnapshotAtomically(\n snapshotPath: string,\n snapshot: Snapshot,\n options: {\n maxAttempts: number;\n retryDelayMs: number;\n }\n): Promise<void> {\n const parentPath = dirname(snapshotPath);\n const contents = serializeSafeJSSnapshot(snapshot);\n\n await assertParentDirectoryExists(snapshotPath, parentPath);\n\n for (let attempt = 1; attempt <= options.maxAttempts; attempt += 1) {\n try {\n const temporaryPath = `${snapshotPath}.${randomUUID()}.tmp`;\n await writeSnapshotOnce(temporaryPath, snapshotPath, contents);\n return;\n } catch (error) {\n if (hasErrorCode(error, \"EEXIST\")) {\n if (attempt === options.maxAttempts) {\n throw new Error(\n `Failed to write snapshot at ${snapshotPath} after ${options.maxAttempts} attempts: temporary path already exists`,\n {\n cause: error\n }\n );\n }\n\n continue;\n }\n\n if (!isLockedFileError(error)) {\n throw error;\n }\n\n if (attempt === options.maxAttempts) {\n throw new Error(\n `Failed to write snapshot at ${snapshotPath} after ${options.maxAttempts} attempts: file is locked (${getOwnErrorCode(error)})`,\n {\n cause: error\n }\n );\n }\n\n await delay(options.retryDelayMs);\n }\n }\n}\n\nasync function assertParentDirectoryExists(\n snapshotPath: string,\n parentPath: string\n): Promise<void> {\n try {\n const parent = await stat(parentPath);\n if (!parent.isDirectory()) {\n throw new Error(\n `Cannot write snapshot at ${snapshotPath}: parent path ${parentPath} is not a directory`\n );\n }\n } catch (error) {\n if (hasErrorCode(error, \"ENOENT\")) {\n throw new Error(\n `Cannot write snapshot at ${snapshotPath}: parent directory ${parentPath} does not exist`,\n {\n cause: error\n }\n );\n }\n\n throw error;\n }\n}\n\nasync function writeSnapshotOnce(\n temporaryPath: string,\n snapshotPath: string,\n contents: string\n): Promise<void> {\n let temporaryCreated = false;\n let renamed = false;\n try {\n try {\n await writeFile(temporaryPath, contents, { encoding: \"utf8\", flag: \"wx\" });\n temporaryCreated = true;\n } catch (error) {\n if (!hasErrorCode(error, \"EEXIST\")) {\n await removeTemporarySnapshot(temporaryPath).catch(() => undefined);\n }\n throw error;\n }\n await rename(temporaryPath, snapshotPath);\n renamed = true;\n } finally {\n if (temporaryCreated && !renamed) {\n await removeTemporarySnapshot(temporaryPath).catch(() => undefined);\n }\n }\n}\n\nasync function enqueueOperation(path: string, operation: () => Promise<void>): Promise<void> {\n const previous = pendingOperations.get(path) ?? Promise.resolve();\n const pending = previous.catch(() => undefined).then(operation);\n const queued = pending.catch(() => undefined);\n pendingOperations.set(path, queued);\n try {\n await pending;\n } finally {\n if (pendingOperations.get(path) === queued) {\n pendingOperations.delete(path);\n }\n }\n}\n\nasync function removeTemporarySnapshot(temporaryPath: string): Promise<void> {\n try {\n await unlink(temporaryPath);\n } catch (error) {\n if (!hasErrorCode(error, \"ENOENT\")) {\n throw error;\n }\n }\n}\n\nasync function delay(ms: number): Promise<void> {\n if (ms === 0) {\n return;\n }\n\n await new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction hasErrorCode(error: unknown, code: string): boolean {\n return hasOwnErrorCode(error, code);\n}\n\nfunction isLockedFileError(error: unknown): boolean {\n const code = getOwnErrorCode(error);\n return code !== undefined && LOCKED_FILE_ERROR_CODES.has(code);\n}\n", "import {\n FileSnapshotBackend,\n type FileSnapshotBackendOptions,\n type Snapshot,\n type SnapshotBackend\n} from \"./backend.js\";\n\nconst DEFAULT_SNAPSHOT_INTERVAL_MS = 30_000;\n\nexport type SnapshotSchedulerOptions = {\n snapshotBackend?: SnapshotBackend;\n snapshotIntervalMs?: number;\n snapshotPath?: string;\n snapshotWriteMaxAttempts?: number;\n snapshotWriteRetryDelayMs?: number;\n};\n\nexport type SnapshotScheduler<TSnapshot> = {\n finish(): Promise<void>;\n onYield(createSnapshot: () => TSnapshot): void;\n pause(): void;\n resume(): void;\n write(snapshot: TSnapshot): Promise<void>;\n};\n\nexport function createSnapshotScheduler<TSnapshot>(\n options: SnapshotSchedulerOptions\n): SnapshotScheduler<TSnapshot> {\n const snapshotBackend =\n options.snapshotBackend ??\n (options.snapshotPath === undefined\n ? undefined\n : new FileSnapshotBackend(options.snapshotPath, createFileSnapshotBackendOptions(options)));\n\n if (snapshotBackend === undefined) {\n return {\n async finish() {},\n onYield() {},\n pause() {},\n resume() {},\n async write() {}\n };\n }\n\n const intervalMs = options.snapshotIntervalMs ?? DEFAULT_SNAPSHOT_INTERVAL_MS;\n if (intervalMs === 0) {\n return {\n async finish() {},\n onYield() {},\n pause() {},\n resume() {},\n async write(snapshot) {\n await snapshotBackend.write(snapshot as Snapshot);\n }\n };\n }\n\n let nextCheckpointAt = Date.now() + intervalMs;\n let pendingWrite = Promise.resolve();\n let isPaused = false;\n const writeErrors: unknown[] = [];\n\n return {\n async finish() {\n await pendingWrite;\n if (writeErrors.length > 0) {\n throw writeErrors[0];\n }\n },\n onYield(createSnapshot) {\n if (isPaused) {\n return;\n }\n\n if (Date.now() < nextCheckpointAt) {\n return;\n }\n\n nextCheckpointAt = Date.now() + intervalMs;\n const snapshot = createSnapshot();\n pendingWrite = pendingWrite\n .catch(() => undefined)\n .then(async () => {\n try {\n await snapshotBackend.write(snapshot as Snapshot);\n } catch (error) {\n writeErrors.push(error);\n }\n });\n },\n pause() {\n isPaused = true;\n },\n resume() {\n if (!isPaused) {\n return;\n }\n\n isPaused = false;\n nextCheckpointAt = Date.now() + intervalMs;\n },\n async write(snapshot) {\n await pendingWrite.catch(() => undefined);\n await snapshotBackend.write(snapshot as Snapshot);\n }\n };\n}\n\nfunction createFileSnapshotBackendOptions(\n options: SnapshotSchedulerOptions\n): FileSnapshotBackendOptions {\n return {\n writeMaxAttempts: options.snapshotWriteMaxAttempts,\n writeRetryDelayMs: options.snapshotWriteRetryDelayMs\n };\n}\n", "import { weakReferenceStates } from \"../interp/weak-reference.js\";\nimport { getIntrinsicRealmIdentity } from \"../interp/intrinsics.js\";\nimport { getFunctionRealmPrototype } from \"../interp/function-realm.js\";\nimport { finalizationRegistryStates } from \"../interp/finalization-registry-state.js\";\nimport { wellKnownSymbols } from \"../interp/symbols.js\";\nimport { hashSource } from \"../parse/hash.js\";\nimport { weakCollectionStates, type WeakCollectionKey } from \"../interp/weak-collection.js\";\nimport type { PropertyDescriptorData } from \"./property-descriptors.js\";\nimport { serializeCollectionProperties } from \"./collection-properties.js\";\nimport { hasCustomRegexProperties, serializeRegexProperties, type RegexPropertyData } from \"./regexp-properties.js\";\nimport { ownSerializableSymbolKeys, serializeSymbol, serializeSymbolProperties, type SerializedSymbol, type SerializedSymbolProperty } from \"./symbols.js\";\nimport { collectionIteratorState, isSandboxCollectionIterator, snapshotCollectionIterator, type CollectionIterationMethod, type SandboxCollectionIterator } from \"../interp/collection-iterator.js\";\nimport { isSandboxRegExpIterator, regexpIteratorState, type SandboxRegExpIterator } from \"../interp/regexp-iterator.js\";\nimport { hasGuestObjectState, hasNullObjectPrototype, isGuestClosure } from \"../interp/object-model.js\";\nimport { sandboxErrorTypes, type SandboxErrorName } from \"../error/shape.js\";\nimport { assertSnapshotDataDepth, assertSnapshotGraphDepth } from \"../graph-depth.js\";\nimport { captureGuestHeapNode, type GuestHeapNode, type GuestObjectState, type PrivateElementData } from \"./guest-heap.js\";\nimport { getClosureOrigin, getGeneratorOrigin } from \"../interp/closure-origin.js\";\nimport { classOrigins } from \"../interp/classes.js\";\nimport { functionSources, templateSources } from \"../parse/function-source.js\";\nimport { templateOrigins, templateRealmIdentities } from \"../interp/template-objects.js\";\nimport { serializeArguments, type SerializedArguments } from \"./arguments.js\";\nimport { requiresArrayEntries, serializeArray, type SerializedArray } from \"./arrays.js\";\nimport { typedArrayStorage, isNumericTypedArray, type NumericTypedArray } from \"../interp/typed-array.js\";\nimport { captureTypedArrayState, encodeTypedArrayLayout, type TypedArrayData } from \"./typed-array.js\";\nimport { isSandboxArrayBuffer } from \"../interp/array-buffer.js\";\nimport { isSandboxSharedArrayBuffer } from \"../interp/shared-array-buffer.js\";\nimport { encodeSharedArrayBufferStorage, type SharedArrayBufferData } from \"./shared-array-buffer.js\";\nimport { dataViewBuffer, isSandboxDataView } from \"../interp/data-view.js\";\nimport { captureDataViewState, encodeDataViewLayout, type DataViewData } from \"./data-view.js\";\nimport { captureArrayBufferState, encodeArrayBufferStorage, type ArrayBufferData } from \"./array-buffer.js\";\nimport { dateDataProperties, isSandboxDate } from \"../interp/date.js\";\nimport { serializeDate, type SerializedDate } from \"./date-properties.js\";\nimport { boxedDataProperties, isSandboxBox, type SandboxBox } from \"../interp/boxed.js\";\nimport { encodeBoxedData, type BoxedData } from \"./boxed.js\";\nimport {\n isSandboxClosure,\n isSandboxArguments,\n isSandboxGenerator,\n isSandboxMap,\n isSandboxRegex,\n getRegexProperties,\n isSandboxSet,\n type SandboxMap,\n type SandboxArray,\n type SandboxClosure,\n type SandboxGenerator,\n type SandboxPromise,\n type SandboxRegex,\n type SandboxSet\n} from \"../interp/values.js\";\n\ntype SnapshotId = number | string;\n\ntype SerializedUndefinedValue = {\n kind: \"undefined\";\n};\n\ntype SerializedNonFiniteNumber = {\n kind: \"number\";\n value: \"-Infinity\" | \"Infinity\" | \"NaN\" | \"-0\";\n};\n\nexport type SerializedClosureValue = {\n kind: \"fn\";\n astNodeId: number;\n capturedScopeId: SnapshotId;\n};\n\nexport type SerializedGeneratorValue =\n { async?: boolean } & ({\n kind: \"generator\";\n state: \"start\";\n astNodeId: number;\n capturedScopeId: SnapshotId;\n }\n | {\n kind: \"generator\";\n state: \"suspended\";\n astNodeId: number;\n capturedScopeId: SnapshotId;\n yieldNodeId: number;\n sent: SerializedSnapshotValue;\n }\n | {\n kind: \"generator\";\n state: \"done\";\n });\n\nexport type SerializedPromiseValue = {\n kind: \"promise\";\n id: SnapshotId;\n};\n\nexport type SerializedReferenceValue = {\n kind: \"ref\";\n id: number;\n};\n\nexport type SerializedHeapValue =\n | (SharedArrayBufferData<SerializedReferenceValue> & {state:GuestObjectState<SerializedSnapshotValue>})\n | (DataViewData<SerializedReferenceValue> & { state: GuestObjectState<SerializedSnapshotValue> })\n | (ArrayBufferData<SerializedReferenceValue> & { state: GuestObjectState<SerializedSnapshotValue> })\n | GuestHeapNode<SerializedSnapshotValue>\n | { kind: \"regexp-iterator\"; matcher: SerializedSnapshotValue; input: SerializedSnapshotValue; exhausted: boolean; global?: boolean; unicode?: boolean; entries: Record<string, SerializedSnapshotValue>; symbolEntries?: Array<SerializedSymbolProperty<SerializedSnapshotValue>> }\n | SerializedSymbol\n | BoxedData<SerializedSnapshotValue>\n | ({ kind: \"regex-object\"; source: string; flags: string; lastIndex: SerializedSnapshotValue } & RegexPropertyData<SerializedSnapshotValue>)\n | { kind: \"collection-iterator\"; collectionKind: \"map\" | \"set\"; method: CollectionIterationMethod; collection: SerializedSnapshotValue; index: number; exhausted: boolean; entries: Record<string, SerializedSnapshotValue> }\n | SerializedDate<SerializedSnapshotValue>\n | (TypedArrayData<SerializedReferenceValue> & { entries: Record<string, SerializedSnapshotValue>; state?: GuestObjectState<SerializedSnapshotValue> })\n | SerializedArguments<SerializedSnapshotValue>\n | SerializedArray<SerializedSnapshotValue>\n | {\n kind: \"object\";\n sandboxNullPrototype?: true;\n entries: Record<string, SerializedSnapshotValue>;\n symbolEntries?: Array<SerializedSymbolProperty<SerializedSnapshotValue>>;\n errorType?: SandboxErrorName;\n }\n | {\n kind: \"map\";\n privateElements?: PrivateElementData<SerializedSnapshotValue>[];\n prototype?: SerializedSnapshotValue;\n propertyState?: PropertyDescriptorData<SerializedSnapshotValue>;\n entries: Array<[SerializedSnapshotValue, SerializedSnapshotValue]>;\n }\n | {\n kind: \"set\";\n privateElements?: PrivateElementData<SerializedSnapshotValue>[];\n prototype?: SerializedSnapshotValue;\n propertyState?: PropertyDescriptorData<SerializedSnapshotValue>;\n values: SerializedSnapshotValue[];\n };\n\nexport type SerializedSnapshotValue =\n | boolean\n | null\n | number\n | string\n | SerializedClosureValue\n | SerializedGeneratorValue\n | SerializedNonFiniteNumber\n | SerializedPromiseValue\n | SerializedReferenceValue\n | SerializedUndefinedValue\n | { kind: \"regex\"; source: string; flags: string; lastIndex: number }\n | SerializedSnapshotValue[]\n | {\n [key: string]: SerializedSnapshotValue;\n };\n\nexport type RuntimeClosureValue = {\n kind: \"fn\";\n astNodeId: number;\n capturedScopeId: SnapshotId;\n call?: unknown;\n};\n\nexport type RuntimePromiseValue = {\n kind: \"promise\";\n id: SnapshotId;\n promise?: Promise<unknown>;\n};\n\nexport type RuntimeSnapshotValue =\n | bigint\n | symbol\n | SandboxBox\n | Date\n | NumericTypedArray\n | ArrayBuffer\n | SharedArrayBuffer\n | DataView<ArrayBufferLike>\n | boolean\n | null\n | number\n | string\n | undefined\n | RuntimeClosureValue\n | SandboxClosure\n | SandboxGenerator\n | SandboxCollectionIterator\n | SandboxRegExpIterator\n | RuntimePromiseValue\n | SandboxPromise\n | SandboxMap\n | SandboxRegex\n | SandboxSet\n | RuntimeSnapshotValue[]\n | {\n [key: string]: RuntimeSnapshotValue;\n };\n\nexport type RuntimeScopeFrame = {\n id: SnapshotId;\n parentId?: SnapshotId;\n bindings: Record<string, RuntimeSnapshotValue>;\n};\n\nexport type SerializedScopeFrame = {\n id: SnapshotId;\n parentId?: SnapshotId;\n bindings: Record<string, SerializedSnapshotValue>;\n};\n\nexport type RuntimeCallFrame = {\n astNodeId: number;\n scopeId: SnapshotId;\n awaitingPromiseId?: SnapshotId;\n};\n\nexport type SerializedCallFrame = RuntimeCallFrame;\n\nexport type RuntimePendingPromise = {\n id: SnapshotId;\n promise?: Promise<unknown>;\n [key: string]: RuntimeSnapshotValue | Promise<unknown> | SnapshotId | undefined;\n};\n\nexport type SerializedPendingPromise = {\n id: SnapshotId;\n [key: string]: SerializedSnapshotValue | SnapshotId;\n};\n\nexport type SerializeInput = {\n source: string;\n currentAstNodeId: number;\n scopeChain: RuntimeScopeFrame[];\n callStack: RuntimeCallFrame[];\n pendingPromises: RuntimePendingPromise[];\n moduleBindings: Record<string, string>;\n};\n\nexport type SerializedSnapshot = {\n sourceHash: string;\n currentAstNodeId: number;\n scopeChain: SerializedScopeFrame[];\n callStack: SerializedCallFrame[];\n pendingPromises: SerializedPendingPromise[];\n moduleBindings: Record<string, string>;\n heap?: Record<string, SerializedHeapValue>;\n};\n\ntype SerializationState = {\n source: string;\n moduleSources: Map<string, number>;\n intrinsicRealms: Map<object, number>;\n float32Buffers: WeakMap<ArrayBuffer, number>;\n sharedBlocks?:WeakMap<object,number>;\n ancestors: WeakMap<object, string>;\n heap: Record<string, SerializedHeapValue>;\n heapIds: Map<object | symbol, number>;\n guestValues: Set<object>;\n weakEntries: Map<object, Array<[WeakCollectionKey, unknown]>>;\n weakTargets: Map<object, object | symbol>;\n finalizationTargets: Map<object, Array<{target?:object | symbol;token?:object | symbol}>>;\n serializedHeapIds: Set<number>;\n};\n\nexport class UnsnapshotableValueError extends Error {\n readonly path: string;\n\n constructor(path: string) {\n super(\n \"Cannot snapshot a generator suspended mid-iteration; drain or discard it before the await boundary.\"\n );\n this.name = \"UnsnapshotableValueError\";\n this.path = path;\n }\n}\n\nexport function serialize(input: SerializeInput): SerializedSnapshot {\n for (const [scopeIndex, scope] of input.scopeChain.entries()) {\n for (const [name, value] of Object.entries(scope.bindings)) {\n assertSnapshotGraphDepth(value, `scopeChain[${scopeIndex}].bindings.${name}`);\n }\n }\n for (const [promiseIndex, promise] of input.pendingPromises.entries()) {\n for (const [key, value] of Object.entries(promise)) {\n if (key !== \"id\" && key !== \"promise\") {\n assertSnapshotGraphDepth(value, `pendingPromises[${promiseIndex}].${key}`);\n }\n }\n }\n const state: SerializationState = {\n source: input.source,\n moduleSources: new Map(),\n intrinsicRealms: new Map(),\n float32Buffers: new WeakMap(),\n ancestors: new WeakMap(),\n heap: Object.create(null) as Record<string, SerializedHeapValue>,\n ...indexHeapContainers(input),\n serializedHeapIds: new Set()\n };\n\n const snapshot: SerializedSnapshot = {\n sourceHash: hashSource(input.source),\n currentAstNodeId: input.currentAstNodeId,\n scopeChain: input.scopeChain.map((scope, index) =>\n serializeScopeFrame(scope, `scopeChain[${index}]`, state)\n ),\n callStack: input.callStack.map((frame) => ({ ...frame })),\n pendingPromises: input.pendingPromises.map((promise, index) =>\n serializePendingPromise(promise, `pendingPromises[${index}]`, state)\n ),\n moduleBindings: { ...input.moduleBindings }\n };\n\n if (Object.keys(state.heap).length === 0) {\n return snapshot;\n }\n\n if (state.intrinsicRealms.size === 1) {\n for (const node of Object.values(state.heap)) if (node.kind === \"intrinsic\" || node.kind === \"guest-function\" || node.kind === \"guest-class\" || node.kind === \"guest-generator\" || node.kind === \"guest-array\") delete node.realm;\n }\n\n return {\n ...snapshot,\n heap: state.heap\n };\n}\n\nfunction serializeScopeFrame(\n scope: RuntimeScopeFrame,\n path: string,\n state: SerializationState\n): SerializedScopeFrame {\n const bindings = Object.create(null) as Record<string, SerializedSnapshotValue>;\n\n for (const [name, value] of Object.entries(scope.bindings)) {\n bindings[name] = serializeValue(value, `${path}.bindings.${name}`, state);\n }\n\n return scope.parentId === undefined\n ? {\n id: scope.id,\n bindings\n }\n : {\n id: scope.id,\n parentId: scope.parentId,\n bindings\n };\n}\n\nfunction serializePendingPromise(\n pendingPromise: RuntimePendingPromise,\n path: string,\n state: SerializationState\n): SerializedPendingPromise {\n const serialized: SerializedPendingPromise = {\n id: pendingPromise.id\n };\n\n for (const [key, value] of Object.entries(pendingPromise)) {\n if (key === \"id\" || key === \"promise\") {\n continue;\n }\n\n serialized[key] = serializeValue(value as RuntimeSnapshotValue, `${path}.${key}`, state);\n }\n\n return serialized;\n}\n\nfunction serializeValue(\n value: RuntimeSnapshotValue,\n path: string,\n state: SerializationState\n): SerializedSnapshotValue {\n if (typeof value === \"symbol\") return serializeSymbol(value, state.heapIds, state.heap);\n if (typeof value === \"object\" && value !== null && state.guestValues.has(value)) {\n const id = state.heapIds.get(value)!;\n if (!state.serializedHeapIds.has(id)) {\n state.serializedHeapIds.add(id);\n const node = captureGuestHeapNode(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<guest>`, state), state.weakEntries.get(value), state.weakTargets.get(value), state.finalizationTargets.get(value));\n if (node === undefined) throw new TypeError(`Missing guest heap state at ${path}.`);\n if ((node.kind === \"guest-function\" || node.kind === \"guest-class\" || node.kind === \"guest-generator\" || node.kind === \"guest-array\") && node.dynamicSource === undefined) {\n const origin = getClosureOrigin(value) ?? classOrigins.get(value) ?? getGeneratorOrigin(value);\n const template = Array.isArray(value) ? templateOrigins.get(value as SandboxArray) : undefined;\n const body = template === undefined\n ? origin === undefined ? undefined : functionSources.get(origin.node)?.text\n : templateSources.get(template);\n if (body !== undefined && body !== state.source) {\n let sourceId = state.moduleSources.get(body);\n if (sourceId === undefined) {\n const source = { kind: \"guest-source\" as const, functionKind: \"module\" as const, parameters: \"\", body };\n sourceId = state.heapIds.size + 1;\n state.heapIds.set(source, sourceId);\n state.moduleSources.set(body, sourceId);\n state.heap[String(sourceId)] = source;\n }\n node.dynamicSource = { kind: \"ref\", id: sourceId };\n }\n }\n if (node.kind === \"intrinsic\" || node.kind === \"guest-function\" || node.kind === \"guest-class\" || node.kind === \"guest-generator\" || node.kind === \"guest-array\") {\n const realmValue = node.kind === \"intrinsic\" ? value\n : isSandboxClosure(value) ? getFunctionRealmPrototype(value, \"Object\", undefined) : undefined;\n const origin = node.kind === \"guest-array\" ? templateRealmIdentities.get(value)\n : node.kind === \"guest-generator\" ? getGeneratorOrigin(value)?.realmIdentity\n : realmValue === undefined ? undefined : getIntrinsicRealmIdentity(realmValue);\n if (origin === undefined && node.kind === \"intrinsic\") throw new TypeError(\"Missing intrinsic realm identity.\");\n if (origin !== undefined) {\n let realm = state.intrinsicRealms.get(origin);\n if (realm === undefined) state.intrinsicRealms.set(origin, realm = state.intrinsicRealms.size + 1);\n node.realm = realm;\n }\n }\n state.heap[String(id)] = node;\n }\n return { kind: \"ref\", id };\n }\n if (isSandboxClosure(value) && !isGuestClosure(value)) throw new TypeError(`Cannot serialize host reference at ${path}.`);\n if (typeof value === \"object\" && value !== null && hasGuestObjectState(value) && !isSandboxMap(value) && !isSandboxSet(value) && !isNumericTypedArray(value) && !isSandboxArrayBuffer(value) && !isSandboxSharedArrayBuffer(value) && !isSandboxDataView(value)) {\n throw new TypeError(\"Guest function properties and prototype links cannot be serialized.\");\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (value === undefined) {\n return {\n kind: \"undefined\"\n };\n }\n\n if (typeof value === \"number\") {\n if (Object.is(value, -0)) return { kind: \"number\", value: \"-0\" };\n if (Number.isFinite(value)) {\n return value;\n }\n\n return {\n kind: \"number\",\n value: Number.isNaN(value)\n ? \"NaN\"\n : value === Number.POSITIVE_INFINITY\n ? \"Infinity\"\n : \"-Infinity\"\n };\n }\n\n if (typeof value === \"bigint\") return { kind: \"bigint\", value: String(value) };\n\n if (Array.isArray(value)) {\n const reference = serializeHeapReference(value, path, state);\n if (reference !== undefined) {\n return reference;\n }\n\n return withSerializableContainer(value, path, state, () =>\n value.map((entry, index) => serializeValue(entry, `${path}[${index}]`, state))\n );\n }\n\n if (isRuntimeClosureValue(value)) {\n return {\n kind: \"fn\",\n astNodeId: value.astNodeId,\n capturedScopeId: value.capturedScopeId\n };\n }\n\n if (isSandboxGenerator(value)) {\n if (value.state === \"done\") {\n return {\n kind: \"generator\",\n state: \"done\",\n ...(value.async ? { async: true } : {})\n };\n }\n\n if (value.state === \"suspended\" || value.state === \"running\") {\n const continuation = value.channel.snapshot();\n if (continuation.yieldNodeId === undefined) {\n throw new UnsnapshotableValueError(path);\n }\n if (value.astNodeId === undefined || value.capturedScopeId === undefined) {\n throw new TypeError(`Cannot serialize generator without origin metadata at ${path}.`);\n }\n return {\n kind: \"generator\",\n state: \"suspended\",\n ...(value.async ? { async: true } : {}),\n astNodeId: value.astNodeId,\n capturedScopeId: value.capturedScopeId,\n yieldNodeId: continuation.yieldNodeId,\n sent: serializeValue(continuation.sent as RuntimeSnapshotValue, `${path}.sent`, state)\n };\n }\n\n if (value.astNodeId === undefined || value.capturedScopeId === undefined) {\n throw new TypeError(`Cannot serialize generator without origin metadata at ${path}.`);\n }\n\n return {\n kind: \"generator\",\n state: \"start\",\n ...(value.async ? { async: true } : {}),\n astNodeId: value.astNodeId,\n capturedScopeId: value.capturedScopeId\n };\n }\n\n if (isRuntimePromiseValue(value)) {\n return {\n kind: \"promise\",\n id: value.id\n };\n }\n\n if (isSandboxRegex(value)) {\n const reference = serializeHeapReference(value, path, state);\n if (reference !== undefined) return reference;\n if (typeof value.lastIndex !== \"number\") throw new TypeError(`Missing regex heap reference at ${path}.`);\n return { kind: \"regex\", source: value.source, flags: value.flags, lastIndex: value.lastIndex };\n }\n\n if (isSandboxSharedArrayBuffer(value) || isSandboxDataView(value) || isSandboxArrayBuffer(value) || isSandboxBox(value) || isSandboxDate(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxRegExpIterator(value) || isSandboxCollectionIterator(value) || isNumericTypedArray(value)) {\n const reference = serializeHeapReference(value, path, state);\n if (reference === undefined) {\n throw new TypeError(`Cannot serialize collection without a heap reference at ${path}.`);\n }\n return reference;\n }\n\n if (!isPlainObject(value)) {\n throw new TypeError(`Cannot serialize host reference at ${path}.`);\n }\n\n const reference = serializeHeapReference(value, path, state);\n if (reference !== undefined) {\n return reference;\n }\n\n const serialized = Object.create(null) as Record<string, SerializedSnapshotValue>;\n\n return withSerializableContainer(value, path, state, () => {\n for (const [key, entry] of Object.entries(value)) {\n serialized[key] = serializeValue(entry, `${path}.${key}`, state);\n }\n\n return serialized;\n });\n}\n\nfunction serializeHeapReference(\n value:\n | SandboxBox\n | RuntimeSnapshotValue[]\n | Record<string, RuntimeSnapshotValue>\n | SandboxMap\n | SandboxSet\n | SandboxRegex\n | SandboxCollectionIterator\n | SandboxRegExpIterator\n | Date\n | NumericTypedArray\n | ArrayBufferLike | DataView<ArrayBufferLike>,\n path: string,\n state: SerializationState\n): SerializedReferenceValue | undefined {\n const id = state.heapIds.get(value);\n if (id === undefined) {\n return undefined;\n }\n\n if (!state.serializedHeapIds.has(id)) {\n state.serializedHeapIds.add(id);\n\n if (isSandboxRegex(value)) {\n state.heap[String(id)] = { kind: \"regex-object\", source: value.source, flags: value.flags,\n lastIndex: serializeValue(value.lastIndex as RuntimeSnapshotValue, `${path}.lastIndex`, state),\n ...serializeRegexProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<regex-property>`, state)) };\n } else if (isSandboxRegExpIterator(value)) {\n const snapshot = regexpIteratorState(value);\n const entries: Record<string, SerializedSnapshotValue> = Object.create(null);\n state.heap[String(id)] = {\n kind: \"regexp-iterator\", matcher: serializeValue(snapshot.matcher as RuntimeSnapshotValue, `${path}.<matcher>`, state),\n ...(snapshot.global === undefined ? {} : { global: snapshot.global, unicode: snapshot.unicode }),\n input: serializeValue(snapshot.input, `${path}.<input>`, state), exhausted: snapshot.exhausted, entries,\n symbolEntries: serializeSymbolProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.[symbol]`, state))\n };\n for (const [key, entry] of Object.entries(value)) entries[key] = serializeValue(entry as RuntimeSnapshotValue, `${path}.${key}`, state);\n } else if (isSandboxCollectionIterator(value)) {\n const snapshot = snapshotCollectionIterator(value);\n const entries: Record<string, SerializedSnapshotValue> = Object.create(null);\n state.heap[String(id)] = {\n kind: \"collection-iterator\", collectionKind: snapshot.collectionKind, method: snapshot.method,\n collection: serializeValue(snapshot.collection, `${path}.<collection>`, state),\n index: snapshot.index, exhausted: snapshot.exhausted, entries\n };\n for (const [key, entry] of Object.entries(value)) entries[key] = serializeValue(entry as RuntimeSnapshotValue, `${path}.${key}`, state);\n } else if (isSandboxBox(value)) {\n state.heap[String(id)] = encodeBoxedData(value, (entry, key) => serializeValue(entry as RuntimeSnapshotValue, `${path}.${key}`, state));\n } else if (isSandboxDate(value)) {\n state.heap[String(id)] = serializeDate(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<date-property>`, state));\n } else if (isSandboxDataView(value)) {\n state.heap[String(id)] = { ...encodeDataViewLayout(value),\n buffer: serializeHeapReference(dataViewBuffer(value), `${path}.buffer`, state)!,\n state: captureDataViewState(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<view>`, state)) };\n } else if (isSandboxSharedArrayBuffer(value)) {\n state.sharedBlocks??=new WeakMap();\n state.heap[String(id)]={...encodeSharedArrayBufferStorage(value,id,state.sharedBlocks,id=>({kind:\"ref\" as const,id})),\n state:captureArrayBufferState(value,entry=>serializeValue(entry as RuntimeSnapshotValue,`${path}.<buffer>`,state))};\n } else if (isSandboxArrayBuffer(value)) {\n state.heap[String(id)] = { ...encodeArrayBufferStorage(value, id, state.float32Buffers, id => ({ kind: \"ref\" as const, id })),\n state: captureArrayBufferState(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<buffer>`, state)) };\n } else if (isNumericTypedArray(value)) {\n const storage = typedArrayStorage(value);\n state.heap[String(id)] = { ...encodeTypedArrayLayout(value),\n buffer: serializeHeapReference(storage.buffer, `${path}.buffer`, state)!, entries: {},\n state: captureTypedArrayState(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<typed-array>`, state)) };\n } else if (isSandboxArguments(value)) {\n state.heap[String(id)] = serializeArguments(value, (entry, key) =>\n serializeValue(entry as RuntimeSnapshotValue, `${path}.${key}`, state)\n );\n } else if (isSandboxMap(value)) {\n state.heap[String(id)] = {\n kind: \"map\",\n ...serializeCollectionProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<property>`, state)),\n entries: [...value.entries].map(([key, entry], index) => [\n serializeValue(key as RuntimeSnapshotValue, `${path}.entries[${index}][0]`, state),\n serializeValue(entry as RuntimeSnapshotValue, `${path}.entries[${index}][1]`, state)\n ])\n };\n } else if (isSandboxSet(value)) {\n state.heap[String(id)] = {\n kind: \"set\",\n ...serializeCollectionProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.<property>`, state)),\n values: [...value.values].map((entry, index) =>\n serializeValue(entry as RuntimeSnapshotValue, `${path}.values[${index}]`, state)\n )\n };\n } else if (Array.isArray(value)) {\n const array = serializeArray(value, (entry, key) =>\n serializeValue(entry as RuntimeSnapshotValue, `${path}[${key}]`, state)\n );\n state.heap[String(id)] = array;\n const symbols = serializeSymbolProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.[symbol]`, state));\n if (symbols.length > 0) array.symbolEntries = symbols;\n } else {\n const entries = Object.create(null) as Record<string, SerializedSnapshotValue>;\n const errorType = sandboxErrorTypes.get(value);\n const serializedObject: Extract<SerializedHeapValue, { kind: \"object\" }> = {\n kind: \"object\",\n ...(hasNullObjectPrototype(value) ? { sandboxNullPrototype: true as const } : {}),\n entries,\n ...(errorType === undefined ? {} : { errorType })\n };\n state.heap[String(id)] = serializedObject;\n\n for (const [key, entry] of Object.entries(value)) {\n entries[key] = serializeValue(entry, `${path}.${key}`, state);\n }\n const symbolKeys = ownSerializableSymbolKeys(value);\n if (symbolKeys.length > 0) {\n serializedObject.symbolEntries = serializeSymbolProperties(value, entry => serializeValue(entry as RuntimeSnapshotValue, `${path}.[symbol]`, state));\n }\n }\n }\n\n return {\n kind: \"ref\",\n id\n };\n}\n\nfunction isRuntimeClosureValue(value: unknown): value is RuntimeClosureValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n hasOwnProperty(value, \"kind\") &&\n value.kind === \"fn\" &&\n hasOwnProperty(value, \"astNodeId\") &&\n typeof value.astNodeId === \"number\" &&\n hasOwnProperty(value, \"capturedScopeId\") &&\n (typeof value.capturedScopeId === \"number\" || typeof value.capturedScopeId === \"string\")\n );\n}\n\nfunction isRuntimePromiseValue(value: unknown): value is RuntimePromiseValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n hasOwnProperty(value, \"kind\") &&\n value.kind === \"promise\" &&\n hasOwnProperty(value, \"id\")\n );\n}\n\nfunction isPlainObject(value: object): value is Record<string, RuntimeSnapshotValue> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction hasOwnProperty<Name extends PropertyKey>(\n value: object,\n name: Name\n): value is Record<Name, unknown> {\n return Object.prototype.hasOwnProperty.call(value, name);\n}\n\nfunction withSerializableContainer<TValue>(\n value: object,\n path: string,\n state: SerializationState,\n serializeContainer: () => TValue\n): TValue {\n const ancestorPath = state.ancestors.get(value);\n if (ancestorPath !== undefined) {\n throw new TypeError(`Cannot serialize cyclic value at ${path}.`);\n }\n\n state.ancestors.set(value, path);\n\n try {\n return serializeContainer();\n } finally {\n state.ancestors.delete(value);\n }\n}\n\nfunction indexHeapContainers(input: SerializeInput): Pick<SerializationState, \"heapIds\" | \"guestValues\" | \"weakEntries\" | \"weakTargets\" | \"finalizationTargets\"> {\n const stats = new Map<\n object,\n {\n count: number;\n cyclic: boolean;\n expanded: boolean;\n forceHeap?: boolean;\n }\n >();\n const ancestors = new WeakSet<object>();\n const guestValues = new Set<object>();\n const weakEntries = new Map<object, Array<[WeakCollectionKey, unknown]>>();\n const seenSymbols = new Set<symbol>();\n type Contribution = { owner: object; key: WeakCollectionKey; value: unknown; depth: number };\n const waiting = new Map<WeakCollectionKey, Contribution[]>();\n const ready: Contribution[] = [];\n const reached = (value: WeakCollectionKey, depth: number) => {\n if (typeof value === \"symbol\") {\n if (seenSymbols.has(value)) return;\n seenSymbols.add(value);\n }\n const unlocked = waiting.get(value);\n if (unlocked !== undefined) {\n for (const contribution of unlocked) ready.push(contribution);\n waiting.delete(value);\n }\n if (typeof value === \"symbol\") return;\n const weakState = weakCollectionStates.get(value);\n if (weakState === undefined) return;\n weakEntries.set(value, []);\n for (const reference of weakState.references) {\n const key = reference.deref();\n if (key === undefined) continue;\n const entry = weakState.entries.get(key);\n if (entry === undefined) continue;\n const contribution = { owner: value, key, value: weakState.kind === \"map\" ? entry.value : undefined, depth: depth + 1 };\n if (typeof key === \"symbol\" ? seenSymbols.has(key) || Object.values(wellKnownSymbols).includes(key) : stats.has(key)) ready.push(contribution);\n else {\n const pending = waiting.get(key);\n if (pending === undefined) waiting.set(key, [contribution]);\n else pending.push(contribution);\n }\n }\n };\n\n for (const scope of input.scopeChain) {\n for (const value of Object.values(scope.bindings)) {\n collectContainerStats(value, stats, ancestors, guestValues, 0, reached);\n }\n }\n\n for (const promise of input.pendingPromises) {\n for (const [key, value] of Object.entries(promise)) {\n if (key === \"id\" || key === \"promise\") {\n continue;\n }\n\n collectContainerStats(value as RuntimeSnapshotValue, stats, ancestors, guestValues, 0, reached);\n }\n }\n\n for (let index = 0; index < ready.length; index++) {\n const contribution = ready[index]!;\n weakEntries.get(contribution.owner)!.push([contribution.key, contribution.value]);\n if (typeof contribution.key === \"object\") stats.get(contribution.key)!.forceHeap = true;\n collectContainerStats(contribution.value, stats, ancestors, guestValues, contribution.depth, reached);\n if (contribution.value !== null && typeof contribution.value === \"object\") {\n const stat = stats.get(contribution.value);\n if (stat !== undefined) stat.forceHeap = true;\n }\n }\n const weakTargets = new Map<object, object | symbol>();\n const finalizationTargets = new Map<object, Array<{target?:object | symbol;token?:object | symbol}>>();\n const reachableWeakTarget = (target: object | symbol | undefined): object | symbol | undefined => {\n if (typeof target === \"symbol\") return seenSymbols.has(target) || Object.values(wellKnownSymbols).includes(target) ? target : undefined;\n if (target === undefined || !stats.has(target)) return undefined;\n stats.get(target)!.forceHeap = true;\n return target;\n };\n for (const value of guestValues) {\n const target = reachableWeakTarget(weakReferenceStates.get(value)?.deref());\n if (target !== undefined) weakTargets.set(value,target);\n const finalization = finalizationRegistryStates.get(value);\n if (finalization !== undefined) finalizationTargets.set(value,[...finalization.state.cells].map(cell => ({\n target:reachableWeakTarget(cell.target.deref()),token:reachableWeakTarget(cell.token?.deref())\n })));\n }\n const heapIds = new Map<object | symbol, number>();\n let nextId = 1;\n for (const [value, stat] of stats.entries()) {\n if (\n stat.count > 1 ||\n stat.forceHeap === true ||\n guestValues.has(value) ||\n stat.cyclic ||\n hasNullObjectPrototype(value) ||\n ownSerializableSymbolKeys(value).length > 0 ||\n (isSandboxRegex(value) && (hasCustomRegexProperties(value) || !Number.isSafeInteger(value.lastIndex) ||\n (typeof value.lastIndex === \"number\" && value.lastIndex < 0) || Object.is(value.lastIndex, -0))) ||\n isSandboxBox(value) ||\n isSandboxDate(value) ||\n isNumericTypedArray(value) ||\n isSandboxArrayBuffer(value) ||\n isSandboxSharedArrayBuffer(value) ||\n isSandboxDataView(value) ||\n (Array.isArray(value) && requiresArrayEntries(value)) ||\n sandboxErrorTypes.has(value) ||\n isSandboxArguments(value) ||\n isSandboxCollectionIterator(value) ||\n isSandboxRegExpIterator(value) ||\n isSandboxMap(value) ||\n isSandboxSet(value)\n ) {\n heapIds.set(value, nextId);\n nextId += 1;\n }\n }\n\n return { heapIds, guestValues, weakEntries, weakTargets, finalizationTargets };\n}\n\nfunction collectContainerStats(\n value: unknown,\n stats: Map<object, { count: number; cyclic: boolean; expanded: boolean; forceHeap?: boolean }>,\n ancestors: WeakSet<object>,\n guestValues: Set<object>,\n depth = 0,\n reached?: (value: WeakCollectionKey, depth: number) => void\n): void {\n if (typeof value === \"symbol\") {\n reached?.(value, depth);\n return;\n }\n if (\n value === null ||\n typeof value !== \"object\" ||\n isRuntimeClosureValue(value) ||\n isRuntimePromiseValue(value) ||\n (isSandboxGenerator(value) && getGeneratorOrigin(value) === undefined)\n ) {\n return;\n }\n\n assertSnapshotDataDepth(depth, \"<snapshot-heap>\");\n let stat = stats.get(value);\n if (stat === undefined) {\n stat = {\n count: 0,\n cyclic: false,\n expanded: false\n };\n stats.set(value, stat);\n reached?.(value, depth);\n }\n\n stat.count += 1;\n\n if (ancestors.has(value)) {\n stat.cyclic = true;\n return;\n }\n\n if (stat.expanded) {\n return;\n }\n\n stat.expanded = true;\n ancestors.add(value);\n\n const guestEntries: unknown[] = [];\n if (isSandboxDataView(value)) guestEntries.push(dataViewBuffer(value));\n if (isNumericTypedArray(value)) guestEntries.push(typedArrayStorage(value).buffer);\n const guest = isSandboxDataView(value)\n ? { kind: \"dataview\", state: captureDataViewState(value, entry => { guestEntries.push(entry); return null; }) }\n : isNumericTypedArray(value)\n ? { kind: \"float32array\", state: captureTypedArrayState(value, entry => { guestEntries.push(entry); return null; }) }\n : isSandboxArrayBuffer(value) || isSandboxSharedArrayBuffer(value)\n ? { kind: \"arraybuffer\", state: captureArrayBufferState(value, entry => { guestEntries.push(entry); return null; }) }\n : captureGuestHeapNode(value, entry => { guestEntries.push(entry); return null; });\n if (guest !== undefined) {\n if (!isNumericTypedArray(value) && !isSandboxArrayBuffer(value) && !isSandboxSharedArrayBuffer(value) && !isSandboxDataView(value)) guestValues.add(value);\n for (const entry of guestEntries) {\n collectContainerStats(entry, stats, ancestors, guestValues, depth + 1, reached);\n if (entry !== null && typeof entry === \"object\") {\n const entryStat = stats.get(entry);\n if (entryStat !== undefined) entryStat.forceHeap = true;\n }\n }\n ancestors.delete(value);\n return;\n }\n\n if (!Array.isArray(value) && !isPlainObject(value) && !isSandboxDate(value) &&\n !isNumericTypedArray(value) && !isSandboxMap(value) && !isSandboxCollectionIterator(value) &&\n !isSandboxRegExpIterator(value) && !isSandboxSet(value)) {\n ancestors.delete(value);\n return;\n }\n\n const entries = isSandboxRegex(value)\n ? Reflect.ownKeys(getRegexProperties(value)).flatMap(key => {\n const descriptor = Object.getOwnPropertyDescriptor(getRegexProperties(value), key)!;\n return \"value\" in descriptor ? [descriptor.value] : [];\n })\n : isSandboxDate(value)\n ? dateDataProperties(value).flatMap(([key, descriptor]) => typeof key === \"string\" ? [descriptor.value] : [])\n : isSandboxBox(value)\n ? boxedDataProperties(value).map(([, descriptor]) => descriptor.value)\n : isSandboxRegExpIterator(value)\n ? [regexpIteratorState(value).matcher, regexpIteratorState(value).input, ...Object.values(value)]\n : isSandboxCollectionIterator(value)\n ? [collectionIteratorState(value).collection, ...Object.values(value)]\n : isSandboxArguments(value)\n ? Object.values(Object.getOwnPropertyDescriptors(value)).flatMap((descriptor) =>\n \"value\" in descriptor ? [descriptor.value] : []\n )\n : isSandboxMap(value)\n ? [...value.entries].flatMap(([key, entry]) => [key, entry])\n : isSandboxSet(value)\n ? [...value.values]\n : Object.values(value);\n if (isSandboxMap(value) || isSandboxSet(value)) {\n serializeCollectionProperties(value, entry => {\n entries.push(entry);\n return null;\n });\n }\n for (const entry of entries) {\n collectContainerStats(entry, stats, ancestors, guestValues, depth + 1, reached);\n }\n for (const key of ownSerializableSymbolKeys(value)) {\n collectContainerStats(key, stats, ancestors, guestValues, depth + 1, reached);\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\"value\" in descriptor)\n collectContainerStats(descriptor.value, stats, ancestors, guestValues, depth + 1, reached);\n }\n\n ancestors.delete(value);\n}\n", "import { collectionIteratorState, isSandboxCollectionIterator } from \"../interp/collection-iterator.js\";\nimport { regexpIteratorState, isSandboxRegExpIterator } from \"../interp/regexp-iterator.js\";\nimport {\n createSandboxPromise,\n createSandboxClosure,\n isSandboxClosure,\n isSandboxMap,\n isSandboxSet,\n isSandboxPromise,\n promiseProperties,\n type SandboxClosure,\n type SandboxPromise,\n type SandboxValue\n} from \"../interp/values.js\";\nimport { createReplayEncodingContext, decodeReplayData, encodeReplayData, type ReplayData, type ReplayPathSegment } from \"./replay-data.js\";\nimport { CompileScope } from \"../interp/regex/compile-guard.js\";\nimport { ownSerializableSymbolKeys } from \"./symbols.js\";\nimport { isSandboxModuleNamespace } from \"../interp/module-namespace.js\";\nimport { validateSnapshotData } from \"./validation.js\";\n\n\nexport type ReplayInputs = {\n bindings: Record<string, SandboxValue>;\n imports: Record<string, SandboxValue>;\n entryPointArgs: SandboxValue[] | undefined;\n importMeta: SandboxValue;\n moduleNamespaces?: Record<string,SandboxValue>;\n};\n\ntype ModuleReplayInputs = {namespace: Record<string,SandboxValue>};\n\nexport function prepareReplayInputs<T extends ReplayInputs | ModuleReplayInputs>(\n current: T,\n saved?: unknown,\n preparePromise?: (promise: SandboxPromise | undefined, id: string) => SandboxPromise,\n onCapabilityRestored?: (original: SandboxClosure, restored: SandboxClosure) => void,\n compilation?: CompileScope,\n onInputSymbols?: (symbols: ReadonlyMap<number, symbol>) => void\n): {\n values: T;\n snapshot: ReplayData;\n captureNamespace: (namespace: Record<string, SandboxValue>, name: string) => void;\n prepareNamespace: (namespace: Record<string, SandboxValue>, name: string) => Record<string, SandboxValue>;\n} {\n const identities = new WeakMap<object, string>();\n const capabilities = new Map<string, SandboxClosure>();\n const promises = new Map<string, SandboxPromise>();\n const namespaces: Record<string, SandboxValue> = Object.create(null);\n if (\"moduleNamespaces\" in current) Object.assign(namespaces, current.moduleNamespaces);\n const context = createReplayEncodingContext();\n const identifyCapability = (closure: SandboxClosure, path: readonly ReplayPathSegment[]) => {\n const id = identities.get(closure) ?? JSON.stringify(path);\n identities.set(closure, id);\n capabilities.set(id, closure);\n return id;\n };\n const inputPromises = new Map<string, SandboxPromise>();\n const identifyPromise = (promise: SandboxPromise, path: readonly ReplayPathSegment[]) => {\n if (preparePromise === undefined) return undefined;\n const id = identities.get(promise) ?? JSON.stringify(path);\n identities.set(promise, id);\n inputPromises.set(id, promise);\n return id;\n };\n const readCapability = (id: string): SandboxValue => {\n const path: unknown = JSON.parse(id);\n if (!Array.isArray(path) || path.length === 0)\n throw new TypeError(\"Invalid replay input capability path.\");\n let value: SandboxValue = { ...current, moduleNamespaces: namespaces };\n for (const key of path) {\n if (typeof key !== \"string\") {\n if (key === null || typeof key !== \"object\" || Array.isArray(key) ||\n Object.keys(key).length !== 1 || !Object.hasOwn(key, \"symbol\") ||\n !Number.isSafeInteger(key.symbol) || key.symbol < 0)\n throw new TypeError(\"Invalid replay input symbol capability path.\");\n if (value === null || typeof value !== \"object\") return undefined;\n const symbol = ownSerializableSymbolKeys(value)[key.symbol];\n if (symbol === undefined) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, symbol);\n if (descriptor === undefined || !(\"value\" in descriptor)) return undefined;\n value = descriptor.value;\n continue;\n }\n if (isSandboxRegExpIterator(value)) {\n if (key === \"<matcher>\") value = regexpIteratorState(value).matcher;\n else if (key === \"<input>\") value = regexpIteratorState(value).input;\n else {\n const property: unknown = JSON.parse(key);\n if (!Array.isArray(property) || property.length !== 2 || property[0] !== \"property\" || typeof property[1] !== \"string\") throw new TypeError(\"Invalid replay input iterator capability path.\");\n const descriptor = Object.getOwnPropertyDescriptor(value, property[1]);\n value = descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n }\n continue;\n }\n if (isSandboxCollectionIterator(value)) {\n if (key === \"<collection>\") value = collectionIteratorState(value).collection;\n else {\n const property: unknown = JSON.parse(key);\n if (!Array.isArray(property) || property.length !== 2 || property[0] !== \"property\" || typeof property[1] !== \"string\") throw new TypeError(\"Invalid replay input iterator capability path.\");\n const descriptor = Object.getOwnPropertyDescriptor(value, property[1]);\n value = descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n }\n continue;\n }\n if (isSandboxMap(value)) {\n const parts = key.split(\":\");\n const [kind, ordinal] = parts;\n const index = Number(ordinal);\n if (\n parts.length !== 2 ||\n ![\"key\", \"value\"].includes(kind) ||\n String(index) !== ordinal ||\n !Number.isSafeInteger(index) ||\n index < 0\n )\n throw new TypeError(\"Invalid replay input map capability path.\");\n value = [...value.entries][index]?.[kind === \"key\" ? 0 : 1];\n continue;\n }\n if (isSandboxSet(value)) {\n const index = Number(key);\n if (String(index) !== key || !Number.isSafeInteger(index) || index < 0)\n throw new TypeError(\"Invalid replay input set capability path.\");\n value = [...value.values][index];\n continue;\n }\n if (key === \"properties\" && isSandboxClosure(value)) {\n value = value.properties;\n continue;\n }\n if (key === \"properties\" && isSandboxPromise(value)) {\n value = promiseProperties.get(value);\n continue;\n }\n if (value === null || typeof value !== \"object\") return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !(\"value\" in descriptor)) return undefined;\n value = descriptor.value;\n }\n return value;\n };\n const resolveCapability = (id: string) => {\n const value = saved === undefined ? capabilities.get(id) : readCapability(id);\n return isSandboxClosure(value) ? value : undefined;\n };\n const memo = { nodes: context.nodes, values: new Map<number, SandboxValue>() };\n if (saved !== undefined) validateSnapshotData(saved);\n const snapshot = saved === undefined ? encodeReplayData(current, {\n context, captureCapabilityProperties: true, identifyCapability, identifyPromise,\n onValueEncoded: (id, value) => { memo.values.set(id, value); }\n }) : structuredClone(saved) as ReplayData;\n if (saved !== undefined) {\n const validationScope = new CompileScope(compilation?.owner);\n try {\n const validated = decodeReplayData(snapshot, {\n resolveCapability,\n resolvePromise: id => { readCapability(id); return createSandboxPromise(Promise.resolve(undefined), { trackReplay: false }); }\n }, validationScope);\n assertReplayInputShape(validated, \"namespace\" in current);\n if (snapshot.namespaceRoots !== undefined) {\n if (snapshot.namespaceRoots === null || typeof snapshot.namespaceRoots !== \"object\" || Array.isArray(snapshot.namespaceRoots))\n throw new TypeError(\"Invalid replay namespace roots.\");\n const validationCapability = createSandboxClosure({ call: () => undefined });\n for (const root of Object.values(snapshot.namespaceRoots)) {\n const namespace = decodeReplayData({ root, nodes: snapshot.nodes }, {\n resolveCapability: id => { readCapability(id); return validationCapability; },\n resolvePromise: id => { readCapability(id); return createSandboxPromise(Promise.resolve(undefined), { trackReplay: false }); }\n }, validationScope);\n if (!isSandboxModuleNamespace(namespace)) throw new TypeError(\"Invalid replay module namespace.\");\n }\n }\n } finally {\n validationScope.dispose();\n }\n context.nodes = snapshot.nodes;\n memo.nodes = snapshot.nodes;\n }\n const inputSymbols = new Map<number, symbol>();\n for (let id = 0; id < snapshot.nodes.length; id++) {\n if (snapshot.nodes[id]?.kind !== \"symbol\") continue;\n const symbol = decodeReplayData({ root: { tag: \"ref\", id }, nodes: snapshot.nodes }, { memo }, compilation);\n if (typeof symbol !== \"symbol\") throw new TypeError(\"Invalid input symbol.\");\n inputSymbols.set(id, symbol);\n }\n onInputSymbols?.(inputSymbols);\n const resolvePromise = (id: string) => {\n const value = saved === undefined ? inputPromises.get(id) : readCapability(id);\n if (!promises.has(id) && preparePromise !== undefined)\n promises.set(id, preparePromise(isSandboxPromise(value) ? value : undefined, id));\n return promises.get(id);\n };\n if (inputPromises.size > 0) {\n memo.values.clear();\n for (const [id, symbol] of inputSymbols) memo.values.set(id, symbol);\n }\n const values = saved === undefined && inputPromises.size === 0 ? current\n : decodeReplayData(snapshot, { memo, resolveCapability, resolvePromise, onCapabilityRestored }, compilation) as T;\n const captureNamespace = (namespace: Record<string, SandboxValue>, name: string) => {\n if (!Object.hasOwn(namespaces, name)) namespaces[name] = namespace;\n if (snapshot.namespaceRoots !== undefined && Object.hasOwn(snapshot.namespaceRoots, name)) return;\n if (!isSandboxModuleNamespace(namespace)) throw new TypeError(\"Invalid replay module namespace.\");\n const encoded = encodeReplayData(namespace, {\n context, path: [\"moduleNamespaces\", name], captureCapabilityProperties: true,\n identifyCapability, identifyPromise\n });\n snapshot.namespaceRoots ??= Object.create(null) as NonNullable<ReplayData[\"namespaceRoots\"]>;\n Object.defineProperty(snapshot.namespaceRoots, name, {\n value: encoded.root, enumerable: true, configurable: true, writable: true\n });\n };\n return {\n values, snapshot, captureNamespace,\n prepareNamespace: (namespace, name) => {\n captureNamespace(namespace, name);\n return decodeReplayData({ root: snapshot.namespaceRoots![name], nodes: snapshot.nodes },\n { memo, resolveCapability, resolvePromise, onCapabilityRestored }, compilation) as Record<string, SandboxValue>;\n }\n };\n}\n\nfunction assertReplayInputShape(restored: SandboxValue, moduleInput: boolean): void {\n if (\n restored === null ||\n typeof restored !== \"object\" ||\n Array.isArray(restored) ||\n isSandboxClosure(restored) ||\n isSandboxPromise(restored) ||\n isSandboxCollectionIterator(restored) ||\n isSandboxRegExpIterator(restored) ||\n isSandboxMap(restored) ||\n isSandboxSet(restored)\n )\n throw new TypeError(\"Invalid replay inputs.\");\n const values = restored as Record<string,SandboxValue>;\n for (const key of moduleInput ? [\"namespace\"] : [\"bindings\", \"imports\", ...(values.moduleNamespaces===undefined ? [] : [\"moduleNamespaces\"])]) {\n if (\n values[key] === null ||\n typeof values[key] !== \"object\" ||\n Array.isArray(values[key]) ||\n isSandboxClosure(values[key]) ||\n isSandboxPromise(values[key]) ||\n isSandboxCollectionIterator(values[key]) ||\n isSandboxRegExpIterator(values[key]) ||\n isSandboxMap(values[key]) ||\n isSandboxSet(values[key])\n )\n throw new TypeError(`Invalid replay input ${key}.`);\n }\n if (values.entryPointArgs !== undefined && !Array.isArray(values.entryPointArgs))\n throw new TypeError(\"Invalid replay entry point arguments.\");\n const namespaces = moduleInput ? [values.namespace]\n : Object.values((values.moduleNamespaces ?? {}) as Record<string,SandboxValue>);\n if (namespaces.some(namespace=>!isSandboxModuleNamespace(namespace)))\n throw new TypeError(\"Invalid replay module namespace.\");\n}\n", "import type {SourceResolver} from \"./modules/source-graph.js\";\nimport { createHostCallbackContext } from \"#safe-js-platform\";\nimport { attachExecutionControl, SandboxJobQueue, type ExecutionControl } from \"./interp/jobs.js\";\nimport { runWithExtensions, type RealmOptions } from \"./realm.js\";\n\nimport { hashParsedAst, hashSource } from \"./parse/hash.js\";\nimport { runResources, withRunResources } from \"./interp/resources.js\";\nimport { createReplayableRandom } from \"./random.js\";\nimport {\n attachErrorSpan,\n describeThrownValue,\n materializeWrappedErrorCause,\n replaceErrorStack,\n type ErrorSourceSpan\n} from \"./error/shape.js\";\nimport type { ParseResult } from \"./parse.js\";\nimport {\n findRegexLiteral,\n parseExecutableModule,\n type AwaitExpression,\n type CallExpression,\n type Identifier,\n type Module,\n type SourceSpan,\n type Statement\n} from \"./parse/parser.js\";\nimport { restore, type SafeJSSnapshot } from \"./restore.js\";\nimport { Budget, type CompileTicket } from \"./interp/budget.js\";\nimport { CompileScope } from \"./interp/regex/compile-guard.js\";\nimport {\n PromiseReplay,\n promiseReplayContext,\n type PromiseReplaySnapshot\n} from \"./interp/promise-replay.js\";\nimport { wrapCancelableBindings } from \"./interp/cancel.js\";\nimport { enterSnapshotRun } from \"./interp/running-state.js\";\nimport {\n createSandboxPromiseRejectionTracker,\n observeSandboxPromise,\n withSandboxPromiseRejectionTracker,\n type SandboxPromiseRejectionTracker\n} from \"./interp/promise-tracker.js\";\nimport {\n HostCallJournal,\n type HostCallRecord,\n type HostCallReplay,\n type HostCallResumeProvider\n} from \"./interp/host-call.js\";\nimport type { ConsoleSink } from \"./interp/globals/console-json.js\";\nimport { createBuiltinBindings } from \"./interp/globals.js\";\nimport { releaseObjectPrototype } from \"./interp/object-model.js\";\nimport {\n declareHostOperation,\n wrapCallerInjectedBindings,\n type CallerInjectedBinding\n} from \"./interp/host-bridge.js\";\nimport {\n interpret,\n Scope,\n type InterpreterResult,\n type LoopIterationSnapshot\n} from \"./interp/interpreter.js\";\nimport { consumeSettledHostCall } from \"./interp/promise.js\";\nimport {\n deepCopyToSandbox,\n isSandboxClosure,\n isSandboxPromise,\n measureSandboxData,\n reconcileCompiledValues,\n type SandboxValue,\n type SandboxPromise\n} from \"./interp/values.js\";\nimport { createModuleEnvironment, resolveModuleImports, resolveModuleNamespace, type ModuleEnvironment, type ModuleEnvironmentOptions, type ModuleRegistry } from \"./modules/registry.js\";\nimport { createModuleNamespace } from \"./interp/module-namespace.js\";\nimport {\n activateOtelSink,\n getActiveOtelSpan,\n safeAddEvent,\n type OtelSink\n} from \"./observability/otel.js\";\nimport type { SnapshotBackend } from \"./snapshot/backend.js\";\nimport { attachDumpController, createDumpController } from \"./snapshot/dump.js\";\nimport { DUMP_FORMAT_VERSION, EXECUTION_SEMANTICS, inMemoryRunSnapshots } from \"./snapshot/dump-format.js\";\nimport { createSnapshotScheduler, type SnapshotScheduler } from \"./snapshot/scheduler.js\";\nimport { UnsnapshotableValueError } from \"./snapshot/serialize.js\";\nimport { prepareReplayInputs, type ReplayInputs } from \"./snapshot/replay-inputs.js\";\nimport {\n decodeReplayData,\n MissingReplayCapabilityError,\n type ReplayData\n} from \"./snapshot/replay-data.js\";\n\nexport type RunOptions = {\n importSpecifiers?: readonly string[];\n sourceType?: \"module\";\n sourceResolver?: SourceResolver;\n sourceRoot?: string;\n extensions?: RealmOptions[\"extensions\"];\n builtinOverrides?: RealmOptions[\"builtinOverrides\"];\n grants?: RealmOptions[\"grants\"];\n limits?: RealmOptions[\"limits\"];\n bindings?: Record<string, CallerInjectedBinding>;\n budget?: Budget;\n clock?: RunClock;\n entryPointArgs?: readonly unknown[];\n filename?: string;\n /** Trusted diagnostic mapping; re-supply when resuming a snapshot. Does not change source or execution. */\n sourceLocation?: (position: { line: number; column: number }) => { filename: string; line: number; column: number } | undefined;\n importMeta?: Record<string, unknown>;\n hostCallResumeProvider?: HostCallResumeProvider;\n modules?: ModuleRegistry;\n random?: RunRandom;\n randomSeed?: number;\n otelSink?: OtelSink;\n signal?: AbortSignal;\n snapshot?: SafeJSSnapshot;\n snapshotBackend?: SnapshotBackend;\n snapshotIntervalMs?: number;\n snapshotPath?: string;\n sink?: ConsoleSink;\n};\n\nexport class UnhandledRejectionError extends Error {\n readonly reason: unknown;\n\n constructor(reason: unknown, span?: ErrorSourceSpan) {\n super(`Unhandled rejection: ${describeThrownValue(reason)}`);\n this.name = \"UnhandledRejectionError\";\n this.reason = reason;\n attachErrorSpan(this, span);\n replaceErrorStack(this);\n }\n}\n\nexport type RunSnapshot = SafeJSSnapshot & {\n bindings: InterpreterResult[\"snapshot\"][\"bindings\"];\n clock?: RunClockSnapshot;\n hostCalls?: HostCallRecord[];\n replay?: HostCallReplay;\n replayError?: string;\n promiseReplay?: PromiseReplaySnapshot;\n initialInputs?: ReplayData;\n loopIterations?: Record<string, LoopIterationSnapshot>;\n pendingAwaits?: RunPendingAwaitSnapshot[];\n random?: {\n seed: number;\n state: number;\n initialState?: number;\n resumeState?: number;\n };\n};\n\nexport type RunPendingAwaitSnapshot = {\n nodeId?: number;\n span: SourceSpan;\n};\n\nexport type RunClockSnapshot = {\n next: number;\n};\n\nexport type RunClock = {\n now?: () => number;\n restore?: (snapshot: RunClockSnapshot) => void;\n snapshot: () => RunClockSnapshot | undefined;\n};\n\nexport type RunRandom = {\n next: () => number;\n seed: number;\n snapshot: () => number;\n};\n\ntype WithRunSnapshot<TResult extends InterpreterResult> = TResult extends unknown\n ? Omit<TResult, \"snapshot\"> & {\n snapshot: RunSnapshot;\n }\n : never;\n\nexport type RunResult = WithRunSnapshot<InterpreterResult>;\nexport type RunPromise = Promise<RunResult> & ExecutionControl;\n\nconst DEFAULT_MAX_CALL_DEPTH = 1_000;\n\nexport function run(source: string, options: RunOptions = {}): RunPromise {\n const jobs = new SandboxJobQueue();\n if (options.extensions !== undefined || options.builtinOverrides !== undefined || options.sourceType !== undefined || options.sourceResolver !== undefined || options.sourceRoot !== undefined) {\n const result = (async () => {\n if (options.sourceType === undefined && (options.sourceResolver !== undefined || options.sourceRoot !== undefined))\n throw new TypeError(\"Source resolution requires sourceType: 'module'.\");\n if (options.sourceRoot !== undefined) {\n if (options.sourceResolver !== undefined) throw new TypeError(\"Specify sourceRoot or sourceResolver, not both.\");\n const {createRootedSourceResolver} = await import(\"./modules/source-files.js\");\n const {sourceRoot, ...resolved} = options;\n const sourceResolver = await createRootedSourceResolver(sourceRoot);\n return runWithExtensions(source,{...resolved,filename:await sourceResolver.entryId(options.filename),sourceResolver},jobs);\n }\n return runWithExtensions(source, options, jobs);\n })().finally(() => jobs.finish());\n const dumpController = createDumpController();\n dumpController.fail(new TypeError(\"Snapshot is not replayable: Live realm state cannot be serialized or replayed.\"));\n return attachExecutionControl(attachDumpController(result, dumpController), jobs, options.signal);\n }\n let capturePausedSnapshot: (() => RunSnapshot) | undefined;\n const lifecycle = {\n hostCallbackDepth: 0,\n hostCallbackContext: createHostCallbackContext()\n };\n const dumpController = createDumpController(lifecycle, {\n isPaused: () => jobs.executionState === \"paused\",\n snapshot: () => capturePausedSnapshot?.()\n });\n const promiseTracker = createSandboxPromiseRejectionTracker();\n const detachExecutionFailure = promiseTracker.onFatalRejection((error) => jobs.interrupt(error));\n let completedSnapshot: RunSnapshot | undefined;\n const execute = async () => {\n const budget = options.budget ?? new Budget({ maxCallDepth: DEFAULT_MAX_CALL_DEPTH });\n const operation = budget.acquireCompileOwner(true);\n const compilation = new CompileScope(operation.owner);\n try {\n const restoredSnapshot =\n options.snapshot === undefined\n ? undefined\n : restore(options.snapshot, { source,\n ...(options.importSpecifiers ? { importSpecifiers: options.importSpecifiers } : {}) }, operation.owner);\n const promiseReplay = new PromiseReplay(restoredSnapshot?.promiseReplay);\n return await promiseReplayContext.run(promiseReplay, async () => {\n const deactivateOtelSink = activateOtelSink(options.otelSink);\n let leaveSnapshotRun: (() => void) | undefined;\n let leaveHostReplay: (() => void) | undefined;\n let leaveInputReplay: (() => void) | undefined;\n let createFailureSnapshot: (() => RunSnapshot) | undefined;\n let cancellationSnapshot: RunSnapshot | undefined;\n let cancellationSnapshotError: { reason: unknown } | undefined;\n let snapshotScheduler: SnapshotScheduler<RunSnapshot> | undefined;\n const captureCancellationSnapshot = () => {\n try {\n cancellationSnapshot = createFailureSnapshot?.();\n } catch (reason) {\n cancellationSnapshotError = { reason };\n }\n };\n options.signal?.addEventListener(\"abort\", captureCancellationSnapshot, { once: true });\n try {\n const executionSemantics =\n restoredSnapshot?.executionSemantics === \"jobs-v6\" ||\n restoredSnapshot?.executionSemantics === \"jobs-v7\" ||\n restoredSnapshot?.executionSemantics === \"jobs-v8\"\n ? restoredSnapshot.executionSemantics\n : EXECUTION_SEMANTICS;\n const functionSourceText = executionSemantics === \"jobs-v8\" || executionSemantics === EXECUTION_SEMANTICS;\n runResources.getStore()!.functionSourceText = functionSourceText;\n runResources.getStore()!.hostDataMetadata = executionSemantics === EXECUTION_SEMANTICS;\n if (options.sourceLocation !== undefined) runResources.getStore()!.sourceLocation = options.sourceLocation;\n const convertInitialInput = <TValue>(convert: () => TValue): TValue =>\n executionSemantics === \"jobs-v6\" ? convert() : promiseReplayContext.exit(convert);\n if (restoredSnapshot !== undefined) {\n leaveSnapshotRun = enterSnapshotRun(options.snapshot ?? restoredSnapshot);\n }\n promiseReplay.attachBudget(budget);\n const filename = options.filename ?? \"<input>\";\n const module = parseExecutableModule(source, filename, operation.owner, options.importSpecifiers);\n promiseReplay.validateNodes(module);\n const sourceHash =\n findRegexLiteral(module) === undefined && options.importSpecifiers === undefined\n ? hashSource(source, operation.owner, functionSourceText)\n : hashParsedAst(module, functionSourceText);\n const hostCalls = new HostCallJournal(\n sourceHash,\n readHostCallSnapshot(restoredSnapshot),\n options.hostCallResumeProvider,\n restoredSnapshot?.replay,\n budget,\n operation.owner\n );\n leaveHostReplay = hostCalls.dispose.bind(hostCalls);\n promiseReplay.validateCallbacks(hostCalls.callbackPositions());\n const generator =\n options.random ??\n createReplayableRandom({ seed: options.randomSeed, snapshot: restoredSnapshot });\n const random = { seed: generator.seed, initialState: generator.snapshot(), generator };\n const interpreterSnapshot =\n restoredSnapshot?.replay === undefined && hasLoopIterationSnapshot(restoredSnapshot)\n ? {\n ...(restoredSnapshot as RunSnapshot),\n resumeNodeId: (restoredSnapshot as RunSnapshot).pendingAwaits?.[0]?.nodeId\n }\n : undefined;\n const callerBindings = convertInitialInput(() =>\n options.bindings === undefined\n ? {}\n : wrapCallerInjectedBindings(options.bindings, {\n budget,\n compileOwner: operation.owner,\n hostCalls,\n moduleId: \"<bindings>\",\n signal: options.signal,\n lifecycle\n })\n );\n const builtinBindings = createBuiltinBindings({\n compileOwner: operation.owner,\n budget,\n hostCalls,\n sink: options.sink,\n random: random?.generator.next,\n clock: options.clock\n });\n const importMeta = convertInitialInput(\n () => deepCopyToSandbox(options.importMeta ?? {}, { compilation }) as Record<string, SandboxValue>\n );\n if (restoredSnapshot?.migration !== undefined) {\n if (Object.hasOwn(importMeta, \"migration\"))\n throw new TypeError(\n \"import.meta.migration is reserved for migrated checkpoint state.\"\n );\n Object.defineProperty(importMeta, \"migration\", {\n value: decodeReplayData(restoredSnapshot.migration.state, {}, compilation),\n enumerable: true,\n configurable: true,\n writable: true\n });\n }\n const inputPromiseReplacements = new WeakMap<SandboxPromise, SandboxPromise>();\n const prepareInputPromise = (promise: SandboxPromise | undefined, id: string): SandboxPromise => {\n if (promise !== undefined) observeSandboxPromise(promise);\n const operation = declareHostOperation(() => {\n if (promise === undefined) throw new TypeError(`Missing initial promise '${id}'.`);\n return promise.promise;\n }, \"read-side-effect\");\n const binding = wrapCallerInjectedBindings({[id]:operation},{\n budget,hostCalls,moduleId:\"<inputs>\",compileOwner:compilation.owner,signal:options.signal,lifecycle,\n promiseReplacements: inputPromiseReplacements\n })[id]!;\n if (!isSandboxClosure(binding)) throw new TypeError(\"Invalid initial promise operation.\");\n const prepared = binding.call([]) as SandboxPromise;\n hostCalls.registerInputPromise(prepared);\n if (promise !== undefined) inputPromiseReplacements.set(promise, prepared);\n return prepared;\n };\n let moduleEnvironment: ModuleEnvironment | undefined;\n const moduleOptions: ModuleEnvironmentOptions = {budget,compileOwner:operation.owner,hostCalls,signal:options.signal};\n const moduleInputOwner = {};\n let moduleInputSize = 0;\n const initialInputs = prepareReplayInputs<ReplayInputs>(\n {\n bindings: callerBindings,\n imports: convertInitialInput(() => {\n const modules = options.modules;\n moduleEnvironment = createModuleEnvironment(modules, moduleOptions);\n return resolveModuleImports(module, modules, {\n environment: moduleEnvironment,\n budget,\n compileOwner: operation.owner,\n hostCalls,\n signal: options.signal,\n allowMissing: restoredSnapshot?.initialInputs !== undefined\n });\n }),\n entryPointArgs: convertInitialInput(() =>\n options.entryPointArgs === undefined\n ? undefined\n : (deepCopyToSandbox([...options.entryPointArgs], { compilation }) as SandboxValue[])\n ),\n importMeta\n },\n restoredSnapshot?.initialInputs,\n prepareInputPromise,\n hostCalls.rebindHostCapability.bind(hostCalls),\n compilation,\n hostCalls.registerInputSymbols.bind(hostCalls)\n );\n leaveInputReplay = () => {\n budget.setRetainedDataUsage(initialInputs,0);\n budget.setRetainedDataUsage(moduleInputOwner,0);\n };\n if (moduleEnvironment !== undefined) {\n moduleOptions.prepareNamespace = (namespace,name) => {\n const prepared = initialInputs.prepareNamespace(namespace,name);\n const included = new Set<CompileTicket>();\n const size = measureSandboxData([prepared],{ignoreClosureCaptures:true,compileTickets:included});\n budget.reconcileCompileData(moduleInputSize+size,included,included,moduleInputOwner);\n moduleInputSize += size;\n return prepared;\n };\n for (const name of Object.keys(initialInputs.snapshot.namespaceRoots ?? {})) {\n if (moduleEnvironment.available.includes(name)) resolveModuleNamespace(moduleEnvironment,name,false);\n else {\n moduleEnvironment.available.push(name);\n moduleEnvironment.namespaces[name] = createModuleNamespace({});\n }\n }\n for (const [name, namespace] of Object.entries(moduleEnvironment.namespaces))\n initialInputs.captureNamespace(namespace as Record<string,SandboxValue>,name);\n }\n hostCalls.validateHostCapabilities();\n const inputTickets = new Set<CompileTicket>();\n const inputSize = measureSandboxData(\n [\n ...Object.values(initialInputs.values.bindings),\n ...Object.values(initialInputs.values.imports),\n ...(initialInputs.values.entryPointArgs ?? []),\n initialInputs.values.importMeta\n ],\n { ignoreClosureCaptures: true, compileTickets: inputTickets }\n );\n budget.reconcileCompileData(inputSize, inputTickets, inputTickets, initialInputs);\n const entryPointArgs = initialInputs.values.entryPointArgs;\n const cancelableCallerBindings = wrapCancelableBindings(\n initialInputs.values.bindings,\n options.signal\n );\n\n const scope = new Scope(\n builtinBindings,\n undefined,\n undefined,\n { chargeData: false },\n interpreterSnapshot?.bindings as Record<string, SandboxValue> | undefined\n );\n const callerScope = scope.child(cancelableCallerBindings, {globalEnvironment: true});\n const executionScope = new Scope(\n initialInputs.values.imports,\n callerScope,\n initialInputs.values.importMeta,\n { functionBoundary: true }\n );\n executionScope.moduleEnvironment = moduleEnvironment;\n const activeSnapshotScheduler = createSnapshotScheduler<RunSnapshot>({\n snapshotBackend: options.snapshotBackend,\n snapshotIntervalMs: options.snapshotIntervalMs,\n snapshotPath: options.snapshotPath\n });\n snapshotScheduler = activeSnapshotScheduler;\n createFailureSnapshot = () =>\n createRunSnapshot({\n executionSemantics,\n migration: restoredSnapshot?.migration,\n bindings: executionScope.snapshot().bindings,\n clock: options.clock,\n hostCalls: hostCalls.snapshot(),\n replay: hostCalls.snapshotReplay(),\n initialInputs: initialInputs.snapshot,\n promiseReplay: promiseReplay.snapshot(),\n random,\n sourceHash\n });\n capturePausedSnapshot = createFailureSnapshot;\n let snapshotIteration = 0;\n\n const topLevelResult = await interpret(createExecutableNode(module), {\n jobs,\n compilation,\n budget,\n captureReplayState: random.generator.snapshot,\n onYield: (yieldPoint) => {\n snapshotIteration += 1;\n safeAddEvent(yieldPoint.otelSpan ?? getActiveOtelSpan(), \"snapshot.saved\", {\n iteration: snapshotIteration\n });\n let snapshot: RunSnapshot | undefined;\n const createSnapshot = () => {\n if (snapshot !== undefined) {\n return snapshot;\n }\n const interpreterSnapshot = yieldPoint.snapshot();\n snapshot = createRunSnapshot({\n executionSemantics,\n migration: restoredSnapshot?.migration,\n bindings: interpreterSnapshot.bindings,\n clock: options.clock,\n hostCalls: hostCalls.snapshot(),\n loopIterations: interpreterSnapshot.loopIterations,\n pendingAwaits: [createPendingAwaitSnapshot(yieldPoint)],\n replay: hostCalls.snapshotReplay(),\n initialInputs: initialInputs.snapshot,\n promiseReplay: promiseReplay.snapshot(),\n random,\n randomResumeState:\n typeof yieldPoint.replayState === \"number\" ? yieldPoint.replayState : undefined,\n sourceHash\n });\n return snapshot;\n };\n\n activeSnapshotScheduler.onYield(createSnapshot);\n dumpController.onYield(createSnapshot);\n },\n scope: executionScope,\n signal: options.signal,\n snapshot: interpreterSnapshot,\n surfaceUnhandledThrows: true,\n useScopeDirectly: true\n });\n const result =\n entryPointArgs === undefined || !topLevelResult.ok\n ? topLevelResult\n : await callEntryPoint({\n jobs,\n args: entryPointArgs,\n budget,\n compilation,\n captureReplayState: random.generator.snapshot,\n filename,\n module,\n onYield: (yieldPoint) => {\n snapshotIteration += 1;\n safeAddEvent(yieldPoint.otelSpan ?? getActiveOtelSpan(), \"snapshot.saved\", {\n iteration: snapshotIteration\n });\n let snapshot: RunSnapshot | undefined;\n const createSnapshot = () => {\n if (snapshot !== undefined) {\n return snapshot;\n }\n const interpreterSnapshot = yieldPoint.snapshot();\n snapshot = createRunSnapshot({\n executionSemantics,\n migration: restoredSnapshot?.migration,\n bindings: interpreterSnapshot.bindings,\n clock: options.clock,\n hostCalls: hostCalls.snapshot(),\n loopIterations: interpreterSnapshot.loopIterations,\n pendingAwaits: [createPendingAwaitSnapshot(yieldPoint)],\n replay: hostCalls.snapshotReplay(),\n initialInputs: initialInputs.snapshot,\n promiseReplay: promiseReplay.snapshot(),\n random,\n randomResumeState:\n typeof yieldPoint.replayState === \"number\"\n ? yieldPoint.replayState\n : undefined,\n sourceHash\n });\n return snapshot;\n };\n\n activeSnapshotScheduler.onYield(createSnapshot);\n dumpController.onYield(createSnapshot);\n },\n scope: executionScope,\n signal: options.signal,\n snapshot: interpreterSnapshot\n });\n await throwIfReturnedPromiseRejected(result);\n await throwIfUnhandledPromiseRejected(promiseTracker);\n await activeSnapshotScheduler.finish();\n\n let replay: HostCallReplay | undefined;\n let replayError: string | undefined;\n try {\n replay = hostCalls.snapshotReplay();\n } catch (error) {\n if (!(error instanceof MissingReplayCapabilityError)) throw error;\n replayError = error.message;\n }\n const snapshot = createRunSnapshot({\n executionSemantics,\n migration: restoredSnapshot?.migration,\n bindings: executionScope.snapshot().bindings,\n clock: options.clock,\n hostCalls: hostCalls.snapshot(),\n replay,\n initialInputs: initialInputs.snapshot,\n promiseReplay: promiseReplay.snapshot(),\n random,\n sourceHash\n });\n if (replayError !== undefined) snapshot.replayError = replayError;\n dumpController.finalize(snapshot);\n completedSnapshot = snapshot;\n\n reconcileCompiledValues(\n budget,\n [\n ...Object.values(result.snapshot.bindings),\n ...(result.ok && \"returnValue\" in result ? [result.returnValue] : [])\n ],\n compilation\n );\n\n return {\n ...result,\n snapshot\n };\n } catch (error) {\n promiseReplay.fail(error);\n materializeWrappedErrorCause(error);\n if (createFailureSnapshot !== undefined && snapshotScheduler !== undefined) {\n try {\n if (cancellationSnapshotError !== undefined) throw cancellationSnapshotError.reason;\n const snapshot = cancellationSnapshot ?? createFailureSnapshot();\n dumpController.finalize(snapshot);\n await snapshotScheduler.write(snapshot);\n } catch (snapshotError) {\n if (snapshotError instanceof UnsnapshotableValueError) {\n console.warn(`Skipping failure snapshot: ${snapshotError.message}`);\n } else {\n console.warn(\"Failed to write failure snapshot.\", snapshotError);\n }\n }\n }\n dumpController.fail(error);\n throw error;\n } finally {\n lifecycle.hostCallbackContext.disable();\n options.signal?.removeEventListener(\"abort\", captureCancellationSnapshot);\n leaveInputReplay?.();\n leaveHostReplay?.();\n promiseReplay.dispose();\n leaveSnapshotRun?.();\n deactivateOtelSink();\n }\n });\n } finally {\n releaseObjectPrototype(budget);\n compilation.dispose();\n operation.release();\n }\n };\n const result = withRunResources(options.signal, () =>\n withSandboxPromiseRejectionTracker(promiseTracker, execute)\n ).catch(async (error: unknown) => {\n if (completedSnapshot !== undefined) {\n try {\n await createSnapshotScheduler<RunSnapshot>(options).write(completedSnapshot);\n } catch (snapshotError) {\n console.warn(\"Failed to write failure snapshot.\", snapshotError);\n }\n }\n dumpController.fail(error);\n throw error;\n });\n\n const controlled = result.finally(() => {\n capturePausedSnapshot = undefined;\n detachExecutionFailure();\n jobs.finish();\n });\n return attachExecutionControl(attachDumpController(controlled, dumpController), jobs, options.signal);\n}\n\nasync function throwIfReturnedPromiseRejected(result: InterpreterResult): Promise<void> {\n if (!result.ok || !isSandboxPromise(result.returnValue)) {\n return;\n }\n\n observeSandboxPromise(result.returnValue);\n\n let rejected = false;\n let rejectionReason: unknown;\n result.returnValue.promise.then(\n () => undefined,\n (reason) => {\n rejected = true;\n rejectionReason = reason;\n }\n );\n\n await Promise.resolve();\n await Promise.resolve();\n\n if (rejected) {\n consumeSettledHostCall(result.returnValue);\n throw new UnhandledRejectionError(rejectionReason, result.returnValue.span);\n }\n}\n\nasync function throwIfUnhandledPromiseRejected(\n tracker: SandboxPromiseRejectionTracker\n): Promise<void> {\n const unhandled = await tracker.findUnhandledRejection();\n if (unhandled !== undefined) {\n throw new UnhandledRejectionError(unhandled.reason, unhandled.span);\n }\n}\n\nasync function callEntryPoint(input: {\n jobs: SandboxJobQueue;\n compilation: CompileScope;\n args: readonly SandboxValue[];\n budget: Budget;\n captureReplayState: () => number;\n filename: string;\n module: Module;\n onYield: NonNullable<Parameters<typeof interpret>[1]>[\"onYield\"];\n scope: Scope;\n signal?: AbortSignal;\n snapshot?: RunSnapshot;\n}): Promise<InterpreterResult> {\n const defaultExport = input.scope.lookup(\"default\");\n\n if (!defaultExport.found) {\n throw new Error(`Script ${input.filename} does not export a default function.`);\n }\n\n if (!isSandboxClosure(defaultExport.value)) {\n throw new TypeError(`Default export in ${input.filename} must be callable.`);\n }\n\n const argumentBindings = Object.fromEntries(\n input.args.map((value, index) => [createEntryPointArgName(index), value])\n ) as Record<string, SandboxValue>;\n const entryScope = input.scope.child({\n __agentScriptEntryPoint: defaultExport.value,\n ...argumentBindings\n });\n\n return interpret(createEntryPointAwait(input.args.length, input.module.span), {\n jobs: input.jobs,\n compilation: input.compilation,\n signal: input.signal,\n budget: input.budget,\n captureReplayState: input.captureReplayState,\n onYield: input.onYield,\n scope: entryScope,\n snapshot: input.snapshot,\n surfaceUnhandledThrows: true,\n useScopeDirectly: true\n });\n}\n\nfunction createEntryPointAwait(argCount: number, span: SourceSpan): AwaitExpression {\n return {\n type: \"AwaitExpression\",\n argument: createEntryPointCall(argCount, span),\n span\n };\n}\n\nfunction createEntryPointCall(argCount: number, span: SourceSpan): CallExpression {\n return {\n type: \"CallExpression\",\n callee: createIdentifier(\"__agentScriptEntryPoint\", span),\n arguments: Array.from({ length: argCount }, (_value, index) =>\n createIdentifier(createEntryPointArgName(index), span)\n ),\n optional: false,\n span\n };\n}\n\nfunction createIdentifier(name: string, span: SourceSpan): Identifier {\n return {\n type: \"Identifier\",\n name,\n span\n };\n}\n\nfunction createEntryPointArgName(index: number): string {\n return `__agentScriptEntryPointArg${index}`;\n}\n\nfunction createExecutableNode(module: Module): ParseResult {\n const executableStatements = module.body.filter(\n (statement): statement is Exclude<Statement, { type: \"ImportDeclaration\" }> =>\n statement.type !== \"ImportDeclaration\"\n );\n\n if (executableStatements.length === 0) {\n return {\n type: \"BlockStatement\",\n body: [],\n span: module.span\n };\n }\n\n if (executableStatements.length === 1) {\n const [statement] = executableStatements;\n return statement.type === \"ExpressionStatement\" ? statement.expression : statement;\n }\n\n return {\n type: \"BlockStatement\",\n body: executableStatements,\n span: module.span\n };\n}\n\nfunction createRunSnapshot(input: {\n executionSemantics: \"jobs-v6\" | \"jobs-v7\" | \"jobs-v8\" | typeof EXECUTION_SEMANTICS;\n migration?: SafeJSSnapshot[\"migration\"];\n bindings: InterpreterResult[\"snapshot\"][\"bindings\"];\n clock: RunClock | undefined;\n hostCalls?: HostCallRecord[];\n replay?: HostCallReplay;\n promiseReplay?: PromiseReplaySnapshot;\n initialInputs?: ReplayData;\n loopIterations?: Record<string, LoopIterationSnapshot>;\n pendingAwaits?: RunPendingAwaitSnapshot[];\n randomResumeState?: number;\n random:\n | {\n seed: number;\n initialState: number;\n generator: RunRandom;\n }\n | undefined;\n sourceHash: string;\n}): RunSnapshot {\n const snapshot: RunSnapshot = {\n version: DUMP_FORMAT_VERSION,\n executionSemantics: input.executionSemantics,\n sourceHash: input.sourceHash,\n ...(input.migration === undefined ? {} : { migration: structuredClone(input.migration) }),\n bindings: input.bindings,\n clock: input.clock?.snapshot(),\n ...(input.hostCalls === undefined || input.hostCalls.length === 0\n ? {}\n : { hostCalls: input.hostCalls }),\n ...(input.loopIterations === undefined ? {} : { loopIterations: input.loopIterations }),\n ...(input.replay === undefined ? {} : { replay: input.replay }),\n ...(input.initialInputs === undefined ? {} : { initialInputs: structuredClone(input.initialInputs) }),\n ...(input.promiseReplay === undefined ? {} : { promiseReplay: input.promiseReplay }),\n ...(input.pendingAwaits === undefined || input.pendingAwaits.length === 0\n ? {}\n : { pendingAwaits: input.pendingAwaits }),\n random:\n input.random === undefined\n ? undefined\n : {\n seed: input.random.seed,\n initialState: input.random.initialState,\n ...(input.randomResumeState === undefined\n ? {}\n : { resumeState: input.randomResumeState }),\n state: input.random.generator.snapshot()\n }\n };\n inMemoryRunSnapshots.add(snapshot);\n return snapshot;\n}\n\nfunction readHostCallSnapshot(snapshot: SafeJSSnapshot | undefined): HostCallRecord[] {\n if (snapshot === undefined || !Array.isArray(snapshot.hostCalls)) {\n return [];\n }\n\n return snapshot.hostCalls.map((value, index) => {\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(`Snapshot hostCalls[${index}] must be an object.`);\n }\n\n const record = value as Partial<HostCallRecord>;\n const requiredStrings = [\n \"id\",\n \"runId\",\n \"sourceHash\",\n \"moduleId\",\n \"operation\",\n \"argumentDigest\"\n ] as const;\n for (const key of requiredStrings) {\n if (typeof record[key] !== \"string\" || record[key].length === 0) {\n throw new TypeError(`Snapshot hostCalls[${index}].${key} must be a non-empty string.`);\n }\n }\n if (record.sourceHash !== snapshot.sourceHash) {\n throw new TypeError(`Snapshot hostCalls[${index}].sourceHash must match the snapshot.`);\n }\n if (record.policy !== \"re-issue\" && record.policy !== \"read-side-effect\") {\n throw new TypeError(`Snapshot hostCalls[${index}].policy is invalid.`);\n }\n if (\n record.lifecycle !== \"created\" &&\n record.lifecycle !== \"running\" &&\n record.lifecycle !== \"settled\" &&\n record.lifecycle !== \"consumed\" &&\n record.lifecycle !== \"cancelled\"\n ) {\n throw new TypeError(`Snapshot hostCalls[${index}].lifecycle is invalid.`);\n }\n if (\n (record.lifecycle === \"settled\" || record.lifecycle === \"cancelled\") &&\n record.outcome === undefined\n ) {\n throw new TypeError(`Snapshot hostCalls[${index}].outcome is required.`);\n }\n\n return record as HostCallRecord;\n });\n}\n\nfunction hasLoopIterationSnapshot(snapshot: SafeJSSnapshot | undefined): snapshot is RunSnapshot {\n return (\n snapshot !== undefined &&\n typeof snapshot.loopIterations === \"object\" &&\n snapshot.loopIterations !== null &&\n Object.keys(snapshot.loopIterations).length > 0\n );\n}\n\nfunction createPendingAwaitSnapshot(yieldPoint: ResumeBreakpoint): RunPendingAwaitSnapshot {\n return {\n ...(yieldPoint.nodeId === undefined ? {} : { nodeId: yieldPoint.nodeId }),\n span: yieldPoint.span\n };\n}\n\ntype ResumeBreakpoint = Parameters<\n NonNullable<NonNullable<Parameters<typeof interpret>[1]>[\"onYield\"]>\n>[0];\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,qBAAAA,0BAAyB;AAClC,SAAS,aAAa;;;ACHtB,SAAQ,yBAAwB;AAsChC,IAAM,YAAY,uBAAO,yBAAyB;AAClD,IAAM,gBAAgB,oBAAI,QAAgB;AAGnC,IAAM,oBAAN,MAAwB;AAAA,EAc7B,YAA6B,SAM1B;AAN0B;AAO3B,SAAK,OAAO,QAAQ,QAAQ,IAAI,gBAAgB;AAChD,uBAAmB,QAAQ,SAAS,KAAK,OAAO,KAAK,IAAI,GAAG,EAAE,6BAA6B,KAAK,CAAC;AACjG,YAAQ,QAAQ,kBAAkB,MAAM,MAAM,CAAC,GAAG,KAAK,QAAQ,OAAO,C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OAAO,GAAG,MAAM,YAAY,OAAO,GAAG,EAAE,WAAW,GAAG;AAC/D,cAAM,IAAI,UAAU,sBAAsB,KAAK,KAAK,GAAG,8BAA8B;AAAA,MACvF;AAAA,IACF;AACA,QAAI,OAAO,eAAe,SAAS,YAAY;AAC7C,YAAM,IAAI,UAAU,sBAAsB,KAAK,uCAAuC;AAAA,IACxF;AACA,QAAI,OAAO,WAAW,cAAc,OAAO,WAAW,oBAAoB;AACxE,YAAM,IAAI,UAAU,sBAAsB,KAAK,sBAAsB;AAAA,IACvE;AACA,QACE,OAAO,cAAc,aACrB,OAAO,cAAc,aACrB,OAAO,cAAc,aACrB,OAAO,cAAc,cACrB,OAAO,cAAc,aACrB;AACA,YAAM,IAAI,UAAU,sBAAsB,KAAK,yBAAyB;AAAA,IAC1E;AACA,SACG,OAAO,cAAc,aAAa,OAAO,cAAc,gBACxD,OAAO,YAAY,QACnB;AACA,YAAM,IAAI,UAAU,sBAAsB,KAAK,wBAAwB;AAAA,IACzE;AAEA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,SAAS,yBAAyB,UAA+D;AAC/F,SACE,aAAa,UACb,OAAO,SAAS,mBAAmB,YACnC,SAAS,mBAAmB,QAC5B,OAAO,KAAK,SAAS,cAAc,EAAE,SAAS;AAElD;AAEA,SAAS,2BAA2B,YAAuD;AACzF,SAAO;AAAA,IACL,GAAI,WAAW,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,WAAW,OAAO;AAAA,IACvE,MAAM,WAAW;AAAA,EACnB;AACF;",
6
+ "names": ["AsyncLocalStorage", "AsyncLocalStorage", "namespace", "descriptor", "result", "dumpController", "operation", "snapshot", "interpreterSnapshot"]
7
+ }