nodejs-map 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/dist/app/assets/app.worker-PoneE3J2.js +8 -0
- package/dist/app/assets/app.worker-PoneE3J2.js.map +1 -0
- package/dist/app/assets/atlas.worker-B0xwOHwo.js +2 -0
- package/dist/app/assets/atlas.worker-B0xwOHwo.js.map +1 -0
- package/dist/app/assets/cm-BiB0hvWw.js +13 -0
- package/dist/app/assets/cm-BiB0hvWw.js.map +1 -0
- package/dist/app/assets/dist-B37Ex44M.js +2 -0
- package/dist/app/assets/dist-B37Ex44M.js.map +1 -0
- package/dist/app/assets/dist-hDhUT_Vg.js +2 -0
- package/dist/app/assets/dist-hDhUT_Vg.js.map +1 -0
- package/dist/app/assets/index-2K-ozYKf.js +16 -0
- package/dist/app/assets/index-2K-ozYKf.js.map +1 -0
- package/dist/app/assets/index-Cw18rDSZ.css +1 -0
- package/dist/app/assets/map-Cnxgv4Ve.js +129 -0
- package/dist/app/assets/map-Cnxgv4Ve.js.map +1 -0
- package/dist/app/assets/map-Cz4s03Wm.css +1 -0
- package/dist/app/assets/sdf-label-font-1nAa0TP8.png +0 -0
- package/dist/app/config.json +5 -0
- package/dist/app/favicon.svg +1 -0
- package/dist/app/index.html +21 -0
- package/dist/atlas/v26.13.1/build-report.json +178 -0
- package/dist/atlas/v26.13.1/chunks/lib.bootstrap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.core.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.devtools.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.events.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.platform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.streams.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.timers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.workers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.callbacks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.diag.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.napi.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.support.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.backends.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.threadpool.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.asmjs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ast.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.base.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.baseline.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.bigint.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.builtins.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.riscv.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.common.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler-dispatcher.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.backend.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.turboshaft.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.d8.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.date.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.debug.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.deoptimizer.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.diagnostics.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.dumpling.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.execution.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.extensions.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.flags.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.fuzzilli.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.handles.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.cppgc.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ic.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.init.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.interpreter.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.json.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libplatform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libsampler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.logging.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.maglev.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.numbers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.objects.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.parsing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.profiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.regexp.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.root.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.roots.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.runtime.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.sandbox.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.snapshot.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.strings.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tasks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.torque.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tracing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.trap-handler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.utils.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.wasm.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.zone.0.json +1 -0
- package/dist/atlas/v26.13.1/edges.json +1 -0
- package/dist/atlas/v26.13.1/files.json +1 -0
- package/dist/atlas/v26.13.1/index.json +1 -0
- package/dist/atlas/v26.13.1/link-check.json +16 -0
- package/dist/atlas/v26.13.1/search.json +1 -0
- package/dist/cli.js +6002 -0
- package/dist/examples.json +1 -0
- package/dist/lessons/async-await-chain.nmrec.gz +0 -0
- package/dist/lessons/beforeexit-and-exit.nmrec.gz +0 -0
- package/dist/lessons/dns-lookup-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/esm-twist.nmrec.gz +0 -0
- package/dist/lessons/eventemitter-is-synchronous.nmrec.gz +0 -0
- package/dist/lessons/fs-promises-await.nmrec.gz +0 -0
- package/dist/lessons/fs-sync-vs-async.nmrec.gz +0 -0
- package/dist/lessons/index.json +621 -0
- package/dist/lessons/interval-and-clear.nmrec.gz +0 -0
- package/dist/lessons/nested-ticks-and-microtasks.nmrec.gz +0 -0
- package/dist/lessons/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
- package/dist/lessons/pool-with-two-threads.nmrec.gz +0 -0
- package/dist/lessons/readfile-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/tcp-round-trip.nmrec.gz +0 -0
- package/dist/lessons/tick-before-promise.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-io.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-main.nmrec.gz +0 -0
- package/dist/lessons/timer-vs-file-read.nmrec.gz +0 -0
- package/dist/lessons/timers-phase.nmrec.gz +0 -0
- package/dist/preload.cjs +477 -0
- package/package.json +25 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app.worker-PoneE3J2.js","names":["BY_ID","inStack","TIMELINE_CLASSES","EventStore","#events","#version","#ended","#listeners","batch","previousLength","base","incoming","#refuse","from","skip","truncated","#change","i","events","n","listener","why","replaced","notify","change","QUEUE_NAMES","table","entries","QUEUE_CODE","PHASES","PHASE_CODE","queueCode","name","code","phaseCode","SIGNAL_KINDS","MAX_THREAD_INDEX","isNum","v","isId","isStr","isObj","checkEvent","value","e","\"k\"","\"t\"","c","\"c\"","\"rule\"","\"at\"","\"tid\"","\"node\"","\"caps\"","\"mode\"","\"program\"","\"poolSize\"","\"code\"","\"signal\"","\"stream\"","\"text\"","loc","\"loc\"","\"id\"","\"type\"","\"trigger\"","\"label\"","\"url\"","\"line\"","\"delayMs\"","\"repeat\"","\"loopCount\"","\"events\"","\"eventsWaiting\"","\"name\"","\"durUs\"","\"edge\"","\"cat\"","\"ph\"","\"queue\"","\"n\"","\"phase\"","\"turn\"","\"afterPoll\"","\"pollTimeoutMs\"","\"lateMs\"","\"job\"","\"kind\"","\"op\"","\"thread\"","\"size\"","\"reason\"","\"frames\"","\"timeKeptRunning\"","\"pausedMs\"","\"gate\"","\"stoppedMs\"","\"why\"","\"hiddenMs\"","\"level\"","countBelow","list","limit","lo","mid","lastBelow","factOf","index","WEAKNESS","weaker","a","b","RunIndex","#openDebug","#openGate","#touchIndex","#touchId","#grow","size","grow8","blocks","t","#touch","rec","#ensure","id","type","prevT","bad","f","ref","existing","parent","tm","lastOf","#tie","before","m","mask","flags","end","start","job","ti","tid","cut","keep","order","turns","pauses","#reopen","bits","kind","k","p","hi","running","RecordingError","message","line","LIMITS","fail","path","what","str","max","text","num","nonNeg","int","poolSize","count","bool","oneOf","allowed","nullable","req","check","opt","isPlainObject","proto","object","spec","extraAllowed","out","key","obj","LOC","FRAME","NODE_INFO","CERT","CAPS","PHASE","QUEUE","frames","args","keys","x","BASE","PAYLOADS","\"output\"","\"scope\"","\"note\"","KINDS","SPEC_BY_KIND","isEventKind","validateEvent","HEADER","s","validateHeader","MAX_LINE","FIELD_RE","FORBIDDEN_FIELDS","typeOf","RecordingEncoder","#shapes","#strings","#prevNs","header","parts","#one","#string","\"src\"","names","types","ty","shape","ns","row","encodeRecording","recording","enc","RecordingDecoder","#rest","#line","#header","#count","chunk","nl","#lineText","tail","raw","tag","#defineString","#defineShape","#event","src","fields","colon","fieldName","#stringAt","shapeIndex","dt","decoded","err","decodeRecording","dec","S","O","ENTRIES","BACKGROUND_IDS","RULES","r","isPoolBackedType","isIoRequestType","PERSISTENT_HANDLE_TYPES","createLive","queues","q","cloneLive","liveSize","queuePush","live","entry","queueFind","queue","items","queueTake","rest","inStack$1","stack","timerCount","state","d","timerMoved","after","activeAfter","stackTimers","seen","o","dropFrom","ensureThread","thread","detach","th","doneRemove","doneAdd","occupy","started","deliver","finishJob","since","viaFromType","platform","setStatus","leavePhase","loopActivity","applyEvent","cls","timerBefore","depth","via","viaIndex","viaRule","io","guess","moved","old","starts","ends","finished","last","RULE_MAIN","RULE_DUE","DEFAULT_VIEW","resolveOptions","cap","VIA_NAMES","TIMER_STATES","fact","ctx","factOrNull","inStack","refOf","timerView","armIndex","startIndex","armed","delayUs","lateMs","armAtStart","itemView","runs","gone","jobs","frameView","viaFrom","afterPollAt","JOB_STATES","heldGate","jobView","gate","atEvent","runView","mainView","loopView","scope","sample","pollEvent","queueView","ended","total","timersView","active","recent","firedEvent","poolView","startSize","sizeEvent","sizeFrom","held","threads","tids","debugView","paused","pe","lastPause","resumed","ge","released","unfrozen","frozen","focusView","places","placeAt","at","place","waiting","fe","logEntries","to","outputRange","fromSeq","toSeq","itemsRange","buildView","run","itemsTotal","notes","outTotal","CLASSES","buildTimeline","width","axis","version","W","phase","phaseCertainty","busy","counts","tlState","tlClass","tMono","t0","t1","byTime","span","hist","carry","cert","ph","best","bestCount","buildMarkers","outputIndex","outputStream","CERT_CODE","now","maskOf","Replay","#index","#ready","#frontier","#keyframes","#keyframePos","#keyframeSlots","#nextKeyframe","#interval","#eager","#target","#cursor","#cursorPos","#viewDefaults","#unsubscribe","#timelines","#markers","#markersReady","store","options","#onChange","#ingest","#rollback","#replay","#gap","keyframe","budgetMs","deadline","copy","#keyframeBefore","pos","#stateAt","#live","position","direction","ready","#context","chain","next","cached","summary","clamp","Player","#playing","#speed","#pace","#stepsPerSecond","#timeScale","#deadTimeUs","#deadTimePauseMs","#follow","#maxTickMs","#last","#credit","#deadTime","#waiting","#atTail","#previous","replay","length","#resetClock","speed","pace","on","reached","cmd","nowMs","#tickOne","#tickTime","#tickSteps","prev","changed","#deadGap","gap","#report","gapUs","progress","stepMs","pauseMs","hold","cost","usToMs","dead","MAX_FRAGMENT_BYTES","toBytes","input","pipe","stream","bytes","maxBytes","tooBig","writer","reader","chunks","done","offset","gzip","gunzip","error","isGzip","utf8","parse","B64","B64_VALUE","toBase64Url","piece","fromBase64Url","openRecording","saveRecording","recordingToFragment","packed","fragment","recordingFromFragment","body","part","dot","QUEUES","PARTS","SCALARS","same","ka","listPatch","comparable","a0","a1","b0","b1","prepend","append","chunkKey","logKey","l","diffView","previous","set","HOST_VIEW_DEFAULTS","ReplayHost","#post","#now","#defer","#viewOptions","#views","#posted","#clock","#timeline","#wantMarkers","#dirty","#summaryDirty","#lastSummary","#cancelFrame","#cancelPump","#disposed","#generation","post","env","fn","ms","handle","#send","request","re","#handle","messageOf","#wake","transfer","#changed","#open","result","#frame","loading","generation","#pump","more","#busy","tick","view","WELL_KNOWN","ASYNC_TYPE_INFO","QUEUE_LABEL","PHASE_LABEL","nf1","nf3","nf0","formatMicros","us","abs","formatMillis","baseName","urlOrPath","oneLine","ch","LOG_GROUPS","KIND_GROUP","summarizeEvent","top","ALL_GROUPS_FILTER","CERTAINTY_BIT","filterKey","toRow","statusAfter","LogIndex","#matches","#matchCount","#scanned","#key","#groupOn","#certaintyMask","#all","#statusMarks","#mode","status","#matchesFilter","group","#setFilter","filter","#scan","bigger","#rowBefore","rows","isEventsFrame","\"run\"","\"base\"","OPEN_SLICE","AppHost","#host","#log","#run","#adopting","#stale","#lastTail","#app","#replaceRun","#tailChanged","frame","decode","slice","host","event"],"sources":["../../../replay/src/types.ts","../../../replay/src/store.ts","../../../replay/src/run-index.ts","../../../event-format/src/validate.ts","../../../event-format/src/codec.ts","../../../event-format/src/rules.ts","../../../replay/src/reducer.ts","../../../replay/src/rules.ts","../../../replay/src/view.ts","../../../replay/src/timeline.ts","../../../replay/src/replay.ts","../../../replay/src/player.ts","../../../replay/src/recording.ts","../../../replay/src/patch.ts","../../../replay/src/host.ts","../../../atlas-format/src/well-known.ts","../../src/lib/format.ts","../../src/lib/logIndex.ts","../../src/worker/appHost.ts","../../src/worker/app.worker.ts"],"sourcesContent":["/**\n * Public data types of @nodejs-map/replay.\n *\n * Everything in this file is plain data: objects, arrays, strings, numbers,\n * booleans, null and typed arrays. Nothing here holds a class instance, a Map\n * or a function, so every value can be sent with postMessage (structured\n * clone) and compared in tests with deepStrictEqual.\n *\n * Absent values are `null`, never `undefined`, for the same reason.\n *\n * Words used throughout:\n * - position: a number P from 0 to the length of the event list. \"The state\n * at position P\" is the state after the first P events were applied.\n * Position 0 is before the first event. The event applied last is the one\n * at index P - 1.\n * - index: the place of one event in the list (0-based).\n * - t: microseconds on the target's clock, as in the event format.\n */\n\nimport type {\n Capabilities,\n Certainty,\n EventKind,\n EventPayloads,\n Frame,\n Loc,\n NmEvent,\n NodeInfo,\n Phase,\n PoolWorkKind,\n QueueName,\n RecordingHeader,\n} from '@nodejs-map/event-format';\n\n// ---------------------------------------------------------------------------\n// Honesty marks\n// ---------------------------------------------------------------------------\n\n/**\n * Where a fact on screen comes from: the event that said so. The UI marks\n * every drawn thing from this (observed / inferred / model) and can open the\n * rule text for `rule`.\n *\n * `rule` is a rule id of @nodejs-map/event-format (RULES) when the event\n * named one, or an id of REPLAY_RULES (they start with \"replay:\") when this\n * package worked the fact out itself. null: the event named no rule.\n */\nexport interface Fact {\n c: Certainty;\n rule: string | null;\n /** Index of the event this fact comes from. */\n index: number;\n /** Time of that event, microseconds. */\n t: number;\n}\n\n// ---------------------------------------------------------------------------\n// The view state\n// ---------------------------------------------------------------------------\n\n/**\n * - idle: no `run.start` seen yet\n * - running: the program runs\n * - paused: JavaScript is stopped at a statement (`debug.paused`)\n * - gate: the target is stopped at a gate (`gate.stopped`, probe build)\n * - ended: `run.end` seen\n */\nexport type RunStatus = 'idle' | 'running' | 'paused' | 'gate' | 'ended';\n\nexport interface RunView {\n status: RunStatus;\n node: NodeInfo | null;\n caps: Capabilities | null;\n program: string | null;\n mode: 'free' | 'debug' | null;\n poolSize: number | null;\n /** From `run.end`. */\n exitCode: number | null;\n signal: string | null;\n started: Fact | null;\n ended: Fact | null;\n}\n\n/** An async item, as far as it is needed to draw a chip for it. */\nexport interface ItemRef {\n id: number;\n /** The async_hooks type. \"?\" when no `item.new` and no `callback.start` named one. */\n type: string;\n label: string | null;\n /** The item during whose callback this one was created; 0 or 1 for the main script. */\n trigger: number;\n /** Where in the user's program it was created. */\n loc: Loc | null;\n /** The `item.new` event. null: the item was first seen in some other event (it was created before the hooks were on). */\n created: Fact | null;\n}\n\n/**\n * - created: seen, not waiting in any queue we know of, no callback yet\n * - waiting: in at least one queue\n * - running: its callback is on the main thread right now\n * - ran: at least one callback has returned and it is not waiting again\n * - gone: destroyed (`item.gone`)\n */\nexport type ItemState = 'created' | 'waiting' | 'running' | 'ran' | 'gone';\n\n/** One async item with its life up to the current position. */\nexport interface ItemView extends ItemRef {\n state: ItemState;\n /** The queues it waits in at this position (normally none or one). */\n queues: QueueName[];\n /** How many callbacks of this item have started so far. */\n runs: number;\n /** Latest `callback.start` and `callback.end` so far. */\n lastStart: Fact | null;\n lastEnd: Fact | null;\n /** `item.gone`. */\n gone: Fact | null;\n /** `promise.settled`. */\n settled: Fact | null;\n /** Timer details when a `timer.set` was seen for this item. */\n timer: TimerView | null;\n /** Name of the pool job tied to this item, when one is. */\n job: string | null;\n /** How many items seen so far name this one as their trigger. */\n children: number;\n}\n\n/**\n * How a callback got onto the main thread.\n * - phase: run by the event loop from one of its phases\n * - nextTick: run by the nextTick drain (processTicksAndRejections)\n * - microtask: run by the microtask drain\n * - unknown: the events do not say\n */\nexport type CallbackVia = 'phase' | 'nextTick' | 'microtask' | 'unknown';\n\nexport interface CallbackFrame {\n item: ItemRef;\n /** The `callback.start` event. */\n from: Fact;\n via: CallbackVia;\n /**\n * How we know `via`. When the item was waiting in a queue, this is the\n * certainty and rule of its `queue.add`. Otherwise it is worked out from\n * the item's type and marked inferred with the matching rule (K1, M1).\n * null when `via` is \"unknown\".\n */\n viaFrom: Fact | null;\n /** The queue the item left when this callback started. null: it was in none. */\n queue: QueueName | null;\n /** The loop phase at that moment, when one was known. */\n phase: Phase | null;\n phaseFrom: Fact | null;\n /** True when that phase was the second run of pending callbacks, right after poll. */\n phaseAfterPoll: boolean;\n /** 0 for a callback started from the loop or a drain; 1 and up when it started inside another callback. */\n depth: number;\n}\n\n/**\n * What the main thread is doing.\n * - main: running the main script (from `run.start` until the first\n * callback, loop event or the end; rule \"replay:main\")\n * - callback: `stack` is not empty; the last frame is the one running\n * - nothing: between callbacks, or the run has not started or has ended\n */\nexport interface MainThreadView {\n doing: 'main' | 'callback' | 'nothing';\n /** For \"main\": the `run.start` fact re-marked as inferred. For \"nothing\": the event that emptied the thread. For \"callback\": the top frame's start. */\n from: Fact | null;\n /** Outermost first. Empty unless `doing` is \"callback\". */\n stack: CallbackFrame[];\n}\n\nexport interface LoopView {\n /** From `loop.turn` (and `phase.enter` when it carries a turn). null before the first one. */\n turn: number | null;\n turnFrom: Fact | null;\n /** The phase the loop is in. null: between phases, or not known. */\n phase: Phase | null;\n phaseFrom: Fact | null;\n /**\n * True when the current phase is libuv's second run of pending callbacks,\n * right after poll (\"pending (after poll)\"; on Windows this is where\n * completed requests run).\n */\n afterPoll: boolean;\n /**\n * The latest poll timeout reported (probe build): how long the loop was\n * prepared to wait in poll. 0: no wait. -1: until something happens.\n * `current` is true while the loop is in that very poll phase.\n */\n poll: { timeoutMs: number; current: boolean; from: Fact } | null;\n /** The phase left most recently. */\n lastPhase: { phase: Phase; afterPoll: boolean; entered: Fact | null; left: Fact } | null;\n /** The latest `scope` signal (RunTimers / CheckImmediate), kept as evidence. */\n lastScope: { name: string; durUs: number; from: Fact } | null;\n /** The latest `loop.sample` signal. */\n lastSample: { loopCount: number; events: number; eventsWaiting: number; from: Fact } | null;\n}\n\nexport interface QueueEntryView {\n item: ItemRef;\n /** The `queue.add` event: since when it waits, how sure, which rule. */\n from: Fact;\n /** Atlas id of that `queue.add`, when it had one. */\n at: string | null;\n /**\n * Callbacks of this item that started while it stayed in the queue. Only\n * persistent handles in \"io\" stay (see PERSISTENT_HANDLE_TYPES); for every\n * other entry this is 0.\n */\n runs: number;\n}\n\nexport interface QueueView {\n name: QueueName;\n /** Number of entries in the queue. */\n total: number;\n /** In arrival order. At most ViewOptions.maxEntries; the oldest are kept. */\n entries: QueueEntryView[];\n truncated: boolean;\n /**\n * True once `run.end` is applied and the queue is not empty: these items\n * were left waiting when the run ended and never ran (a timer created in\n * an \"exit\" listener, for example). Their entries are unchanged.\n */\n leftAtEnd: boolean;\n}\n\n/**\n * - waiting: armed, its callback has not started\n * - running: its callback is on the main thread\n * - done: its callback returned and it was not armed again\n * - cleared: cancelled or destroyed before running (again)\n */\nexport type TimerState = 'waiting' | 'running' | 'done' | 'cleared';\n\nexport interface TimerView {\n item: ItemRef;\n delayMs: number;\n repeat: boolean;\n /** The `timer.set` event. */\n set: Fact;\n /** The event that armed it most recently: `timer.set`, or the `queue.add` that put a repeating timer back. */\n armed: Fact;\n /**\n * When it is due: time of `armed` plus the delay, in microseconds. This is\n * our arithmetic, not a report from Node (rule \"replay:due\").\n */\n dueT: number;\n dueFrom: Fact;\n state: TimerState;\n /** Callbacks started so far. */\n runs: number;\n /** Latest callback start. */\n lastRun: Fact | null;\n /** How late the latest callback started against `dueT` at that time, in milliseconds (rule \"replay:due\"). */\n lateMs: number | null;\n /** The event that cleared it. */\n cleared: Fact | null;\n}\n\nexport interface TimersView {\n /** Waiting and running timers, soonest due first. At most ViewOptions.maxEntries. */\n active: TimerView[];\n /** Done and cleared timers, oldest first, the most recent ones only. */\n recent: TimerView[];\n counts: { set: number; waiting: number; running: number; done: number; cleared: number };\n /** Loop-level `timer.fired` events: how many, and the latest. */\n fired: { count: number; last: { lateMs: number | null; from: Fact } | null };\n truncated: boolean;\n /** True once `run.end` is applied and timers are still waiting: they were left waiting when the run ended. */\n leftAtEnd: boolean;\n}\n\n/**\n * The life of a pool job: queued -> started -> finished -> posted -> delivered.\n * - waiting: queued, no thread has picked it up\n * - running: a thread runs its work function\n * - finished: the work function returned. On the probe build the thread\n * still holds the job until it has posted the result; on an\n * official build nothing more is reported and the job is shown\n * on its way to the loop.\n * - posted: the result is on the loop's done list (probe build only)\n * A delivered or cancelled job is no longer shown.\n */\nexport type PoolJobState = 'waiting' | 'running' | 'finished' | 'posted';\n\n/** The gates a target can be stopped at (see `gate.stopped` in the event format). */\nexport type GateName = EventPayloads['gate.stopped']['gate'];\n\nexport interface PoolJobView {\n job: string;\n kind: PoolWorkKind;\n op: string | null;\n state: PoolJobState;\n /** The async item it belongs to, when `pool.queued` or `pool.link` said so. */\n item: ItemRef | null;\n /** The event that tied the job to the item. */\n itemFrom: Fact | null;\n /** Display index of the thread that runs or ran it. */\n thread: number | null;\n queued: Fact | null;\n started: Fact | null;\n finished: Fact | null;\n /** `pool.posted` (probe build). */\n posted: Fact | null;\n /** Atlas id of the latest pool event of this job. */\n at: string | null;\n /** The gate that holds this job right now (poolStart, poolPost or poolDone), or null. See PoolView.held. */\n held: GateName | null;\n}\n\nexport interface PoolThreadView {\n /** Display index, 1-based. */\n thread: number;\n /**\n * The job this thread holds: one it runs (state \"running\") or, on the\n * probe build, one whose work has returned and whose result it has not\n * posted yet (state \"finished\").\n */\n job: PoolJobView | null;\n /** The real thread id, when the `pool.started` event carried one. */\n tid: number | null;\n /** Jobs this thread has started so far. */\n jobs: number;\n /** True when the index is above the pool size of `run.start`: the events showed a thread we did not expect. */\n extra: boolean;\n}\n\n/** What one real thread id did, from `pool.thread` signals. Evidence, not a job assignment. */\nexport interface PoolTidView {\n tid: number;\n busy: boolean;\n /** Name of the job kind it started most recently. */\n name: string;\n /** The latest signal of this thread. */\n from: Fact;\n starts: number;\n ends: number;\n}\n\nexport interface PoolView {\n /**\n * The number of pool threads in effect at this position: the size from\n * the latest `pool.size` event, or UV_THREADPOOL_SIZE as `run.start`\n * reported it (which stays in RunView.poolSize). A program can set the\n * variable itself before it first uses the pool; libuv reads it only then.\n * The thread lanes follow this number: lanes above it that are idle and\n * never ran a job are removed, missing ones are added.\n */\n size: number | null;\n /** The event the size comes from: `pool.size`, or `run.start`. */\n sizeFrom: Fact | null;\n threads: PoolThreadView[];\n /** Jobs queued and not yet picked up, oldest first. */\n waiting: PoolJobView[];\n /**\n * Jobs whose work is over and whose done-callback has not run, oldest\n * first.\n *\n * Probe build: the jobs on the loop's done list, from `pool.posted` (state\n * \"posted\") until `pool.delivered`.\n *\n * Official build: neither event exists. A job is listed from\n * `pool.finished` (state \"finished\") until the callback of its item starts\n * or the item goes away (rule \"replay:delivered\"). A job that was never\n * tied to an item cannot leave that way: such jobs are kept, oldest\n * dropped first, up to UNLINKED_DONE_LIMIT.\n */\n done: PoolJobView[];\n /**\n * The job a gate holds right now, when the target is stopped at a pool\n * gate that names one.\n * - poolStart: a pool thread holds a job it has not started (where \"thread\")\n * - poolPost: a pool thread holds a finished job it has not posted (where \"thread\")\n * - poolDone: the loop holds a result before its done-callback (where \"loop\")\n * `thread` is the display index of the holding thread when the events tell\n * it: the thread the job is shown on, or the thread whose real id is the\n * gate event's `tid`. `view` is null when the job is not on screen.\n */\n held: { gate: GateName; job: string; where: 'thread' | 'loop'; thread: number | null; view: PoolJobView | null; from: Fact } | null;\n tids: PoolTidView[];\n counts: { queued: number; started: number; finished: number; posted: number; delivered: number; cancelled: number; droppedUnlinked: number };\n truncated: boolean;\n /** True once `run.end` is applied and jobs are still waiting, on a thread or in the done list: the run ended with them unfinished or undelivered. */\n leftAtEnd: boolean;\n}\n\nexport interface OutputChunk {\n /** Ordinal of this chunk in the run, from 0. Stable: use it as a list key. */\n seq: number;\n index: number;\n t: number;\n stream: 'stdout' | 'stderr';\n text: string;\n}\n\nexport interface OutputView {\n /** Chunks written up to this position. */\n total: number;\n /** Characters written up to this position. */\n chars: number;\n /**\n * The latest chunks, at most ViewOptions.maxOutput. Older ones are read\n * with Replay.output(fromSeq, toSeq). The chunk objects are the same\n * objects from one view to the next; nothing is copied per step.\n */\n chunks: OutputChunk[];\n}\n\nexport interface DebugView {\n paused: boolean;\n reason: 'breakpoint' | 'step' | 'pause' | 'exception' | 'entry' | 'other' | null;\n /** Top frame first. Empty when not paused. */\n frames: Frame[];\n /** True on an official build: real time kept running while paused, and the UI must say so. */\n timeKeptRunning: boolean;\n /** The `debug.paused` event. */\n from: Fact | null;\n /** The latest pause that is over. */\n lastPause: { pausedMs: number; timeKeptRunning: boolean; paused: Fact | null; resumed: Fact } | null;\n /** Pauses so far, including a current one. */\n pauses: number;\n gate: {\n stopped: boolean;\n gate: GateName | null;\n phase: Phase | null;\n job: string | null;\n from: Fact | null;\n /** From the latest `gate.released`. */\n lastStoppedMs: number | null;\n stops: number;\n };\n clock: {\n frozen: boolean;\n /** What froze it, when the event said: a gate or a JavaScript breakpoint. */\n why: 'gate' | 'breakpoint' | null;\n from: Fact | null;\n /** From the latest `clock.unfrozen`. */\n lastHiddenMs: number | null;\n /** Sum of `hiddenMs` so far. */\n hiddenMs: number;\n };\n}\n\nexport interface NoteView {\n seq: number;\n level: 'info' | 'warn';\n text: string;\n from: Fact;\n}\n\nexport interface NotesView {\n total: number;\n /** The latest notes, oldest first, at most ViewOptions.maxNotes. */\n items: NoteView[];\n}\n\n/** A place on the map where work is waiting. */\n/**\n * A place on the map with work at it, and exactly how much of which kind.\n *\n * Every thing is counted once, at one place, in one of the four numbers:\n *\n * - A queue entry counts as `waiting` at the atlas id of its `queue.add`.\n * - A pool job counts at the atlas id of its latest pool event, by its\n * state: `poolWaiting` (queued, no thread yet), `poolRunning` (a thread\n * runs it), `poolDone` (finished or posted, not yet delivered).\n * - A request in the \"pool\" queue whose job is known (tied to it by\n * `pool.queued` or `pool.link`) is the same piece of work as that job. It\n * is represented by the job only and its queue entry is not counted. An\n * entry of the \"pool\" queue is counted on its own (as `waiting`) only when\n * no job is known for it.\n *\n * So with six pbkdf2 requests, four of them on threads: the submit place\n * has poolWaiting 2 and nothing else, the worker place has poolRunning 4.\n */\nexport interface WaitingPlace {\n /** Atlas id. */\n at: string;\n /** The total: waiting + poolWaiting + poolRunning + poolDone. */\n count: number;\n /** The weakest certainty among the events these things come from (model < inferred < observed). */\n c: Certainty;\n /** Queue entries waiting here. */\n waiting: number;\n /** Pool jobs here that wait for a thread. */\n poolWaiting: number;\n /** Pool jobs here that a thread is running. */\n poolRunning: number;\n /** Pool jobs here whose work has finished (or whose result is posted) and has not been delivered. */\n poolDone: number;\n /** The queues the `waiting` entries are in. */\n queues: QueueName[];\n /** True when any of the three pool numbers is not zero. */\n pool: boolean;\n}\n\nexport interface FocusView {\n /** Atlas id where the action is: the `at` of the latest event that has one. */\n at: string | null;\n from: Fact | null;\n kind: EventKind | null;\n /** Atlas ids with work at them: queue entries waiting, pool jobs waiting, running or done. Sorted by id. See WaitingPlace for how things are counted. */\n waiting: WaitingPlace[];\n}\n\nexport interface LogEntry {\n index: number;\n event: NmEvent;\n /** True when the reducer skipped this event (unknown kind or malformed). */\n skipped: boolean;\n}\n\nexport interface ProblemCounts {\n /** Events with a kind this version does not know. */\n unknown: number;\n /** Events that are not an object, have no usable time, or lack a field their kind needs. */\n malformed: number;\n /**\n * Events that disagree with earlier ones (a callback end with no start, a\n * thread starting a job while it runs another, ...). They are applied in\n * the way that keeps the view consistent with the latest event.\n */\n inconsistent: number;\n}\n\n/** The complete state the screen draws at one position. */\nexport interface ViewState {\n /** Events applied: the state is \"after the first `position` events\". */\n position: number;\n /** Events in the store. */\n length: number;\n /** Events the reducer has prepared. Smaller than `length` only while a large batch is being indexed (see Replay.pump). */\n ready: number;\n /** True while the run has not ended. */\n live: boolean;\n /** Bumped every time the event list changes. */\n version: number;\n /** Time of the latest applied event, microseconds; never goes down as the position goes up. */\n t: number;\n /** Time of the last event in the store. */\n endT: number;\n\n run: RunView;\n main: MainThreadView;\n loop: LoopView;\n queues: Record<QueueName, QueueView>;\n /** Counts of async items up to this position. The items themselves: `referenced` below, or Replay.item / Replay.items / Replay.why. */\n items: {\n total: number;\n /** Present only with ViewOptions.items = \"all\": every item so far, in creation order. */\n all: ItemView[] | null;\n };\n timers: TimersView;\n pool: PoolView;\n output: OutputView;\n debug: DebugView;\n notes: NotesView;\n focus: FocusView;\n /** The latest events, oldest first, at most ViewOptions.maxLog. */\n log: LogEntry[];\n problems: ProblemCounts;\n}\n\nexport interface ViewOptions {\n /** Cap for each queue, the active timers and each pool list. Default 200. */\n maxEntries?: number;\n /** Cap for output chunks in the view. Default 200. */\n maxOutput?: number;\n /** Cap for notes in the view. Default 50. */\n maxNotes?: number;\n /** Cap for the log. Default 50. */\n maxLog?: number;\n /** \"all\" adds every item seen so far to `items.all`. Meant for small runs and tests. Default \"none\". */\n items?: 'none' | 'all';\n}\n\n// ---------------------------------------------------------------------------\n// View patches\n// ---------------------------------------------------------------------------\n\n/**\n * How an ordered list changed. The new list is: `prepend`, then the entries\n * of the old list whose number (chunk seq, event index) is in [from, to),\n * then `append`.\n */\nexport interface ListPatch<T> {\n from: number;\n to: number;\n prepend: T[];\n append: T[];\n}\n\n/**\n * The difference between two views (see diffView and applyViewPatch). A\n * patch applies to the view made by the patch before it; a `full` patch\n * applies to nothing and carries everything.\n */\nexport interface ViewPatch {\n full: boolean;\n /** Parts of the view that changed, each one whole. */\n set: Partial<Pick<ViewState, 'position' | 'length' | 'ready' | 'live' | 'version' | 't' | 'endT' | 'run' | 'main' | 'loop' | 'items' | 'timers' | 'pool' | 'debug' | 'notes' | 'focus' | 'problems'>>;\n /** The queues that changed, each one whole. */\n queues: Partial<Record<QueueName, QueueView>>;\n /** null: the output part is unchanged. */\n output: ({ total: number; chars: number } & ListPatch<OutputChunk>) | null;\n /** null: the log is unchanged. */\n log: ListPatch<LogEntry> | null;\n}\n\n// ---------------------------------------------------------------------------\n// Event store\n// ---------------------------------------------------------------------------\n\n/** The `events` message of the helper protocol, without the envelope. */\nexport interface EventBatch {\n /** The first `base` events stay as they are. */\n base: number;\n /** They are followed by these. */\n events: readonly NmEvent[];\n}\n\nexport type StoreStatus = 'empty' | 'live' | 'ended';\n\nexport interface StoreChange {\n /**\n * The lowest index whose event changed, was added or was removed. State at\n * positions up to and including `from` is unaffected; everything after it\n * must be recomputed.\n */\n from: number;\n /** Length before and after. */\n previousLength: number;\n length: number;\n /** True when events that were in the list were replaced or removed (a late tail). */\n truncated: boolean;\n /** True when the whole run was replaced: reset() or load(). Views go back to position 0. */\n replaced: boolean;\n status: StoreStatus;\n version: number;\n /**\n * Set when the batch was not applied: its `base` was beyond the end of the\n * list (events are missing in between) or not a whole number from 0 up.\n */\n rejected: 'gap' | 'bad-base' | null;\n}\n\n// ---------------------------------------------------------------------------\n// Stepping\n// ---------------------------------------------------------------------------\n\n/**\n * What a step stops at. A step moves to the position just after the next\n * (or previous) event of the kind.\n * - event: any event\n * - step: a \"meaningful\" event: anything except the pure signals listed in SIGNAL_KINDS\n * - callback: `callback.start`\n * - phase: `phase.enter`\n * - turn: `loop.turn`\n * - output: `output`\n * - pause: `debug.paused` or `gate.stopped`\n */\nexport type StepKind = 'event' | 'step' | 'callback' | 'phase' | 'turn' | 'output' | 'pause';\n\n// ---------------------------------------------------------------------------\n// Player\n// ---------------------------------------------------------------------------\n\n/**\n * How playback time is spent.\n * - steps: every meaningful step takes the same time (stepsPerSecond at 1x);\n * pure signals ride along with the next step. The default.\n * - time: program time, slowed down (timeScale at 1x).\n * - tick: exactly one event per tick() call, whatever the clock says.\n */\nexport type Pace = 'steps' | 'time' | 'tick';\n\nexport interface PlayerOptions {\n /** 0.05 to 20. Default 1. */\n speed?: number;\n pace?: Pace;\n /** \"steps\" pace: meaningful steps per second at 1x. Default DEFAULT_STEPS_PER_SECOND. */\n stepsPerSecond?: number;\n /** \"time\" pace: seconds of program time per second of playback at 1x. Default DEFAULT_TIME_SCALE. */\n timeScale?: number;\n /** A gap between two events longer than this (microseconds of program time) is dead time. Default DEFAULT_DEAD_TIME_US. 0 turns compression off. */\n deadTimeUs?: number;\n /** How long a dead gap plays at 1x, in milliseconds. Default DEFAULT_DEAD_TIME_PAUSE_MS. */\n deadTimePauseMs?: number;\n /** Stick to the tail while the run is live. Default true. */\n follow?: boolean;\n /** The most clock time one tick may account for, in milliseconds (a tab that was in the background does not leap). Default 250. */\n maxTickMs?: number;\n}\n\n/** Reported while the player sits in a compressed gap. */\nexport interface DeadTime {\n /** Length of the gap in milliseconds of program time: \"nothing happened for N ms\". */\n ms: number;\n /** The gap lies between the events at these two indexes. */\n afterIndex: number;\n beforeIndex: number;\n /**\n * What the main thread was doing during the gap, so the UI can word it\n * honestly: \"nothing\" (the loop was waiting), \"callback\" or \"main\"\n * (JavaScript was running and no event was sent).\n */\n during: 'nothing' | 'callback' | 'main';\n /** 0 to 1: how much of the short pause has played. */\n progress: number;\n}\n\nexport interface PlayerState {\n playing: boolean;\n speed: number;\n pace: Pace;\n /** The follow switch. */\n follow: boolean;\n /** True when the position is being held at the tail of a live run. */\n following: boolean;\n position: number;\n /** Events the player can reach (Replay.ready). */\n length: number;\n live: boolean;\n /** At the last event of a run that has ended. */\n atEnd: boolean;\n /** Playing, at the tail of a live run, waiting for more events. */\n waiting: boolean;\n deadTime: DeadTime | null;\n /** Time at the position, microseconds. */\n t: number;\n}\n\nexport type PlayerCommand =\n | { do: 'play' }\n | { do: 'pause' }\n | { do: 'toggle' }\n | { do: 'speed'; speed: number }\n | { do: 'pace'; pace: Pace }\n | { do: 'follow'; on: boolean }\n | { do: 'seek'; position: number }\n | { do: 'seekTime'; t: number }\n | { do: 'step'; kind: StepKind; direction: 1 | -1 }\n | { do: 'options'; options: PlayerOptions };\n\nexport interface PlayerTick {\n /** True when the position changed during this tick. */\n moved: boolean;\n /** True when anything in PlayerState changed during this tick. */\n changed: boolean;\n state: PlayerState;\n}\n\n// ---------------------------------------------------------------------------\n// Timeline\n// ---------------------------------------------------------------------------\n\n/**\n * What a timeline bucket counts. One count per class per bucket.\n * \"cb.*\" are callback starts by the queue the item came from; \"cb.other\" is\n * a callback of an item that was in no queue.\n */\nexport const TIMELINE_CLASSES = [\n 'cb.nextTick',\n 'cb.microtask',\n 'cb.timers',\n 'cb.immediate',\n 'cb.pool',\n 'cb.io',\n 'cb.close',\n 'cb.other',\n 'stdout',\n 'stderr',\n 'pause',\n 'pool',\n 'note',\n] as const;\nexport type TimelineClass = (typeof TIMELINE_CLASSES)[number];\n\n/** Codes used in TimelineSummary.phase: index into this list. 0 means no phase known. */\nexport const PHASE_CODES: readonly (Phase | null)[] = [null, 'timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\n\n/** Codes used in TimelineSummary.phaseCertainty: index into this list. */\nexport const CERTAINTY_CODES: readonly (Certainty | null)[] = [null, 'observed', 'inferred', 'model'];\n\nexport type TimelineAxis = 'index' | 'time';\n\n/**\n * The run cut into `width` buckets, for the scrubber. Columns are typed\n * arrays so the summary is cheap to build, to post and to draw.\n */\nexport interface TimelineSummary {\n axis: TimelineAxis;\n width: number;\n /** Store version this was built from. */\n version: number;\n /** Events covered. */\n length: number;\n /** Domain of the axis: event indexes for \"index\", microseconds for \"time\". Bucket b covers from + b*(to-from)/width. */\n from: number;\n to: number;\n /** Per bucket: index of the first event in it. For an empty bucket (time axis): index of the next event after it. Length `width`. */\n start: Uint32Array;\n /** Per bucket: number of events. Length `width`. */\n events: Uint32Array;\n /** Per bucket: the phase most of the bucket was in, as a PHASE_CODES index. */\n phase: Uint8Array;\n /** Per bucket: weakest certainty of the phase information in it, as a CERTAINTY_CODES index. */\n phaseCertainty: Uint8Array;\n /** Per bucket: 1 when the program was paused or stopped at a gate in it. */\n paused: Uint8Array;\n /** Per bucket: 1 when a callback was running in it. */\n busy: Uint8Array;\n /** Per bucket and class: counts, laid out as counts[bucket * TIMELINE_CLASSES.length + classIndex]. */\n counts: Uint32Array;\n}\n\nexport interface PauseMarker {\n kind: 'debug' | 'gate';\n /** Index and time of `debug.paused` / `gate.stopped`. */\n index: number;\n t: number;\n /** Index of the matching `debug.resumed` / `gate.released`. null while still paused. */\n endIndex: number | null;\n /** From the resume event. */\n ms: number | null;\n reason: string;\n timeKeptRunning: boolean;\n}\n\nexport interface NoteMarker {\n index: number;\n t: number;\n level: 'info' | 'warn';\n text: string;\n}\n\nexport interface TimelineMarkers {\n version: number;\n pauses: PauseMarker[];\n notes: NoteMarker[];\n /** Event indexes of `loop.turn`, ascending, and the turn number of each. */\n turnIndex: Uint32Array;\n turnNumber: Uint32Array;\n /** Event indexes of `output`, ascending, and the stream of each (0 stdout, 1 stderr). */\n outputIndex: Uint32Array;\n outputStream: Uint8Array;\n}\n\n// ---------------------------------------------------------------------------\n// Recordings and share links\n// ---------------------------------------------------------------------------\n\nexport interface OpenOptions {\n /** Refuse input that unpacks to more than this many bytes. Default MAX_RECORDING_BYTES. */\n maxBytes?: number;\n}\n\nexport interface SaveOptions {\n /** true: gzip-compressed bytes. false: the UTF-8 text. Default false. */\n gzip?: boolean;\n}\n\nexport type ShareResult =\n | {\n ok: true;\n /** Goes after the \"#\" of the player URL. Starts with FRAGMENT_PREFIX. */\n fragment: string;\n /** Length of `fragment` in characters. */\n length: number;\n /** True when it is at most SHARE_LINK_SAFE_CHARS: it also fits places with tight message limits. */\n fitsEverywhere: boolean;\n }\n | {\n ok: false;\n reason: 'too-big';\n /** The length the fragment would have had, and the limit it exceeds. */\n length: number;\n limit: number;\n /** \"Too big to share as a link, share the file instead\", with the numbers. */\n message: string;\n };\n\nexport interface ShareOptions {\n /** Default SHARE_LINK_MAX_CHARS. */\n maxChars?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Worker protocol\n// ---------------------------------------------------------------------------\n\n/** Questions the UI can ask about the run. Answers are about the current position unless a position is given. */\nexport type ReplayQuery =\n /** One item with its life. */\n | { what: 'item'; id: number }\n /** \"Why did this run?\": the item, then the item that scheduled it, and so on up to the main script. */\n | { what: 'why'; id: number }\n /** Items in creation order. */\n | { what: 'items'; from: number; limit: number }\n /** Output chunks by seq, `from` included, `to` excluded. */\n | { what: 'output'; from: number; to: number }\n /** Events by index, `from` included, `to` excluded (at most 1,000 per call). */\n | { what: 'events'; from: number; to: number }\n /** The view at another position, without moving the player. */\n | { what: 'viewAt'; position: number };\n\nexport type ReplayAnswer =\n | { what: 'item'; item: ItemView | null }\n | { what: 'why'; chain: ItemView[] }\n | { what: 'items'; items: ItemView[]; total: number }\n | { what: 'output'; chunks: OutputChunk[] }\n | { what: 'events'; entries: LogEntry[] }\n | { what: 'viewAt'; view: ViewState };\n\n/** UI -> worker (or -> ReplayHost on the main thread). */\nexport type HostRequest =\n /** Forget the run and start empty. */\n | { op: 'reset' }\n /** A batch from the helper's `events` message. */\n | { op: 'events'; base: number; events: NmEvent[] }\n /** The helper's `run.ended`: the list is final. */\n | { op: 'ended' }\n /** Open a recording (text, or bytes that are text or gzip). Replaces the run. Nothing is executed. */\n | { op: 'open'; id: number; data: string | ArrayBuffer | Uint8Array }\n /** Open a share link fragment. Replaces the run. Nothing is executed. */\n | { op: 'openFragment'; id: number; fragment: string }\n /** Encode the run held by the host as a recording file. */\n | { op: 'save'; id: number; header: RecordingHeader; gzip: boolean }\n /** Encode the run held by the host as a share link fragment. */\n | { op: 'share'; id: number; header: RecordingHeader }\n | { op: 'player'; cmd: PlayerCommand }\n /**\n * The UI's clock, normally sent once per animation frame. The host answers\n * each tick with at most one `view` (only when something changed). Without\n * ticks the host runs on its own timer (see `configure.clock`).\n */\n | { op: 'tick'; now: number }\n | {\n op: 'configure';\n /** Merged into the options of posted views. The host starts with maxEntries 60, maxOutput 50, maxLog 30 (smaller than Replay.view: a posted view is copied). */\n view?: ViewOptions;\n /**\n * \"full\" (default): every post is a whole view (`view` messages).\n * \"patch\": posts are `patch` messages carrying only what changed since\n * the post before; rebuild the view with applyViewPatch. Sending this\n * again makes the next patch a full one (use it to resynchronise).\n */\n views?: 'full' | 'patch';\n /** \"external\": the UI sends `tick`. \"internal\": the host ticks itself about 60 times a second. Default \"internal\". */\n clock?: 'external' | 'internal';\n /** Ask for timeline summaries at this width; null stops them. They are re-sent when the run changes. */\n timeline?: { width: number; axis: TimelineAxis } | null;\n /** Ask for marker lists; re-sent when the run changes. */\n markers?: boolean;\n }\n | { op: 'query'; id: number; q: ReplayQuery };\n\n/** worker (or ReplayHost) -> UI. */\nexport type HostMessage =\n | { op: 'ready' }\n | { op: 'view'; view: ViewState; player: PlayerState }\n /** Instead of `view` when `configure.views` is \"patch\". */\n | { op: 'patch'; patch: ViewPatch; player: PlayerState }\n | { op: 'timeline'; summary: TimelineSummary }\n | { op: 'markers'; markers: TimelineMarkers }\n | { op: 'answer'; re: number; answer: ReplayAnswer }\n | { op: 'opened'; re: number; header: RecordingHeader; events: number }\n | { op: 'saved'; re: number; bytes: Uint8Array }\n | { op: 'shared'; re: number; result: ShareResult }\n | { op: 'error'; re: number | null; message: string };\n","/**\n * The event list of one run.\n *\n * The helper sends the list in batches of the form \"the first `base` events\n * as before, followed by these\". Usually `base` is the current length (a\n * plain append). Trace events are delivered late, at safe points; the helper\n * then re-sends the tail from the first position that changed. apply()\n * implements exactly that and reports the lowest index that changed, so that\n * everything computed from the list knows from where to recompute.\n *\n * The store keeps events as they came, including ones the reducer will skip\n * (unknown kinds, malformed): indexes must stay equal to the helper's.\n */\n\nimport type { NmEvent } from '@nodejs-map/event-format';\nimport type { EventBatch, StoreChange, StoreStatus } from './types.ts';\n\nexport class EventStore {\n #events: NmEvent[] = [];\n #version = 0;\n #ended = false;\n #listeners = new Set<(change: StoreChange) => void>();\n\n /** The events, in order. Do not change this array; use apply(). */\n get events(): readonly NmEvent[] {\n return this.#events;\n }\n\n get length(): number {\n return this.#events.length;\n }\n\n /** Bumped on every change. */\n get version(): number {\n return this.#version;\n }\n\n /**\n * - empty: no events yet\n * - live: events are still arriving\n * - ended: the list is final (end() was called or a finished run was loaded)\n */\n get status(): StoreStatus {\n if (this.#ended) return 'ended';\n return this.#events.length === 0 ? 'empty' : 'live';\n }\n\n /** True while more events can arrive: from the first event until the run ends. */\n get live(): boolean {\n return !this.#ended && this.#events.length > 0;\n }\n\n /**\n * Truncate-and-append: keep the first `base` events, then add `events`.\n *\n * A batch whose `base` is beyond the end of the list cannot be applied\n * (events are missing in between); it is refused and the change says so in\n * `rejected`. A batch after end() re-opens nothing: a final list can still\n * be corrected by the helper (late trace events can arrive with the last\n * batch), so it is applied and the status stays \"ended\".\n */\n apply(batch: EventBatch): StoreChange {\n const previousLength = this.#events.length;\n const base = batch === null || typeof batch !== 'object' ? Number.NaN : batch.base;\n const incoming = batch !== null && typeof batch === 'object' && Array.isArray(batch.events) ? (batch.events as readonly NmEvent[]) : null;\n if (!Number.isInteger(base) || base < 0 || incoming === null) return this.#refuse('bad-base');\n if (base > previousLength) return this.#refuse('gap');\n\n // A re-sent tail usually repeats some events unchanged before the first\n // late one. Skipping an identical prefix (same object, which is what an\n // in-process feeder gives us) costs nothing and narrows what has to be\n // recomputed. Events that came over a socket are new objects every time;\n // for those `from` is simply `base`, as the helper promises.\n let from = base;\n let skip = 0;\n while (from < previousLength && skip < incoming.length && this.#events[from] === incoming[skip]) {\n from++;\n skip++;\n }\n const truncated = from < previousLength;\n if (!truncated && skip === incoming.length) {\n // Nothing changed at all.\n return this.#change(previousLength, previousLength, false, false, false);\n }\n if (truncated) this.#events.length = from;\n for (let i = skip; i < incoming.length; i++) this.#events.push(incoming[i] as NmEvent);\n return this.#change(from, previousLength, truncated, false, true);\n }\n\n /** Replace everything with a finished run (an opened recording). */\n load(events: readonly NmEvent[]): StoreChange {\n const previousLength = this.#events.length;\n this.#events = Array.isArray(events) ? events.slice() : [];\n this.#ended = true;\n return this.#change(0, previousLength, previousLength > 0, true, true);\n }\n\n /** The list is final (the helper's `run.ended`). */\n end(): StoreChange {\n const n = this.#events.length;\n if (this.#ended) return this.#change(n, n, false, false, false);\n this.#ended = true;\n return this.#change(n, n, false, false, true);\n }\n\n /** Forget the run. */\n reset(): StoreChange {\n const previousLength = this.#events.length;\n this.#events = [];\n this.#ended = false;\n return this.#change(0, previousLength, previousLength > 0, true, true);\n }\n\n /** Calls `listener` after every change. Returns a function that stops it. */\n subscribe(listener: (change: StoreChange) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #refuse(why: 'gap' | 'bad-base'): StoreChange {\n const n = this.#events.length;\n return { from: n, previousLength: n, length: n, truncated: false, replaced: false, status: this.status, version: this.#version, rejected: why };\n }\n\n #change(from: number, previousLength: number, truncated: boolean, replaced: boolean, notify: boolean): StoreChange {\n if (notify) this.#version++;\n const change: StoreChange = {\n from,\n previousLength,\n length: this.#events.length,\n truncated,\n replaced,\n status: this.status,\n version: this.#version,\n rejected: null,\n };\n if (notify) for (const listener of [...this.#listeners]) listener(change);\n return change;\n }\n}\n","/**\n * The run index: everything about a run that does not depend on the position\n * being shown.\n *\n * The view state has two kinds of content. Some of it is small and changes\n * with every step (what runs now, who waits where); that is the \"live\" state\n * of reducer.ts, and keyframes hold copies of it. The rest only ever grows\n * with the run (every item ever seen, all output, all notes, the per-event\n * columns the scrubber draws). Copying that into keyframes would cost memory\n * proportional to events x items, so it is kept here once, with the index of\n * the event that produced each piece. \"The items at position P\" is then\n * \"the items whose event index is below P\": a filter, not a copy.\n *\n * The index is built in event order (add) and can be cut back (truncate)\n * when a late tail replaces the end of the list.\n *\n * Internal: not part of the public API.\n */\n\nimport type { Certainty, EventKind, NmEvent, Phase, QueueName } from '@nodejs-map/event-format';\nimport type { Fact, ItemRef, OutputChunk, PauseMarker } from './types.ts';\n\n// ---- per-event flags --------------------------------------------------------\n\nexport const F_STEP = 1; // a \"meaningful\" step stops here\nexport const F_CALLBACK = 2; // callback.start\nexport const F_PHASE = 4; // phase.enter\nexport const F_TURN = 8; // loop.turn\nexport const F_OUTPUT = 16; // output\nexport const F_PAUSE = 32; // debug.paused or gate.stopped\nexport const F_SKIP = 64; // the reducer skips this event\nexport const F_UNKNOWN = 128; // with F_SKIP: unknown kind (otherwise malformed)\n\nexport const QUEUE_NAMES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n// Lookup tables have no prototype: a name such as \"constructor\" in a bad event must not find anything.\nconst table = (entries: Record<string, number>): Record<string, number> => Object.assign(Object.create(null) as Record<string, number>, entries);\nconst QUEUE_CODE = table({ nextTick: 0, microtask: 1, timers: 2, immediate: 3, pool: 4, io: 5, close: 6 });\nexport const PHASES: readonly (Phase | null)[] = [null, 'timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\nconst PHASE_CODE = table({ timers: 1, pending: 2, idle: 3, prepare: 4, poll: 5, check: 6, closing: 7 });\n\nexport function queueCode(name: unknown): number {\n const code = typeof name === 'string' ? QUEUE_CODE[name] : undefined;\n return code === undefined ? -1 : code;\n}\n\nexport function phaseCode(name: unknown): number {\n const code = typeof name === 'string' ? PHASE_CODE[name] : undefined;\n return code === undefined ? 0 : code;\n}\n\n/**\n * Event kinds that are pure signals. A \"meaningful\" step never stops on\n * them: they are evidence, or bookkeeping that another event of the same\n * moment already shows (`item.new` and `timer.set` are followed by the\n * `queue.add` that puts the item on screen; `item.gone` of a waiting item\n * comes with its `queue.remove`).\n */\nexport const SIGNAL_KINDS: ReadonlySet<EventKind> = new Set<EventKind>([\n 'loop.sample',\n 'signal',\n 'scope',\n 'pool.thread',\n 'promise.settled',\n 'item.new',\n 'item.gone',\n 'timer.set',\n 'pool.link',\n 'clock.frozen',\n 'clock.unfrozen',\n]);\n\n/** libuv's MAX_THREADPOOL_SIZE; a thread index above it is not believable. */\nconst MAX_THREAD_INDEX = 1024;\n\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst isId = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0;\nconst isStr = (v: unknown): v is string => typeof v === 'string';\nconst isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;\n\n/**\n * Is this event usable? 0: yes. 1: unknown kind. 2: malformed.\n *\n * Only what the reducer reads is checked. Recording files are validated in\n * full by the event-format codec; live events come from our own helper. This\n * check exists so that a bad event can never crash the view or be drawn with\n * a certainty it does not have.\n */\nexport function checkEvent(value: unknown): 0 | 1 | 2 {\n if (!isObj(value)) return 2;\n const e = value;\n if (!isStr(e['k']) || !isNum(e['t'])) return 2;\n const c = e['c'];\n if (c !== 'observed' && c !== 'inferred' && c !== 'model') return 2;\n if (e['rule'] !== undefined && !isStr(e['rule'])) return 2;\n if (e['at'] !== undefined && !isStr(e['at'])) return 2;\n if (e['tid'] !== undefined && !isNum(e['tid'])) return 2;\n switch (e['k']) {\n case 'run.start':\n return isObj(e['node']) && isObj(e['caps']) && isStr(e['mode']) && isStr(e['program']) && isNum(e['poolSize']) ? 0 : 2;\n case 'run.end':\n return (e['code'] === null || e['code'] === undefined || isNum(e['code'])) && (e['signal'] === null || e['signal'] === undefined || isStr(e['signal'])) ? 0 : 2;\n case 'output':\n return (e['stream'] === 'stdout' || e['stream'] === 'stderr') && isStr(e['text']) ? 0 : 2;\n case 'item.new': {\n const loc = e['loc'];\n return isId(e['id']) &&\n isStr(e['type']) &&\n isId(e['trigger']) &&\n (e['label'] === undefined || isStr(e['label'])) &&\n (loc === undefined || (isObj(loc) && isStr(loc['url']) && isNum(loc['line'])))\n ? 0\n : 2;\n }\n case 'callback.start':\n return isId(e['id']) && isStr(e['type']) ? 0 : 2;\n case 'callback.end':\n case 'item.gone':\n case 'promise.settled':\n return isId(e['id']) ? 0 : 2;\n case 'timer.set':\n return isId(e['id']) && isNum(e['delayMs']) && typeof e['repeat'] === 'boolean' ? 0 : 2;\n case 'loop.sample':\n return isNum(e['loopCount']) && isNum(e['events']) && isNum(e['eventsWaiting']) ? 0 : 2;\n case 'scope':\n return isStr(e['name']) && isNum(e['durUs']) ? 0 : 2;\n case 'pool.thread':\n return (e['edge'] === 'start' || e['edge'] === 'end') && isStr(e['name']) ? 0 : 2;\n case 'signal':\n return isStr(e['cat']) && isStr(e['name']) && isStr(e['ph']) ? 0 : 2;\n case 'queue.add':\n case 'queue.remove':\n return queueCode(e['queue']) >= 0 && isId(e['id']) ? 0 : 2;\n case 'loop.turn':\n return isNum(e['n']) ? 0 : 2;\n case 'phase.enter':\n case 'phase.leave':\n return phaseCode(e['phase']) > 0 &&\n (e['turn'] === undefined || isNum(e['turn'])) &&\n (e['afterPoll'] === undefined || typeof e['afterPoll'] === 'boolean') &&\n (e['pollTimeoutMs'] === undefined || isNum(e['pollTimeoutMs']))\n ? 0\n : 2;\n case 'timer.fired':\n return e['lateMs'] === undefined || isNum(e['lateMs']) ? 0 : 2;\n case 'pool.queued':\n return isStr(e['job']) && isStr(e['kind']) && (e['op'] === undefined || isStr(e['op'])) && (e['id'] === undefined || isId(e['id'])) ? 0 : 2;\n case 'pool.delivered':\n case 'pool.cancelled':\n return isStr(e['job']) ? 0 : 2;\n case 'pool.started':\n case 'pool.finished':\n case 'pool.posted':\n return isStr(e['job']) && isId(e['thread']) && (e['thread'] as number) >= 1 && (e['thread'] as number) <= MAX_THREAD_INDEX ? 0 : 2;\n case 'pool.link':\n return isStr(e['job']) && isId(e['id']) ? 0 : 2;\n case 'pool.size':\n return isId(e['size']) && (e['size'] as number) >= 1 && (e['size'] as number) <= MAX_THREAD_INDEX ? 0 : 2;\n case 'debug.paused':\n return isStr(e['reason']) && Array.isArray(e['frames']) && typeof e['timeKeptRunning'] === 'boolean' ? 0 : 2;\n case 'debug.resumed':\n return isNum(e['pausedMs']) ? 0 : 2;\n case 'gate.stopped':\n return isStr(e['gate']) && (e['job'] === undefined || isStr(e['job'])) && (e['phase'] === undefined || phaseCode(e['phase']) > 0) ? 0 : 2;\n case 'gate.released':\n return isNum(e['stoppedMs']) ? 0 : 2;\n case 'clock.frozen':\n return e['why'] === undefined || isStr(e['why']) ? 0 : 2;\n case 'clock.unfrozen':\n return isNum(e['hiddenMs']) ? 0 : 2;\n case 'note':\n return (e['level'] === 'info' || e['level'] === 'warn') && isStr(e['text']) ? 0 : 2;\n default:\n return 1;\n }\n}\n\n// ---- records ------------------------------------------------------------------\n\nexport interface TimerRec {\n /** Index of `timer.set`. */\n setIndex: number;\n delayMs: number;\n repeat: boolean;\n /** Indexes of the events that armed it: `timer.set`, then each `queue.add` that put it back after a run. Ascending. */\n arms: number[];\n /** Index of the event that cleared it, or -1. */\n clearedIndex: number;\n}\n\nexport interface ItemRec {\n id: number;\n /** The item as `item.new` described it; before that event, as far as other events showed it. */\n ref: ItemRef;\n /** When the item was seen before its `item.new`: what was known until then. */\n early: ItemRef | null;\n /** Index of `item.new`, or -1. */\n newIndex: number;\n /** Index of the first event that mentioned the item. */\n firstIndex: number;\n /** Indexes of `callback.start` / `callback.end`, ascending. */\n starts: number[];\n ends: number[];\n goneIndex: number;\n settledIndex: number;\n /** Indexes of the `item.new` events that name this item as trigger, ascending. */\n children: number[];\n /** Pool jobs tied to this item, with the index of the event that tied them. */\n jobNames: string[];\n jobIndexes: number[];\n timer: TimerRec | null;\n}\n\n/** Timer states as numbers; 0 means \"no timer at this position\". */\nexport const T_NONE = 0;\nexport const T_WAITING = 1;\nexport const T_RUNNING = 2;\nexport const T_DONE = 3;\nexport const T_CLEARED = 4;\n\n/** How many entries of an ascending list are below `limit`. */\nexport function countBelow(list: readonly number[], limit: number): number {\n let n = list.length;\n if (n <= 16) {\n while (n > 0 && (list[n - 1] as number) >= limit) n--;\n return n;\n }\n let lo = 0;\n while (lo < n) {\n const mid = (lo + n) >>> 1;\n if ((list[mid] as number) < limit) lo = mid + 1;\n else n = mid;\n }\n return lo;\n}\n\n/** The last entry of an ascending list that is below `limit`, or -1. */\nexport function lastBelow(list: readonly number[], limit: number): number {\n const n = countBelow(list, limit);\n return n === 0 ? -1 : (list[n - 1] as number);\n}\n\nexport function factOf(e: NmEvent, index: number): Fact {\n return { c: e.c, rule: e.rule === undefined ? null : e.rule, index, t: e.t };\n}\n\nconst WEAKNESS: Record<Certainty, number> = { observed: 0, inferred: 1, model: 2 };\n/** The weaker of two certainties (model < inferred < observed). */\nexport function weaker(a: Certainty, b: Certainty): Certainty {\n return WEAKNESS[a] >= WEAKNESS[b] ? a : b;\n}\n\n// ---- the index ------------------------------------------------------------------\n\nexport class RunIndex {\n /** Events indexed so far. */\n n = 0;\n /** Per event: F_* bits. */\n flags = new Uint8Array(1024);\n /**\n * Per block of 256 events: the F_* bits of all its events or-ed together.\n * A search for the next or previous stop of a kind skips whole blocks that\n * have none, so it stays fast when the kind is rare or absent in a long run.\n */\n blockFlags = new Uint8Array(4);\n /** Per event: its time, made non-decreasing (the largest `t` up to it), microseconds. */\n tMono = new Float64Array(1024);\n /**\n * Per event, written by the reducer after it applied the event: the loop\n * phase (bits 0-2), the certainty of that phase (bits 3-4, CERTAINTY_CODES),\n * paused or stopped (bit 5), a callback is running (bit 6).\n */\n tlState = new Uint8Array(1024);\n /** Per event: 1 + index into TIMELINE_CLASSES, or 0. Written by the reducer. */\n tlClass = new Uint8Array(1024);\n\n readonly items = new Map<number, ItemRec>();\n /** Items in order of first mention. */\n readonly order: ItemRec[] = [];\n readonly output: OutputChunk[] = [];\n /** Characters written up to and including each chunk. */\n readonly outputChars: number[] = [];\n /** Event indexes of notes. */\n readonly notes: number[] = [];\n /** Event indexes of `loop.turn` and the turn numbers. */\n readonly turns: number[] = [];\n readonly turnNumbers: number[] = [];\n readonly pauses: PauseMarker[] = [];\n\n #openDebug: PauseMarker | null = null;\n #openGate: PauseMarker | null = null;\n /** Log of record changes: which item was touched by which event. Lets truncate() undo them. */\n #touchIndex: number[] = [];\n #touchId: number[] = [];\n\n #grow(): void {\n const size = this.flags.length * 2;\n const grow8 = (a: Uint8Array) => {\n const b = new Uint8Array(size);\n b.set(a);\n return b;\n };\n this.flags = grow8(this.flags);\n const blocks = new Uint8Array(size >> 8);\n blocks.set(this.blockFlags);\n this.blockFlags = blocks;\n this.tlState = grow8(this.tlState);\n this.tlClass = grow8(this.tlClass);\n const t = new Float64Array(size);\n t.set(this.tMono);\n this.tMono = t;\n }\n\n #touch(rec: ItemRec, i: number): void {\n this.#touchIndex.push(i);\n this.#touchId.push(rec.id);\n }\n\n /** The record of item `id`, made on first mention. */\n #ensure(id: number, i: number, type: string): ItemRec {\n let rec = this.items.get(id);\n if (rec === undefined) {\n rec = {\n id,\n ref: { id, type, label: null, trigger: 0, loc: null, created: null },\n early: null,\n newIndex: -1,\n firstIndex: i,\n starts: [],\n ends: [],\n goneIndex: -1,\n settledIndex: -1,\n children: [],\n jobNames: [],\n jobIndexes: [],\n timer: null,\n };\n this.items.set(id, rec);\n this.order.push(rec);\n this.#touch(rec, i);\n } else if (type !== '?' && rec.newIndex < 0 && rec.ref.type === '?') {\n // The type of an item first seen without one. A type is a fixed\n // property of the item, not a state, so it is not rolled back by\n // position; truncate() drops it with the record if needed.\n rec.ref = { ...rec.ref, type };\n }\n return rec;\n }\n\n /**\n * Index the event at position `i` (which must be the next one). Returns\n * its flags. Never throws on bad input: such events get F_SKIP.\n */\n add(e: NmEvent, i: number): number {\n if (i >= this.flags.length) this.#grow();\n const prevT = i === 0 ? 0 : (this.tMono[i - 1] as number);\n this.tlState[i] = 0;\n this.tlClass[i] = 0;\n const bad = checkEvent(e);\n if (bad !== 0) {\n const f = bad === 1 ? F_SKIP | F_UNKNOWN : F_SKIP;\n this.flags[i] = f;\n if ((i & 255) === 0) this.blockFlags[i >> 8] = f;\n else this.blockFlags[i >> 8] = (this.blockFlags[i >> 8] as number) | f;\n // An unknown kind from a newer helper still has a usable time.\n const t = bad === 1 ? (e as { t: number }).t : prevT;\n this.tMono[i] = i === 0 || t > prevT ? t : prevT;\n this.n = i + 1;\n return f;\n }\n this.tMono[i] = i === 0 || e.t > prevT ? e.t : prevT;\n let f = SIGNAL_KINDS.has(e.k) ? 0 : F_STEP;\n\n switch (e.k) {\n case 'item.new': {\n const ref: ItemRef = {\n id: e.id,\n type: e.type,\n label: e.label === undefined ? null : e.label,\n trigger: e.trigger,\n loc: e.loc === undefined ? null : e.loc,\n created: factOf(e, i),\n };\n const existing = this.items.get(e.id);\n if (existing === undefined) {\n const rec = this.#ensure(e.id, i, e.type);\n rec.ref = ref;\n rec.newIndex = i;\n const parent = this.items.get(e.trigger);\n if (parent !== undefined && parent !== rec) {\n parent.children.push(i);\n this.#touch(parent, i);\n }\n } else if (existing.newIndex < 0) {\n // Seen earlier in another event; now we learn what it is.\n existing.early = existing.ref;\n existing.ref = ref;\n existing.newIndex = i;\n this.#touch(existing, i);\n const parent = this.items.get(e.trigger);\n if (parent !== undefined && parent !== existing) {\n parent.children.push(i);\n this.#touch(parent, i);\n }\n }\n // A second item.new for the same id is ignored here; the reducer counts it as inconsistent.\n break;\n }\n case 'callback.start': {\n const rec = this.#ensure(e.id, i, e.type);\n rec.starts.push(i);\n this.#touch(rec, i);\n f |= F_CALLBACK;\n break;\n }\n case 'callback.end': {\n const rec = this.#ensure(e.id, i, '?');\n rec.ends.push(i);\n this.#touch(rec, i);\n break;\n }\n case 'item.gone': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.goneIndex < 0) rec.goneIndex = i;\n const tm = rec.timer;\n // A timer destroyed while it was armed was cleared (clearTimeout, clearInterval).\n if (tm !== null && tm.clearedIndex < 0 && (tm.arms[tm.arms.length - 1] as number) > lastOf(rec.starts)) tm.clearedIndex = i;\n this.#touch(rec, i);\n break;\n }\n case 'promise.settled': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.settledIndex < 0) rec.settledIndex = i;\n this.#touch(rec, i);\n break;\n }\n case 'timer.set': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.timer === null) rec.timer = { setIndex: i, delayMs: e.delayMs, repeat: e.repeat, arms: [i], clearedIndex: -1 };\n else rec.timer.arms.push(i); // set again: armed again, first delay kept (the reducer counts it as inconsistent)\n this.#touch(rec, i);\n break;\n }\n case 'queue.add': {\n const rec = this.#ensure(e.id, i, '?');\n const tm = rec.timer;\n // A timer put back into the timers queue after a run is armed again\n // (setInterval, rule QT2 of the event format).\n if (e.queue === 'timers' && tm !== null && tm.clearedIndex < 0 && lastOf(rec.starts) > (tm.arms[tm.arms.length - 1] as number)) {\n tm.arms.push(i);\n this.#touch(rec, i);\n }\n break;\n }\n case 'queue.remove': {\n const rec = this.items.get(e.id);\n const tm = rec === undefined ? null : rec.timer;\n if (rec !== undefined && tm !== null && e.queue === 'timers' && tm.clearedIndex < 0) {\n // Cleared: while armed, or (a repeating timer) from inside its own callback.\n if (tm.repeat || (tm.arms[tm.arms.length - 1] as number) > lastOf(rec.starts)) {\n tm.clearedIndex = i;\n this.#touch(rec, i);\n }\n }\n break;\n }\n case 'pool.queued':\n if (e.id !== undefined) this.#tie(e.id, e.job, i);\n break;\n case 'pool.link':\n this.#tie(e.id, e.job, i);\n break;\n case 'output': {\n const before = this.outputChars.length === 0 ? 0 : (this.outputChars[this.outputChars.length - 1] as number);\n this.output.push({ seq: this.output.length, index: i, t: e.t, stream: e.stream, text: e.text });\n this.outputChars.push(before + e.text.length);\n f |= F_OUTPUT;\n break;\n }\n case 'note':\n this.notes.push(i);\n break;\n case 'loop.turn':\n this.turns.push(i);\n this.turnNumbers.push(e.n);\n f |= F_TURN;\n break;\n case 'phase.enter':\n f |= F_PHASE;\n break;\n case 'debug.paused': {\n const m: PauseMarker = { kind: 'debug', index: i, t: e.t, endIndex: null, ms: null, reason: e.reason, timeKeptRunning: e.timeKeptRunning };\n this.pauses.push(m);\n this.#openDebug = m;\n f |= F_PAUSE;\n break;\n }\n case 'debug.resumed':\n if (this.#openDebug !== null) {\n this.#openDebug.endIndex = i;\n this.#openDebug.ms = e.pausedMs;\n this.#openDebug = null;\n }\n break;\n case 'gate.stopped': {\n const m: PauseMarker = { kind: 'gate', index: i, t: e.t, endIndex: null, ms: null, reason: e.gate, timeKeptRunning: false };\n this.pauses.push(m);\n this.#openGate = m;\n f |= F_PAUSE;\n break;\n }\n case 'gate.released':\n if (this.#openGate !== null) {\n this.#openGate.endIndex = i;\n this.#openGate.ms = e.stoppedMs;\n this.#openGate = null;\n }\n break;\n default:\n break;\n }\n this.flags[i] = f;\n if ((i & 255) === 0) this.blockFlags[i >> 8] = f;\n else this.blockFlags[i >> 8] = (this.blockFlags[i >> 8] as number) | f;\n this.n = i + 1;\n return f;\n }\n\n /** The first index in [from, n) whose flags have a bit of `mask`, or -1. */\n nextWith(mask: number, from: number): number {\n const flags = this.flags;\n const blocks = this.blockFlags;\n const n = this.n;\n let i = Math.max(0, from);\n while (i < n) {\n if (((blocks[i >> 8] as number) & mask) === 0) {\n i = ((i >> 8) + 1) << 8; // nothing in this block\n continue;\n }\n const end = Math.min(n, ((i >> 8) + 1) << 8);\n for (; i < end; i++) if (((flags[i] as number) & mask) !== 0) return i;\n }\n return -1;\n }\n\n /** The last index in [0, from] whose flags have a bit of `mask`, or -1. */\n previousWith(mask: number, from: number): number {\n const flags = this.flags;\n const blocks = this.blockFlags;\n let i = Math.min(this.n - 1, from);\n while (i >= 0) {\n if (((blocks[i >> 8] as number) & mask) === 0) {\n i = ((i >> 8) << 8) - 1;\n continue;\n }\n const start = (i >> 8) << 8;\n for (; i >= start; i--) if (((flags[i] as number) & mask) !== 0) return i;\n }\n return -1;\n }\n\n #tie(id: number, job: string, i: number): void {\n const rec = this.#ensure(id, i, '?');\n rec.jobNames.push(job);\n rec.jobIndexes.push(i);\n this.#touch(rec, i);\n }\n\n /** Forget everything that came from events at index `from` and above. */\n truncate(from: number): void {\n if (from >= this.n) return;\n const ti = this.#touchIndex;\n const tid = this.#touchId;\n while (ti.length > 0 && (ti[ti.length - 1] as number) >= from) {\n ti.pop();\n const rec = this.items.get(tid.pop() as number);\n if (rec === undefined) continue;\n if (rec.firstIndex >= from) {\n this.items.delete(rec.id);\n continue;\n }\n if (rec.newIndex >= from) {\n rec.ref = rec.early as ItemRef;\n rec.early = null;\n rec.newIndex = -1;\n }\n cut(rec.starts, from);\n cut(rec.ends, from);\n cut(rec.children, from);\n const keep = countBelow(rec.jobIndexes, from);\n rec.jobIndexes.length = keep;\n rec.jobNames.length = keep;\n if (rec.goneIndex >= from) rec.goneIndex = -1;\n if (rec.settledIndex >= from) rec.settledIndex = -1;\n const tm = rec.timer;\n if (tm !== null) {\n if (tm.setIndex >= from) rec.timer = null;\n else {\n cut(tm.arms, from);\n if (tm.clearedIndex >= from) tm.clearedIndex = -1;\n }\n }\n }\n const order = this.order;\n while (order.length > 0 && (order[order.length - 1] as ItemRec).firstIndex >= from) order.pop();\n while (this.output.length > 0 && (this.output[this.output.length - 1] as OutputChunk).index >= from) {\n this.output.pop();\n this.outputChars.pop();\n }\n cut(this.notes, from);\n const turns = countBelow(this.turns, from);\n this.turns.length = turns;\n this.turnNumbers.length = turns;\n const pauses = this.pauses;\n while (pauses.length > 0 && (pauses[pauses.length - 1] as PauseMarker).index >= from) pauses.pop();\n // A pause that ended at or after `from` is open again. Only the latest\n // remaining pause of each kind can be affected: a later one of the same\n // kind would have started after that end, and was dropped above.\n this.#openDebug = this.#reopen('debug', from);\n this.#openGate = this.#reopen('gate', from);\n // The block that `from` cuts through keeps only the bits of the events that are left.\n // (Later blocks are started afresh by add() when their first event arrives.)\n if ((from & 255) !== 0) {\n let bits = 0;\n for (let i = from & ~255; i < from; i++) bits |= this.flags[i] as number;\n this.blockFlags[from >> 8] = bits;\n }\n this.n = from;\n }\n\n #reopen(kind: 'debug' | 'gate', from: number): PauseMarker | null {\n for (let k = this.pauses.length - 1; k >= 0; k--) {\n const m = this.pauses[k] as PauseMarker;\n if (m.kind !== kind) continue;\n if (m.endIndex !== null && m.endIndex >= from) {\n m.endIndex = null;\n m.ms = null;\n }\n return m.endIndex === null ? m : null;\n }\n return null;\n }\n\n /** How many items had been mentioned before position `p`. */\n itemsBefore(p: number): number {\n const order = this.order;\n let lo = 0;\n let hi = order.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((order[mid] as ItemRec).firstIndex < p) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n /** The item as it was known at position `p`. */\n refAt(rec: ItemRec, p: number): ItemRef {\n return rec.newIndex >= 0 && rec.newIndex >= p && rec.early !== null ? rec.early : rec.ref;\n }\n\n /** State of the item's timer at position `p`. `running`: its callback is on the stack at `p`. */\n timerStateAt(rec: ItemRec, p: number, running: boolean): number {\n const tm = rec.timer;\n if (tm === null || tm.setIndex >= p) return T_NONE;\n if (tm.clearedIndex >= 0 && tm.clearedIndex < p) return T_CLEARED;\n if (running) return T_RUNNING;\n return lastBelow(tm.arms, p) > lastBelow(rec.starts, p) ? T_WAITING : T_DONE;\n }\n}\n\nfunction lastOf(list: readonly number[]): number {\n return list.length === 0 ? -1 : (list[list.length - 1] as number);\n}\n\n/** Drop the entries of an ascending list that are `from` or above. */\nfunction cut(list: number[], from: number): void {\n let n = list.length;\n while (n > 0 && (list[n - 1] as number) >= from) n--;\n list.length = n;\n}\n","/**\n * Validation of events and recording headers.\n *\n * A recording file is untrusted input: it may come from a shared link. These\n * functions check every field, reject unknown kinds and unknown fields, cap\n * the length of every string, and return a fresh plain object that contains\n * nothing but the checked fields. They never evaluate anything.\n */\n\nimport type { Capabilities, EventKind, Frame, Loc, NmEvent, NodeInfo, RecordingHeader } from './types.ts';\nimport { FORMAT_VERSION } from './types.ts';\n\n/** Thrown for anything wrong with a recording, an event or a header. */\nexport class RecordingError extends Error {\n /** 1-based line of the recording text, when the error belongs to one. */\n readonly line: number | undefined;\n constructor(message: string, line?: number) {\n super(line === undefined ? message : `line ${line}: ${message}`);\n this.name = 'RecordingError';\n this.line = line;\n }\n}\n\n/** Limits. Generous for real recordings, small enough to bound memory per field. */\nexport const LIMITS = {\n /** Output text of one write, source text of one file. */\n text: 1_000_000,\n /** Names, labels, types, urls, atlas ids. */\n name: 512,\n /** Frames of one paused stack. */\n frames: 200,\n /** Keys of a `signal` event's args. */\n args: 32,\n /** Source files carried in a header. */\n sources: 64,\n} as const;\n\ntype Check = (v: unknown, path: string) => unknown;\n\nfunction fail(path: string, what: string): never {\n throw new RecordingError(`${path}: ${what}`);\n}\n\nconst str = (max: number): Check => (v, p) => {\n if (typeof v !== 'string') fail(p, 'must be a string');\n if ((v as string).length > max) fail(p, `string longer than ${max}`);\n return v;\n};\nconst name = str(LIMITS.name);\nconst text = str(LIMITS.text);\nconst num: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isFinite(v)) fail(p, 'must be a finite number');\n return v;\n};\nconst nonNeg: Check = (v, p) => {\n num(v, p);\n if ((v as number) < 0) fail(p, 'must not be negative');\n return v;\n};\nconst int: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isSafeInteger(v)) fail(p, 'must be an integer');\n return v;\n};\n/** A libuv pool size: 1 to 1024 threads (MAX_THREADPOOL_SIZE). */\nconst poolSize: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || v > 1024) fail(p, 'must be a whole number from 1 to 1024');\n return v;\n};\nconst count: Check = (v, p) => {\n int(v, p);\n if ((v as number) < 0) fail(p, 'must not be negative');\n return v;\n};\nconst bool: Check = (v, p) => {\n if (typeof v !== 'boolean') fail(p, 'must be true or false');\n return v;\n};\nconst oneOf = (...allowed: readonly string[]): Check => (v, p) => {\n if (typeof v !== 'string' || !allowed.includes(v)) fail(p, `must be one of ${allowed.join(', ')}`);\n return v;\n};\nconst nullable = (c: Check): Check => (v, p) => (v === null ? null : c(v, p));\n\ninterface Field {\n check: Check;\n optional?: true;\n}\ntype Spec = Record<string, Field>;\nconst req = (check: Check): Field => ({ check });\nconst opt = (check: Check): Field => ({ check, optional: true });\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\n/** Checks `v` against `spec`; unknown keys are an error. Returns a fresh object. */\nfunction object(spec: Spec, v: unknown, path: string, extraAllowed?: ReadonlySet<string>): Record<string, unknown> {\n if (!isPlainObject(v)) fail(path, 'must be an object');\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v)) {\n if (!Object.hasOwn(spec, key) && !(extraAllowed && extraAllowed.has(key))) fail(path, `unknown field \"${key}\"`);\n }\n for (const key of Object.keys(spec)) {\n const f = spec[key] as Field;\n const value = Object.hasOwn(v, key) ? v[key] : undefined;\n if (value === undefined) {\n if (!f.optional) fail(path, `missing field \"${key}\"`);\n continue;\n }\n out[key] = f.check(value, path === '' ? key : `${path}.${key}`);\n }\n return out;\n}\nconst obj = (spec: Spec): Check => (v, p) => object(spec, v, p);\n\nconst LOC: Spec = { url: req(name), line: req(count), col: opt(count) };\nconst FRAME: Spec = { fn: req(name), loc: req(obj(LOC)), origin: req(oneOf('user', 'node', 'other')), at: opt(name) };\nconst NODE_INFO: Spec = { version: req(name), v8: req(name), uv: req(name), platform: req(name), arch: req(name) };\nconst CERT = oneOf('observed', 'inferred', 'model');\nconst CAPS: Spec = {\n provider: req(oneOf('user', 'pinned', 'probe')),\n jsDebugger: req(bool),\n asyncItems: req(bool),\n poolThreads: req(oneOf('delayed', 'live', 'none')),\n phasesTimersCheck: req(oneOf('observed', 'inferred', 'model', 'none')),\n phasesOther: req(oneOf('observed', 'inferred', 'model', 'none')),\n gates: req(obj({ phase: req(bool), timer: req(bool), poolStart: req(bool), poolPost: req(bool) })),\n frozenClock: req(bool),\n};\nconst PHASE = oneOf('timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing');\nconst QUEUE = oneOf('nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close');\n\nconst frames: Check = (v, p) => {\n if (!Array.isArray(v)) fail(p, 'must be a list');\n if (v.length > LIMITS.frames) fail(p, `more than ${LIMITS.frames} frames`);\n return v.map((f, i) => object(FRAME, f, `${p}[${i}]`));\n};\n\nconst args: Check = (v, p) => {\n if (!isPlainObject(v)) fail(p, 'must be an object');\n const keys = Object.keys(v);\n if (keys.length > LIMITS.args) fail(p, `more than ${LIMITS.args} keys`);\n const out: Record<string, string | number | boolean | null> = Object.create(null) as Record<string, string | number | boolean | null>;\n for (const key of keys) {\n if (key.length > LIMITS.name) fail(p, 'key too long');\n const x = v[key];\n if (x === null || typeof x === 'boolean') out[key] = x;\n else if (typeof x === 'number' && Number.isFinite(x)) out[key] = x;\n else if (typeof x === 'string' && x.length <= LIMITS.text) out[key] = x;\n else fail(`${p}.${key}`, 'must be a string, a finite number, true, false or null');\n }\n // a plain object again (the null prototype above only protects the copy loop)\n return Object.assign({}, out);\n};\n\n/** Fields every event may carry besides its payload. */\nconst BASE: Spec = {\n k: req(name),\n t: req(num),\n tq: opt(oneOf('approx', 'tie')),\n src: req(oneOf('hooks', 'trace', 'cdp', 'probe', 'helper', 'rule')),\n c: req(CERT),\n rule: opt(str(32)),\n at: opt(name),\n tid: opt(count),\n};\n\n/** The payload fields of every kind. Keep in step with EventPayloads in types.ts. */\nconst PAYLOADS: { [K in EventKind]: Spec } = {\n 'run.start': {\n node: req(obj(NODE_INFO)),\n caps: req(obj(CAPS)),\n mode: req(oneOf('free', 'debug')),\n program: req(name),\n poolSize: req(count),\n },\n 'run.end': { code: req(nullable(int)), signal: req(nullable(name)) },\n 'output': { stream: req(oneOf('stdout', 'stderr')), text: req(text) },\n 'item.new': { id: req(count), type: req(name), trigger: req(count), label: opt(name), loc: opt(obj(LOC)) },\n 'callback.start': { id: req(count), type: req(name), close: opt(bool) },\n 'callback.end': { id: req(count) },\n 'item.gone': { id: req(count) },\n 'promise.settled': { id: req(count) },\n 'timer.set': { id: req(count), delayMs: req(nonNeg), repeat: req(bool) },\n 'loop.sample': { loopCount: req(count), events: req(count), eventsWaiting: req(count) },\n 'scope': { name: req(name), durUs: req(nonNeg) },\n 'pool.thread': { edge: req(oneOf('start', 'end')), name: req(name) },\n 'signal': { cat: req(name), name: req(name), ph: req(str(8)), ref: opt(name), args: opt(args) },\n 'queue.add': { queue: req(QUEUE), id: req(count) },\n 'queue.remove': { queue: req(QUEUE), id: req(count), why: req(oneOf('cancel', 'gone')) },\n 'loop.turn': { n: req(count) },\n 'phase.enter': { phase: req(PHASE), turn: opt(count), afterPoll: opt(bool), pollTimeoutMs: opt(num) },\n 'phase.leave': { phase: req(PHASE), turn: opt(count), afterPoll: opt(bool) },\n 'timer.fired': { lateMs: opt(num) },\n 'pool.queued': {\n job: req(name),\n kind: req(oneOf('fs', 'dns', 'crypto', 'zlib', 'user', 'unknown')),\n op: opt(name),\n id: opt(count),\n },\n 'pool.started': { job: req(name), thread: req(count) },\n 'pool.finished': { job: req(name), thread: req(count) },\n 'pool.posted': { job: req(name), thread: req(count) },\n 'pool.delivered': { job: req(name) },\n 'pool.cancelled': { job: req(name) },\n 'pool.link': { job: req(name), id: req(count) },\n 'pool.size': { size: req(poolSize) },\n 'debug.paused': {\n reason: req(oneOf('breakpoint', 'step', 'pause', 'exception', 'entry', 'other')),\n frames: req(frames),\n timeKeptRunning: req(bool),\n },\n 'debug.resumed': { pausedMs: req(nonNeg) },\n 'gate.stopped': { gate: req(oneOf('phase', 'turn', 'timer', 'poolStart', 'poolPost', 'poolDone', 'manual')), phase: opt(PHASE), job: opt(name) },\n 'gate.released': { stoppedMs: req(nonNeg) },\n 'clock.frozen': { why: opt(oneOf('gate', 'breakpoint')) },\n 'clock.unfrozen': { hiddenMs: req(nonNeg) },\n 'note': { level: req(oneOf('info', 'warn')), text: req(str(2000)) },\n};\n\nconst KINDS: ReadonlySet<string> = new Set(Object.keys(PAYLOADS));\nconst SPEC_BY_KIND = new Map<string, Spec>();\nfor (const k of Object.keys(PAYLOADS) as EventKind[]) SPEC_BY_KIND.set(k, { ...BASE, ...PAYLOADS[k] });\n\n/** Every event kind of this format version. */\nexport function eventKinds(): EventKind[] {\n return Object.keys(PAYLOADS) as EventKind[];\n}\n\n/** True when `k` is a kind of this format version. */\nexport function isEventKind(k: unknown): k is EventKind {\n return typeof k === 'string' && KINDS.has(k);\n}\n\n/** The names of the fields an event of kind `k` may carry besides `k`, `t`, `src`, `c`. */\nexport function fieldNames(k: EventKind): string[] {\n return Object.keys(SPEC_BY_KIND.get(k) as Spec).filter((f) => f !== 'k' && f !== 't' && f !== 'src' && f !== 'c');\n}\n\n/**\n * Checks one event. Returns a fresh object with only the known fields.\n * Throws RecordingError when anything is off.\n */\nexport function validateEvent(value: unknown): NmEvent {\n if (!isPlainObject(value)) throw new RecordingError('an event must be an object');\n const k = value['k'];\n if (!isEventKind(k)) throw new RecordingError(`unknown event kind ${typeof k === 'string' ? JSON.stringify(k.slice(0, 60)) : typeof k}`);\n const out = object(SPEC_BY_KIND.get(k) as Spec, value, k);\n if (out['c'] !== 'observed' && typeof out['rule'] !== 'string') {\n throw new RecordingError(`${k}: an ${String(out['c'])} event must name its rule`);\n }\n return out as unknown as NmEvent;\n}\n\nconst HEADER: Spec = {\n format: req(oneOf('nodejs-map-recording')),\n version: req(count),\n created: req(str(64)),\n tool: req(str(64)),\n node: req(obj(NODE_INFO)),\n atlas: req(obj({ tag: req(str(64)), commit: req(str(64)) })),\n title: opt(name),\n description: opt(str(4000)),\n sources: opt((v, p) => {\n if (!Array.isArray(v)) fail(p, 'must be a list');\n if (v.length > LIMITS.sources) fail(p, `more than ${LIMITS.sources} sources`);\n return v.map((s, i) => object({ name: req(name), text: req(text) }, s, `${p}[${i}]`));\n }),\n};\n\n/**\n * Checks a recording header. Refuses a newer format version: an older reader\n * cannot know what a newer writer meant.\n */\nexport function validateHeader(value: unknown): RecordingHeader {\n const out = object(HEADER, value, 'header') as unknown as RecordingHeader;\n if (out.version > FORMAT_VERSION) {\n throw new RecordingError(`this recording is format version ${out.version}; this reader understands up to ${FORMAT_VERSION}`);\n }\n if (out.version < 1) throw new RecordingError('header.version: must be 1 or more');\n if (Number.isNaN(Date.parse(out.created))) throw new RecordingError('header.created: not a date');\n return out;\n}\n\n/** Type helpers re-exported for callers that build events by hand. */\nexport type { Capabilities, Frame, Loc, NodeInfo };\n","/**\n * Recording files (\"encoding B\").\n *\n * A recording is a text file, one JSON value per line:\n *\n * line 1 the header object (RecordingHeader)\n * [\"s\", text] defines the next string; strings are numbered from 0\n * [\"d\", kind, src, c, [\"field:type\", ...]]\n * defines the next shape; shapes are numbered from 0\n * [shape, dtNs, v1, v2, ...]\n * one event: shape number, time since the previous event in\n * whole nanoseconds, then one value per field of the shape\n *\n * Field types: i integer, f other number, b boolean (0 or 1), n null,\n * s string (a string number), j any other JSON value (a string number whose\n * text is JSON). A definition always comes before its first use, so any\n * prefix of the file that ends at a line break can be decoded: the player\n * decodes in slices and a live stream can be written as it grows.\n *\n * `t` is stored with nanosecond resolution. Nothing here executes code: the\n * decoder uses JSON.parse and checks every event with validateEvent.\n */\n\nimport type { NmEvent, Recording, RecordingHeader } from './types.ts';\nimport { FORMAT_VERSION } from './types.ts';\nimport { RecordingError, validateEvent, validateHeader } from './validate.ts';\n\nconst MAX_LINE = 4_000_000;\nconst MAX_SHAPES = 8192;\nconst MAX_STRINGS = 4_000_000;\nconst MAX_FIELDS = 32;\nconst FIELD_RE = /^[A-Za-z][A-Za-z0-9]{0,31}:[ifbnsj]$/;\nconst FORBIDDEN_FIELDS: ReadonlySet<string> = new Set(['k', 't', 'src', 'c', 'constructor', 'prototype']);\n\ntype FieldType = 'i' | 'f' | 'b' | 'n' | 's' | 'j';\n\nfunction typeOf(v: unknown): FieldType {\n switch (typeof v) {\n case 'number':\n return Number.isSafeInteger(v) ? 'i' : 'f';\n case 'string':\n return 's';\n case 'boolean':\n return 'b';\n default:\n return v === null ? 'n' : 'j';\n }\n}\n\ninterface EncShape {\n index: number;\n names: string[];\n types: FieldType[];\n}\n\n/** Writes a recording piece by piece. `header()` first, then `events()` as often as needed. */\nexport class RecordingEncoder {\n #shapes = new Map<string, EncShape>();\n #strings = new Map<string, number>();\n #prevNs = 0;\n\n /** The first line of the file. */\n header(header: RecordingHeader): string {\n return JSON.stringify(validateHeader(header)) + '\\n';\n }\n\n /** The lines for these events (definitions they need included). */\n events(events: readonly NmEvent[]): string {\n const parts: string[] = [];\n for (const e of events) this.#one(e as unknown as Record<string, unknown>, parts);\n return parts.join('');\n }\n\n #string(text: string, parts: string[]): number {\n let i = this.#strings.get(text);\n if (i === undefined) {\n i = this.#strings.size;\n this.#strings.set(text, i);\n parts.push('[\"s\",' + JSON.stringify(text) + ']\\n');\n }\n return i;\n }\n\n #one(e: Record<string, unknown>, parts: string[]): void {\n let key = `${String(e['k'])}|${String(e['src'])}|${String(e['c'])}`;\n const names: string[] = [];\n const types: FieldType[] = [];\n for (const f of Object.keys(e)) {\n if (f === 'k' || f === 't' || f === 'src' || f === 'c') continue;\n const v = e[f];\n if (v === undefined) continue;\n const ty = typeOf(v);\n names.push(f);\n types.push(ty);\n key += `|${f}:${ty}`;\n }\n let shape = this.#shapes.get(key);\n if (shape === undefined) {\n shape = { index: this.#shapes.size, names, types };\n this.#shapes.set(key, shape);\n parts.push(JSON.stringify(['d', e['k'], e['src'], e['c'], names.map((n, i) => `${n}:${types[i] as string}`)]) + '\\n');\n }\n const t = e['t'];\n if (typeof t !== 'number' || !Number.isFinite(t)) throw new RecordingError(`${String(e['k'])}: t must be a finite number`);\n const ns = Math.round(t * 1000);\n let row = `[${shape.index},${ns - this.#prevNs}`;\n this.#prevNs = ns;\n for (let i = 0; i < names.length; i++) {\n const v = e[names[i] as string];\n switch (types[i]) {\n case 'i':\n case 'f':\n row += ',' + String(v);\n break;\n case 'b':\n row += v ? ',1' : ',0';\n break;\n case 'n':\n row += ',0';\n break;\n case 's':\n row += ',' + this.#string(v as string, parts);\n break;\n default:\n row += ',' + this.#string(JSON.stringify(v), parts);\n }\n }\n parts.push(row + ']\\n');\n }\n}\n\n/** The whole recording as text. */\nexport function encodeRecording(recording: Recording): string {\n const enc = new RecordingEncoder();\n return enc.header({ ...recording.header, version: FORMAT_VERSION }) + enc.events(recording.events);\n}\n\ninterface DecShape {\n k: string;\n src: string;\n c: string;\n names: string[];\n types: FieldType[];\n}\n\n/**\n * Reads a recording piece by piece. Feed text with `push` in chunks of any\n * size (a chunk may end in the middle of a line); it returns the events that\n * became complete. Call `finish` at the end of the input.\n */\nexport class RecordingDecoder {\n #rest = '';\n #line = 0;\n #header: RecordingHeader | undefined;\n #shapes: DecShape[] = [];\n #strings: string[] = [];\n #prevNs = 0;\n #count = 0;\n\n /** The header, once the first line has been read. */\n get header(): RecordingHeader | undefined {\n return this.#header;\n }\n\n /** Number of events decoded so far. */\n get count(): number {\n return this.#count;\n }\n\n push(chunk: string): NmEvent[] {\n const out: NmEvent[] = [];\n let text = this.#rest + chunk;\n let start = 0;\n for (;;) {\n const nl = text.indexOf('\\n', start);\n if (nl < 0) break;\n this.#lineText(text.slice(start, nl), out);\n start = nl + 1;\n }\n text = text.slice(start);\n if (text.length > MAX_LINE) throw new RecordingError('line too long', this.#line + 1);\n this.#rest = text;\n return out;\n }\n\n /** Decodes a last line without a line break, if any, and checks that a header was seen. */\n finish(): NmEvent[] {\n const out: NmEvent[] = [];\n const tail = this.#rest;\n this.#rest = '';\n if (tail.trim() !== '') this.#lineText(tail, out);\n if (this.#header === undefined) throw new RecordingError('empty recording: no header line');\n return out;\n }\n\n #lineText(raw: string, out: NmEvent[]): void {\n this.#line++;\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw;\n if (line.length > MAX_LINE) throw new RecordingError('line too long', this.#line);\n if (line === '') {\n if (this.#header === undefined) throw new RecordingError('the first line must be the header', this.#line);\n return;\n }\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n throw new RecordingError('not valid JSON', this.#line);\n }\n try {\n if (this.#header === undefined) {\n this.#header = validateHeader(value);\n return;\n }\n if (!Array.isArray(value) || value.length < 2) throw new RecordingError('expected a definition or an event row');\n const tag: unknown = value[0];\n if (tag === 's') this.#defineString(value);\n else if (tag === 'd') this.#defineShape(value);\n else if (typeof tag === 'number') {\n out.push(this.#event(value as unknown[]));\n this.#count++;\n } else throw new RecordingError('unknown line type');\n } catch (e) {\n if (e instanceof RecordingError && e.line === undefined) throw new RecordingError(e.message, this.#line);\n throw e;\n }\n }\n\n #defineString(row: unknown[]): void {\n if (row.length !== 2 || typeof row[1] !== 'string') throw new RecordingError('bad string definition');\n if (this.#strings.length >= MAX_STRINGS) throw new RecordingError('too many strings');\n this.#strings.push(row[1]);\n }\n\n #defineShape(row: unknown[]): void {\n const [, k, src, c, fields] = row;\n if (row.length !== 5 || typeof k !== 'string' || typeof src !== 'string' || typeof c !== 'string' || !Array.isArray(fields)) {\n throw new RecordingError('bad shape definition');\n }\n if (this.#shapes.length >= MAX_SHAPES) throw new RecordingError('too many shapes');\n if (fields.length > MAX_FIELDS) throw new RecordingError('too many fields in a shape');\n const names: string[] = [];\n const types: FieldType[] = [];\n for (const f of fields as unknown[]) {\n if (typeof f !== 'string' || !FIELD_RE.test(f)) throw new RecordingError('bad field in a shape');\n const colon = f.lastIndexOf(':');\n const fieldName = f.slice(0, colon);\n if (FORBIDDEN_FIELDS.has(fieldName) || names.includes(fieldName)) throw new RecordingError(`field \"${fieldName}\" not allowed in a shape`);\n names.push(fieldName);\n types.push(f.slice(colon + 1) as FieldType);\n }\n this.#shapes.push({ k, src, c, names, types });\n }\n\n #stringAt(i: unknown): string {\n if (typeof i !== 'number' || !Number.isInteger(i) || i < 0 || i >= this.#strings.length) throw new RecordingError('string number out of range');\n return this.#strings[i] as string;\n }\n\n #event(row: unknown[]): NmEvent {\n const shapeIndex = row[0] as number;\n const shape = Number.isInteger(shapeIndex) && shapeIndex >= 0 ? this.#shapes[shapeIndex] : undefined;\n if (shape === undefined) throw new RecordingError('shape number out of range');\n const dt = row[1];\n if (typeof dt !== 'number' || !Number.isSafeInteger(dt)) throw new RecordingError('bad time delta');\n if (row.length !== shape.names.length + 2) throw new RecordingError('wrong number of values for the shape');\n this.#prevNs += dt;\n if (!Number.isSafeInteger(this.#prevNs)) throw new RecordingError('time out of range');\n const e: Record<string, unknown> = { k: shape.k, t: this.#prevNs / 1000, src: shape.src, c: shape.c };\n for (let i = 0; i < shape.names.length; i++) {\n const v = row[i + 2];\n let decoded: unknown;\n switch (shape.types[i]) {\n case 'i':\n case 'f':\n if (typeof v !== 'number') throw new RecordingError('expected a number');\n decoded = v;\n break;\n case 'b':\n if (v !== 0 && v !== 1) throw new RecordingError('expected 0 or 1');\n decoded = v === 1;\n break;\n case 'n':\n decoded = null;\n break;\n case 's':\n decoded = this.#stringAt(v);\n break;\n default:\n try {\n decoded = JSON.parse(this.#stringAt(v));\n } catch (err) {\n if (err instanceof RecordingError) throw err;\n throw new RecordingError('bad JSON value');\n }\n }\n e[shape.names[i] as string] = decoded;\n }\n return validateEvent(e);\n }\n}\n\n/** Decodes text given in pieces; yields the events of each piece. */\nexport function* decodeLines(chunks: Iterable<string>): Generator<NmEvent[], RecordingHeader, void> {\n const dec = new RecordingDecoder();\n for (const chunk of chunks) {\n const events = dec.push(chunk);\n if (events.length > 0) yield events;\n }\n const tail = dec.finish();\n if (tail.length > 0) yield tail;\n return dec.header as RecordingHeader;\n}\n\n/** Decodes a whole recording. Throws RecordingError on anything unexpected. */\nexport function decodeRecording(text: string): Recording {\n const dec = new RecordingDecoder();\n const events = dec.push(text);\n for (const e of dec.finish()) events.push(e);\n return { header: dec.header as RecordingHeader, events };\n}\n","/**\n * The rule registry.\n *\n * Every event that is not a raw signal names the rule that produced it\n * (`rule` on the event). A rule says, in plain English, what was seen and\n * what may be concluded from it, how sure the conclusion is, and which parts\n * of Node's source it relies on.\n *\n * `cites` are atlas ids, never line numbers:\n * s:<path>#<qualified name> a function in Node's source at the tag\n * o:<name> a well-known box of the atlas overlay\n * The atlas resolves them to files and lines for the Node version in use, and\n * a proof test checks that every id cited here exists in the built atlas.\n *\n * Rules are data. The code that applies them lives in the helper\n * (rule stage); the ids here are the contract between the two.\n */\n\nimport type { Certainty } from './types.ts';\n\nexport interface Rule {\n /** Short id written into events, for example \"T1\". */\n id: string;\n title: string;\n /** \"When we see X, we claim Y\", in plain English. */\n statement: string;\n /** The certainty of the events this rule produces. */\n yields: Certainty;\n /** Where the rule holds. `unix` covers Linux and macOS. */\n platform: 'all' | 'unix' | 'win32';\n /** Atlas ids of the source the rule relies on. */\n cites: readonly string[];\n}\n\n// Source symbols used below, kept in one place so a rename is one edit.\nconst S = {\n // the scope constructor has overloads; the overlay box for InternalMakeCallback covers them\n callbackScopeCtor: 'o:cb.InternalMakeCallback',\n callbackScopeClose: 's:src/api/callback.cc#node::InternalCallbackScope::Close',\n runTimers: 's:src/env.cc#node::Environment::RunTimers',\n scheduleTimer: 's:src/env.cc#node::Environment::ScheduleTimer',\n checkImmediate: 's:src/env.cc#node::Environment::CheckImmediate',\n toggleImmediateRef: 's:src/env.cc#node::Environment::ToggleImmediateRef',\n uvRunTimers: 's:deps/uv/src/timer.c#uv__run_timers',\n processTimers: 's:lib/internal/timers.js#getTimerCallbacks/processTimers',\n listOnTimeout: 'o:timers.listOnTimeout',\n processImmediate: 's:lib/internal/timers.js#getTimerCallbacks/processImmediate',\n timeoutCtor: 's:lib/internal/timers.js#Timeout.prototype.constructor',\n immediateCtor: 's:lib/internal/timers.js#Immediate.prototype.constructor',\n timerInsert: 's:lib/internal/timers.js#insert',\n nextTick: 's:lib/internal/process/task_queues.js#nextTick',\n processTicks: 's:lib/internal/process/task_queues.js#processTicksAndRejections',\n queueMicrotask: 's:lib/internal/process/task_queues.js#queueMicrotask',\n runMicrotask: 's:lib/internal/process/task_queues.js#runMicrotask',\n promiseInitHook: 's:lib/internal/async_hooks.js#promiseInitHook',\n promiseBeforeHook: 's:lib/internal/async_hooks.js#promiseBeforeHook',\n uvRunUnix: 's:deps/uv/src/unix/core.c#uv_run',\n uvRunWin: 's:deps/uv/src/win/core.c#uv_run',\n uvPollWin: 's:deps/uv/src/win/core.c#uv__poll',\n uvProcessReqs: 's:deps/uv/src/win/core.c#uv__process_reqs',\n uvIoPollLinux: 's:deps/uv/src/unix/linux.c#uv__io_poll',\n uvAsyncIo: 's:deps/uv/src/unix/async.c#uv__async_io',\n uvAsyncWakeupWin: 's:deps/uv/src/win/async.c#uv__process_async_wakeup_req',\n worker: 's:deps/uv/src/threadpool.c#worker',\n post: 's:deps/uv/src/threadpool.c#post',\n workSubmit: 's:deps/uv/src/threadpool.c#uv__work_submit',\n workDone: 's:deps/uv/src/threadpool.c#uv__work_done',\n initThreads: 's:deps/uv/src/threadpool.c#init_threads',\n scheduleWork: 's:src/threadpoolwork-inl.h#node::ThreadPoolWork::ScheduleWork',\n fsWorkUnix: 's:deps/uv/src/unix/fs.c#uv__fs_work',\n fsWorkWin: 's:deps/uv/src/win/fs.c#uv__fs_work',\n getaddrinfoUnix: 's:deps/uv/src/unix/getaddrinfo.c#uv_getaddrinfo',\n getaddrinfoWin: 's:deps/uv/src/win/getaddrinfo.c#uv_getaddrinfo',\n uvMetricsInfo: 's:src/node_perf.cc#node::performance::UvMetricsInfo',\n queryResponse: 's:src/cares_wrap.h#node::cares_wrap::QueryWrap::QueueResponseCallback',\n handleOnClose: 's:src/handle_wrap.cc#node::HandleWrap::OnClose',\n closingUnix: 's:deps/uv/src/unix/core.c#uv__run_closing_handles',\n closingWin: 's:deps/uv/src/win/core.c#uv__process_endgames',\n ioFeed: 's:deps/uv/src/unix/core.c#uv__io_feed',\n runPending: 's:deps/uv/src/unix/core.c#uv__run_pending',\n streamIo: 's:deps/uv/src/unix/stream.c#uv__stream_io',\n writeReqFinish: 's:deps/uv/src/unix/stream.c#uv__write_req_finish',\n shutdownUnix: 's:deps/uv/src/unix/stream.c#uv_shutdown',\n} as const;\n\nconst O = {\n phaseTimers: 'o:phase.timers',\n phasePending: 'o:phase.pending',\n phasePoll: 'o:phase.poll',\n phaseCheck: 'o:phase.check',\n tickDrain: 'o:tick.drain',\n microtaskDrain: 'o:microtask.run',\n promiseReactionEnqueue: 'o:v8.enqueueMicrotask',\n promiseReactionRun: 'o:v8.promiseReactionJob',\n performPromiseThen: 'o:v8.performPromiseThen',\n triggerReactions: 'o:v8.triggerReactions',\n poolSubmit: 'o:pool.submit',\n poolWorker: 'o:pool.worker',\n poolDone: 'o:pool.done',\n makeCallback: 'o:cb.InternalMakeCallback',\n uvRun: 'o:loop.run',\n dnsQueryResponse: 'o:dns.queryResponse',\n nativeImmediatesRun: 'o:immediate.native',\n shutdownQueue: 'o:uv.shutdown',\n shutdownRun: 'o:uv.shutdownDone',\n closeCallbacks: 'o:loop.finishClose',\n handleOnClose: 'o:cb.handleOnClose',\n} as const;\n\nconst ENTRIES: readonly Rule[] = [\n // ---- callbacks ------------------------------------------------------------\n {\n id: 'C0',\n title: 'A callback started or ended',\n statement:\n 'Node calls the async_hooks \"before\" hook just before it runs the JavaScript callback of an async item and \"after\" when the callback has returned. We report these two moments as they are.',\n yields: 'observed',\n platform: 'all',\n cites: [S.callbackScopeCtor, S.callbackScopeClose, S.listOnTimeout, S.processImmediate, S.processTicks],\n },\n\n // ---- timers phase -----------------------------------------------------------\n {\n id: 'T0',\n title: 'The timers phase ran timer callbacks',\n statement:\n \"Node reports a timed scope named RunTimers each time libuv's timers step calls Node's one timer. From its start to its end the loop is in the timers phase and is running due setTimeout and setInterval callbacks.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.runTimers, S.uvRunTimers, S.scheduleTimer, O.phaseTimers],\n },\n {\n id: 'T1',\n title: 'A timer callback implies the timers phase',\n statement:\n 'A callback of an item of type Timeout started and no RunTimers scope has been reported for that moment (trace events arrive later than hooks). Timeout callbacks are only ever run by processTimers, which libuv calls in its timers step, so the loop is in the timers phase.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.processTimers, S.listOnTimeout, S.runTimers, O.phaseTimers],\n },\n {\n id: 'T2',\n title: 'A timer callback inside a reported timers scope',\n statement:\n 'A Timeout callback started between the start and the end of a RunTimers scope that Node reported. Both facts are observed, so this callback ran in the timers phase.',\n yields: 'observed',\n platform: 'all',\n cites: [S.runTimers, S.listOnTimeout],\n },\n\n // ---- check phase ------------------------------------------------------------\n {\n id: 'I0',\n title: 'The check phase ran',\n statement:\n 'Node reports a timed scope named CheckImmediate from the callback of a libuv check handle that is always active. It runs once in every loop turn, in the check phase, whether or not the program used setImmediate.',\n yields: 'observed',\n platform: 'all',\n cites: [S.checkImmediate, O.phaseCheck],\n },\n {\n id: 'I1',\n title: 'An immediate callback implies the check phase',\n statement:\n 'A callback of an item of type Immediate started and no CheckImmediate scope has been reported for that moment. Immediate callbacks are only run by processImmediate, which Node calls from the check phase.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.processImmediate, S.checkImmediate, O.phaseCheck],\n },\n {\n id: 'I2',\n title: 'An immediate callback inside a reported check scope',\n statement: 'An Immediate callback started between the start and the end of a CheckImmediate scope that Node reported.',\n yields: 'observed',\n platform: 'all',\n cites: [S.checkImmediate, S.processImmediate],\n },\n\n // ---- I/O callbacks ----------------------------------------------------------\n {\n id: 'P1u',\n title: 'A thread pool result is delivered inside the poll step (Linux, macOS)',\n statement:\n 'A callback of a thread-pool-backed item (file system, dns.lookup, crypto, zlib) started outside the timers and check phases. On Unix a finished job wakes the loop through an async handle, and libuv runs the callback from uv__io_poll, so the loop is in the poll phase.',\n yields: 'inferred',\n platform: 'unix',\n cites: [S.uvRunUnix, S.uvIoPollLinux, S.uvAsyncIo, S.workDone, O.phasePoll],\n },\n {\n id: 'P1w',\n title: 'A thread pool result is delivered after the poll step (Windows)',\n statement:\n 'A callback of a thread-pool-backed item started outside the timers and check phases. On Windows uv__poll only collects finished requests; their callbacks run in uv__process_reqs, which uv_run calls right after the poll and again at the top of the next turn. We show this as the pending step.',\n yields: 'inferred',\n platform: 'win32',\n cites: [S.uvRunWin, S.uvPollWin, S.uvProcessReqs, S.uvAsyncWakeupWin, S.workDone, O.phasePending],\n },\n {\n id: 'P2',\n title: 'A handle callback that is not its close callback is delivered by the poll step',\n statement:\n 'A callback of a handle (TCP socket or server, pipe, terminal, UDP socket, child process, signal, file watcher) started outside the timers and check phases, and the helper saw that it is not the handle\\'s close callback (rule CL1). Data, connections and other events of a handle are read in the poll step: on Unix libuv calls back from there; on Windows uv__poll only collects them and the callbacks run in uv__process_reqs right after, which we show as the pending step after the poll. On Windows the same holds for write, shutdown, connect and send requests. No phase is inferred, rather than a wrong one, in these cases: write, shutdown, connect and send requests on Unix (libuv finishes them from uv__stream_io in the poll step when data was still waiting to be written, and otherwise queues the stream with uv__io_feed so that the callback runs in a pending pass: a shutdown with no write waiting runs in the pending step, one behind queued writes in the poll step, and the type does not say which); message ports and every other kind of item, whose callbacks can be made from several steps; a handle whose close state the helper could not read.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.uvRunUnix, S.uvRunWin, S.uvProcessReqs, S.streamIo, S.ioFeed, S.runPending, S.writeReqFinish, S.shutdownUnix, O.shutdownQueue, O.shutdownRun, O.phasePoll, O.phasePending],\n },\n {\n id: 'CL1',\n title: 'A handle\\'s close callback runs in the closing step',\n statement:\n 'A callback of a handle started, and the handle object carries the property Node sets when close(callback) is called (handle_onclose). After close() the handle gets no other callback, so this one is the close callback: libuv makes it in the closing step at the end of the turn (uv__run_closing_handles on Unix, uv__process_endgames on Windows), and Node passes it on from HandleWrap::OnClose.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.handleOnClose, S.closingUnix, S.closingWin, S.uvRunUnix, S.uvRunWin, O.handleOnClose, O.closeCallbacks],\n },\n {\n id: 'I3',\n title: 'A dns.resolve answer is delivered in the check phase',\n statement:\n 'A callback of a QUERYWRAP item (dns.resolve and its relatives, answered by c-ares) started outside a reported scope. Node does not call back when the answer arrives on the socket: QueryWrap::QueueResponseCallback defers it with SetImmediate, so it runs with the native immediates in the check phase, on every system.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.queryResponse, S.checkImmediate, O.dnsQueryResponse, O.nativeImmediatesRun, O.phaseCheck],\n },\n\n // ---- nextTick and microtasks ------------------------------------------------\n {\n id: 'K1',\n title: 'A nextTick callback ran from the tick queue',\n statement:\n 'A callback of an item of type TickObject started. process.nextTick creates exactly one TickObject per call and processTicksAndRejections runs them in order when the current callback scope closes, before the loop continues.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.nextTick, S.processTicks, S.callbackScopeClose, O.tickDrain],\n },\n {\n id: 'M1',\n title: 'A microtask ran',\n statement:\n 'A callback of an item of type PROMISE or Microtask started. Promise reactions and queueMicrotask callbacks are jobs on V8\\'s microtask queue, drained after the nextTick queue and whenever a callback scope closes.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.promiseBeforeHook, S.runMicrotask, S.processTicks, S.callbackScopeClose, O.microtaskDrain, O.promiseReactionRun],\n },\n\n // ---- loop turns ---------------------------------------------------------------\n {\n id: 'L1',\n title: 'Loop counters',\n statement:\n \"performance.nodeTiming.uvMetricsInfo returns libuv's own counters. loopCount is increased once per turn, just before the poll step. We read it when a top-level callback starts, so the value is exact but the moment a turn began is not known from it.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.uvMetricsInfo, S.uvRunUnix, S.uvRunWin],\n },\n {\n id: 'L2',\n title: 'Loop turns from the check phase',\n statement:\n 'CheckImmediate is reported once per loop turn (rule I0). The timers step that follows it belongs to the same turn. The first callback or scope after that starts the next turn; we place the turn boundary there.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.checkImmediate, S.uvRunUnix, S.uvRunWin, O.uvRun],\n },\n {\n id: 'L3',\n title: 'Loop turns from the loop counter',\n statement:\n 'The loop counter read when a callback starts (rule L1) is higher than at the previous callback, so at least one new turn began in between. Until trace events arrive we place the turn boundary at this callback. Turns in which no callback of ours ran are skipped.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.uvMetricsInfo, S.uvRunUnix, S.uvRunWin, O.uvRun],\n },\n\n // ---- thread pool ----------------------------------------------------------------\n {\n id: 'W0',\n title: 'A job was submitted to, or came back from, the thread pool',\n statement:\n \"Node's ThreadPoolWork reports a trace event with the job's address when it submits work to libuv and another when the result is delivered on the main thread.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.scheduleWork, S.workSubmit, S.workDone, O.poolSubmit, O.poolDone],\n },\n {\n id: 'W1',\n title: 'Which async item a pool job belongs to',\n statement:\n 'The trace event for a submitted job follows the creation of an async item of a thread-pool-backed type on the main thread, in the same synchronous call. We take that item as the owner of the job. The trace event itself carries no async id.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork, S.workSubmit],\n },\n {\n id: 'W2',\n title: 'A pool thread started a job',\n statement:\n \"Node's ThreadPoolWork reports a trace event from the pool thread when the work function begins. The event carries the real thread id and the kind of job, but not which job.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.scheduleWork, S.worker, O.poolWorker],\n },\n {\n id: 'W2b',\n title: 'Which job a pool thread started',\n statement:\n 'libuv keeps one first-in first-out work queue for all pool threads. The n-th \"started\" report for a kind of job is therefore the n-th submitted job of that kind. Two threads that take jobs within the same microsecond can report in swapped order.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.post, S.workSubmit],\n },\n {\n id: 'W3',\n title: 'A pool thread finished a job',\n statement:\n 'The pool thread reports a trace event when the work function returns. The thread and the time are observed; the job is the one that thread started (rule W2b).',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork, S.worker],\n },\n {\n id: 'W4',\n title: 'The result of a pool job was delivered',\n statement:\n 'The pool thread appends the finished job to the loop\\'s done queue and wakes the loop; uv__work_done runs the after-work callbacks on the main thread in that order. The \"result delivered\" trace event with the job\\'s address marks this, and the callback of the owning item follows.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.workDone, O.poolDone],\n },\n {\n id: 'W5',\n title: 'A job is waiting for a free pool thread',\n statement:\n 'A job was submitted while as many jobs as the pool has threads were running. It waits in the queue. This count is incomplete: file system requests and dns.lookup hold pool threads without reporting from them, and dns.lookup may use at most half of the threads.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.post, S.initThreads],\n },\n {\n id: 'W6',\n title: 'File system requests and dns.lookup use the pool without thread reports',\n statement:\n 'Classic file system requests and dns.lookup are handed to the pool by libuv itself, not through ThreadPoolWork. Node reports their start and end on the main thread only. We show them as queued pool work; which thread ran them, and when, is not available on an official build.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.fsWorkUnix, S.fsWorkWin, S.getaddrinfoUnix, S.getaddrinfoWin, S.workSubmit],\n },\n {\n id: 'X1',\n title: 'The first use of the thread pool blocks the main thread',\n statement:\n 'The pool threads are created on the first submission, and the submitting thread waits until all of them have started. A gap on the main thread right after the first submission is this wait.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.workSubmit, S.initThreads],\n },\n {\n id: 'W7',\n title: 'The pool size is read when the pool is first used',\n statement:\n 'libuv creates the pool threads at the first submission and reads UV_THREADPOOL_SIZE only then (no value: 4 threads; 0 or text that is not a number: 1; at most 1024). A program can therefore still set the variable before its first pool request. The helper reads the variable when the first thread-pool-backed async item is created and reports the size when it differs from the one the run started with. A use of the pool that creates no such item (a native add-on, a worker thread) is not seen.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.initThreads, S.workSubmit],\n },\n {\n id: 'G1',\n title: 'Thread reports are missing for a pool job',\n statement:\n 'Every ThreadPoolWork job reports one start and one end from its pool thread. When a job was submitted and delivered but one of the two reports is absent, it was dropped while trace events were being read from the target. The job ran; its thread or times are not known.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork],\n },\n\n // ---- where items wait ---------------------------------------------------------------\n {\n id: 'QT',\n title: 'A new Timeout waits in the timer lists',\n statement:\n 'An async item of type Timeout was created. setTimeout and setInterval construct a Timeout and insert it into the timer lists in the same call, so the item is waiting in the timers queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.timeoutCtor, S.timerInsert],\n },\n {\n id: 'QT2',\n title: 'A repeating timer waits again after it ran',\n statement:\n 'The callback of a Timeout created by setInterval returned and the timer was not cleared. listOnTimeout inserts a repeating timer again after each run.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.listOnTimeout, S.timerInsert],\n },\n {\n id: 'QI',\n title: 'A new Immediate waits in the immediate queue',\n statement: 'An async item of type Immediate was created. The Immediate constructor appends itself to the immediate queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.immediateCtor, S.processImmediate, S.toggleImmediateRef],\n },\n {\n id: 'QK',\n title: 'A new TickObject waits in the nextTick queue',\n statement: 'An async item of type TickObject was created. process.nextTick pushes exactly one TickObject onto the tick queue per call.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.nextTick],\n },\n {\n id: 'QM',\n title: 'A queueMicrotask callback waits in the microtask queue',\n statement: 'An async item of type Microtask was created. queueMicrotask creates it and enqueues the callback on V8\\'s microtask queue in the same call.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.queueMicrotask, O.promiseReactionEnqueue],\n },\n {\n id: 'QP',\n title: 'A promise reaction is queued when its promise settles',\n statement:\n 'then, catch, finally and await register a reaction on a promise and create a second promise for it (async_hooks reports that one with the first as its trigger). V8 puts the reaction job on the microtask queue when the first promise settles, or at once when it has already settled. The helper sees settling through the promiseResolve hook, which fires on fulfil and reject and not when a promise is merely resolved with another promise. So the reaction is shown in the microtask queue from the later of the two moments, creation and settling, until its callback starts. A promise that is only created while another promise\\'s callback runs is not a reaction (its trigger is the running callback); neither is a promise that settles or runs before its trigger has settled (the wrapper an await makes around a plain value). Reactions of a promise whose settling was not seen are not shown as queued; they simply run.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.promiseInitHook, O.performPromiseThen, O.triggerReactions, O.promiseReactionEnqueue],\n },\n {\n id: 'QP2',\n title: 'A reaction that was shown as queued did not run in its turn',\n statement:\n 'The microtask queue is first-in first-out and is emptied completely before the next timer, immediate or I/O callback. When a reaction that rule QP put in the queue is overtaken by a later microtask, or is still listed when such a callback starts, it was not in the queue: rule QP was wrong for this promise. The entry is removed here rather than left standing.',\n yields: 'inferred',\n platform: 'all',\n cites: [O.promiseReactionEnqueue, O.triggerReactions],\n },\n {\n id: 'QW',\n title: 'A new thread-pool-backed request waits for the pool',\n statement:\n 'An async item of a thread-pool-backed type was created (FSREQCALLBACK, FSREQPROMISE, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, a crypto *REQUEST, zlib). Node creates the item and submits the work in the same call, so the request is with the thread pool until its callback starts.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.workSubmit, S.scheduleWork, O.poolSubmit],\n },\n {\n id: 'QR',\n title: 'A new one-shot I/O request waits on the operating system',\n statement:\n 'An async item of a one-shot request type was created (a connect, write or shutdown request). It waits for the operating system until its callback starts.',\n yields: 'inferred',\n platform: 'all',\n cites: [O.phasePoll, O.makeCallback],\n },\n {\n id: 'QX',\n title: 'A waiting item went away without running',\n statement:\n 'An item that was waiting was reported as destroyed before any callback of it started (for example clearTimeout, clearImmediate or clearInterval). It left its queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.timeoutCtor, S.immediateCtor],\n },\n];\n\n/**\n * Entries that explain what the helper relies on but that no event carries:\n * background, not rules. (They used to sit in RULES; an id here never appears\n * in an event's `rule`.)\n */\nconst BACKGROUND_IDS: ReadonlySet<string> = new Set(['C0', 'T2', 'I2', 'L1', 'W2', 'W4', 'W5', 'W6', 'X1']);\n\n/** The rules: exactly the ids that code writes into events (the helper's rule stage and sources, and the replay package for K1 and M1). */\nexport const RULES: readonly Rule[] = ENTRIES.filter((r) => !BACKGROUND_IDS.has(r.id));\n\n/** Background explanations: same shape as a rule, never the `rule` of an event. */\nexport const BACKGROUND: readonly Rule[] = ENTRIES.filter((r) => BACKGROUND_IDS.has(r.id));\n\nconst BY_ID = new Map<string, Rule>(RULES.map((r) => [r.id, r]));\n\n/** The rule with this id, or undefined. */\nexport function ruleById(id: string): Rule | undefined {\n return BY_ID.get(id);\n}\n\n/** True when `id` names a rule of this registry. */\nexport function isRuleId(id: string): boolean {\n return BY_ID.has(id);\n}\n\n/** Every atlas id cited by any rule, sorted, without duplicates. */\nexport function allCitedIds(): string[] {\n const ids = new Set<string>();\n for (const r of ENTRIES) for (const c of r.cites) ids.add(c);\n return [...ids].sort();\n}\n\n/**\n * async_hooks types whose work runs on the libuv thread pool. Crypto request\n * types all end in \"REQUEST\".\n */\nexport function isPoolBackedType(type: string): boolean {\n return (\n type === 'FSREQCALLBACK' ||\n type === 'FSREQPROMISE' ||\n type === 'GETADDRINFOREQWRAP' ||\n type === 'GETNAMEINFOREQWRAP' ||\n type === 'ZLIB' ||\n type === 'BROTLI_DECODE' ||\n type === 'BROTLI_ENCODE' ||\n type === 'ZSTD_COMPRESS' ||\n type === 'ZSTD_DECOMPRESS' ||\n type.endsWith('REQUEST')\n );\n}\n\n/** One-shot request types that wait on the operating system (rule QR). */\nexport function isIoRequestType(type: string): boolean {\n return type === 'TCPCONNECTWRAP' || type === 'PIPECONNECTWRAP' || type === 'WRITEWRAP' || type === 'SHUTDOWNWRAP' || type === 'UDPSENDWRAP';\n}\n\n/** Which queue a new item of this type waits in, with the rule that says so. Undefined: none we can name. */\nexport function queueOfNewItem(type: string, _triggerType?: string): { queue: 'nextTick' | 'microtask' | 'timers' | 'immediate' | 'pool' | 'io'; rule: string } | undefined {\n if (type === 'Timeout') return { queue: 'timers', rule: 'QT' };\n if (type === 'Immediate') return { queue: 'immediate', rule: 'QI' };\n if (type === 'TickObject') return { queue: 'nextTick', rule: 'QK' };\n if (type === 'Microtask') return { queue: 'microtask', rule: 'QM' };\n // Promise reactions (rule QP) depend on when the trigger settles and on what\n // was running: the helper's rule stage decides them, not the type alone.\n if (type === 'PROMISE') return undefined;\n if (isPoolBackedType(type)) return { queue: 'pool', rule: 'QW' };\n if (isIoRequestType(type)) return { queue: 'io', rule: 'QR' };\n return undefined;\n}\n","/**\n * The reducer: the small, fast-changing part of the view state (\"live\"\n * state) and the one function that advances it by one event.\n *\n * Rules the reducer follows:\n *\n * - It reflects events; it does not know how Node works. Where it has to\n * conclude something itself (see rules.ts) the result is marked inferred\n * with a \"replay:\" rule id.\n * - It never shows a state the events contradict. When a later event\n * disagrees with what is on screen (a new phase starts while another is\n * still shown, a thread starts a job while it shows another), the later\n * event wins and the disagreement is counted in `inconsistent`.\n * - It never throws on input. Unknown kinds and malformed events were\n * flagged by the index and are only counted here.\n *\n * The live state holds ids and event indexes, not copies of event data:\n * details are read from the event list when a view is built (view.ts). That\n * keeps a keyframe (a copy of this state) small.\n *\n * Internal, except for the three constants re-exported by index.ts.\n */\n\nimport type { NmEvent, PoolWorkKind } from '@nodejs-map/event-format';\nimport { isIoRequestType, isPoolBackedType } from '@nodejs-map/event-format';\nimport type { RunStatus } from './types.ts';\nimport {\n F_SKIP,\n F_UNKNOWN,\n T_CLEARED,\n T_DONE,\n T_NONE,\n T_RUNNING,\n T_WAITING,\n lastBelow,\n phaseCode,\n queueCode,\n} from './run-index.ts';\nimport type { ItemRec, RunIndex } from './run-index.ts';\n\nexport { SIGNAL_KINDS } from './run-index.ts';\n\n/**\n * async_hooks types of libuv handles: things that call back many times\n * (a server accepts many connections, a socket reads many chunks). When one\n * of them waits in the \"io\" queue it stays there across its callbacks, until\n * `item.gone` or a `queue.remove` (rule \"replay:handle\"). Every other item\n * leaves its queue when its callback starts, as the event format says.\n *\n * The list is the provider types of the classes that derive from HandleWrap\n * in Node's src/ at v26.13.1 (tcp_wrap.h, pipe_wrap.h, tty_wrap.cc,\n * udp_wrap.h, process_wrap.cc, signal_wrap.cc, fs_event_wrap.cc,\n * node_stat_watcher.h, node_messaging.h), checked against that tag.\n */\nexport const PERSISTENT_HANDLE_TYPES: ReadonlySet<string> = new Set([\n 'TCPWRAP',\n 'TCPSERVERWRAP',\n 'PIPEWRAP',\n 'PIPESERVERWRAP',\n 'TTYWRAP',\n 'UDPWRAP',\n 'PROCESSWRAP',\n 'SIGNALWRAP',\n 'FSEVENTWRAP',\n 'STATWATCHER',\n 'MESSAGEPORT',\n]);\n\n/**\n * A finished pool job normally leaves the \"done\" list when the callback of\n * its item starts. A job that was never tied to an item has no such moment\n * (the format has no \"delivered\" event), so it would stay forever. We keep\n * the most recent ones, flagged as untied (PoolJobView.item is null), and\n * drop the oldest beyond this number. The count of dropped ones is shown.\n */\nexport const UNLINKED_DONE_LIMIT = 32;\n\n/** How many finished or cleared timers the live state remembers for display. */\nexport const RECENT_TIMERS = 32;\n\n// ---- pieces of the live state -------------------------------------------------\n// All of them are immutable once made: a change replaces the object. That is\n// what lets a keyframe copy arrays and maps without copying their entries.\n\nexport interface QEntry {\n readonly id: number;\n /** Index of the `queue.add`. */\n readonly index: number;\n /** Callbacks started while it stayed (persistent handles). */\n readonly runs: number;\n}\n\n/** A queue in arrival order. Removal at the front only moves `head`. */\nexport interface QueueL {\n items: QEntry[];\n head: number;\n}\n\nexport const VIA_UNKNOWN = 0;\nexport const VIA_PHASE = 1;\nexport const VIA_TICK = 2;\nexport const VIA_MICRO = 3;\n\nexport interface FrameL {\n readonly id: number;\n /** Index of the `callback.start`. */\n readonly index: number;\n readonly via: number;\n /** Index of the `queue.add` that tells us `via`; -1 when `via` comes from the item's type (rule `viaRule`). */\n readonly viaIndex: number;\n readonly viaRule: string | null;\n /** Queue code the item left, or -1. */\n readonly queue: number;\n readonly phase: number;\n readonly phaseIndex: number;\n readonly depth: number;\n}\n\nexport const JOB_WAITING = 0;\nexport const JOB_RUNNING = 1;\nexport const JOB_FINISHED = 2;\nexport const JOB_POSTED = 3;\n\nexport interface JobL {\n readonly job: string;\n readonly kind: PoolWorkKind;\n readonly op: string | null;\n /** Item id, or -1. */\n readonly id: number;\n readonly linkIndex: number;\n readonly state: number;\n /** Display thread index, or 0. */\n readonly thread: number;\n readonly queuedIndex: number;\n readonly startedIndex: number;\n readonly finishedIndex: number;\n readonly postedIndex: number;\n /** True while the job is in the done list. */\n readonly done: boolean;\n /** Index of the latest pool event of this job that carried an atlas id, or -1. */\n readonly atIndex: number;\n}\n\nexport interface ThreadL {\n readonly job: string | null;\n readonly tid: number;\n readonly jobs: number;\n}\n\nexport interface TidL {\n readonly tid: number;\n readonly busy: boolean;\n readonly name: string;\n readonly index: number;\n readonly starts: number;\n readonly ends: number;\n}\n\nexport interface Live {\n // run\n status: RunStatus;\n /** Index of `run.start` / `run.end`, or -1. */\n startIndex: number;\n endIndex: number;\n // main thread\n mainScript: boolean;\n /** Index of the event after which the thread had nothing to run, or -1. */\n idleIndex: number;\n stack: FrameL[];\n // loop\n turn: number;\n turnIndex: number;\n phase: number;\n phaseIndex: number;\n lastPhase: number;\n lastPhaseEntered: number;\n lastPhaseLeft: number;\n /** Index of the latest `phase.enter` that told the poll timeout, or -1. */\n pollIndex: number;\n scopeIndex: number;\n sampleIndex: number;\n // queues\n queues: QueueL[];\n /** Item id -> bit mask of the queues it is in. */\n where: Map<number, number>;\n // timers\n timersActive: Set<number>;\n timersRecent: number[];\n tSet: number;\n tWaiting: number;\n tRunning: number;\n tDone: number;\n tCleared: number;\n firedCount: number;\n firedIndex: number;\n // pool\n /** Index of the latest `pool.size`, or -1: the size is the one of `run.start`. */\n poolSizeIndex: number;\n threads: ThreadL[];\n jobs: Map<string, JobL>;\n poolWaiting: string[];\n poolDone: string[];\n /** How many jobs in the done list belong to no known item. */\n doneUntied: number;\n tids: Map<number, TidL>;\n pQueued: number;\n pStarted: number;\n pFinished: number;\n pPosted: number;\n pDelivered: number;\n pCancelled: number;\n pDropped: number;\n /**\n * True when this binary reports `pool.posted` (the probe build: capability\n * poolThreads \"live\", or such an event was seen). Then a finished job stays\n * on its thread until it is posted. Otherwise the thread is free at\n * `pool.finished`.\n */\n poolPosts: boolean;\n // output, notes\n outputCount: number;\n noteCount: number;\n // debugger\n paused: boolean;\n pausedIndex: number;\n lastPausedIndex: number;\n lastResumedIndex: number;\n pauses: number;\n gateStopped: boolean;\n gateIndex: number;\n gateReleasedIndex: number;\n gateStops: number;\n clockFrozen: boolean;\n clockIndex: number;\n clockUnfrozenIndex: number;\n hiddenMs: number;\n // focus\n focusIndex: number;\n // problems\n unknown: number;\n malformed: number;\n inconsistent: number;\n}\n\nexport function createLive(): Live {\n const queues: QueueL[] = [];\n for (let q = 0; q < 7; q++) queues.push({ items: [], head: 0 });\n return {\n status: 'idle',\n startIndex: -1,\n endIndex: -1,\n mainScript: false,\n idleIndex: -1,\n stack: [],\n turn: -1,\n turnIndex: -1,\n phase: 0,\n phaseIndex: -1,\n lastPhase: 0,\n lastPhaseEntered: -1,\n lastPhaseLeft: -1,\n pollIndex: -1,\n scopeIndex: -1,\n sampleIndex: -1,\n queues,\n where: new Map(),\n timersActive: new Set(),\n timersRecent: [],\n tSet: 0,\n tWaiting: 0,\n tRunning: 0,\n tDone: 0,\n tCleared: 0,\n firedCount: 0,\n firedIndex: -1,\n poolSizeIndex: -1,\n threads: [],\n jobs: new Map(),\n poolWaiting: [],\n poolDone: [],\n doneUntied: 0,\n tids: new Map(),\n pQueued: 0,\n pStarted: 0,\n pFinished: 0,\n pPosted: 0,\n pDelivered: 0,\n pCancelled: 0,\n pDropped: 0,\n poolPosts: false,\n outputCount: 0,\n noteCount: 0,\n paused: false,\n pausedIndex: -1,\n lastPausedIndex: -1,\n lastResumedIndex: -1,\n pauses: 0,\n gateStopped: false,\n gateIndex: -1,\n gateReleasedIndex: -1,\n gateStops: 0,\n clockFrozen: false,\n clockIndex: -1,\n clockUnfrozenIndex: -1,\n hiddenMs: 0,\n focusIndex: -1,\n unknown: 0,\n malformed: 0,\n inconsistent: 0,\n };\n}\n\n/** An independent copy. Entries are shared (they are immutable); containers are copied. */\nexport function cloneLive(s: Live): Live {\n const queues: QueueL[] = [];\n for (const q of s.queues) queues.push({ items: q.head === 0 ? q.items.slice() : q.items.slice(q.head), head: 0 });\n return {\n ...s,\n stack: s.stack.slice(),\n queues,\n where: new Map(s.where),\n timersActive: new Set(s.timersActive),\n timersRecent: s.timersRecent.slice(),\n threads: s.threads.slice(),\n jobs: new Map(s.jobs),\n poolWaiting: s.poolWaiting.slice(),\n poolDone: s.poolDone.slice(),\n tids: new Map(s.tids),\n };\n}\n\n/** Roughly how many container slots a copy of this state has: the cost of a keyframe. */\nexport function liveSize(s: Live): number {\n let n = 64 + s.stack.length + s.where.size * 2 + s.timersActive.size + s.timersRecent.length + s.threads.length + s.jobs.size * 2 + s.poolWaiting.length + s.poolDone.length + s.tids.size * 2;\n for (const q of s.queues) n += q.items.length - q.head;\n return n;\n}\n\n// ---- queue helpers ------------------------------------------------------------\n\nfunction queuePush(live: Live, q: number, entry: QEntry): void {\n (live.queues[q] as QueueL).items.push(entry);\n live.where.set(entry.id, (live.where.get(entry.id) ?? 0) | (1 << q));\n}\n\nfunction queueFind(queue: QueueL, id: number): number {\n const items = queue.items;\n for (let k = queue.head; k < items.length; k++) if ((items[k] as QEntry).id === id) return k;\n return -1;\n}\n\n/** Remove item `id` from queue `q`. Returns its entry, or null when it was not there. */\nfunction queueTake(live: Live, q: number, id: number): QEntry | null {\n const mask = live.where.get(id);\n if (mask === undefined || (mask & (1 << q)) === 0) return null;\n const queue = live.queues[q] as QueueL;\n const k = queueFind(queue, id);\n const rest = mask & ~(1 << q);\n if (rest === 0) live.where.delete(id);\n else live.where.set(id, rest);\n if (k < 0) return null;\n const entry = queue.items[k] as QEntry;\n if (k === queue.head) {\n // The usual case: queues drain from the front. Moving `head` instead of\n // shifting the array keeps a long drain linear.\n queue.head++;\n if (queue.head === queue.items.length) {\n queue.items = [];\n queue.head = 0;\n } else if (queue.head >= 1024 && queue.head * 2 >= queue.items.length) {\n queue.items = queue.items.slice(queue.head);\n queue.head = 0;\n }\n } else {\n queue.items.splice(k, 1);\n }\n return entry;\n}\n\nfunction inStack(live: Live, id: number): boolean {\n const stack = live.stack;\n for (let k = stack.length - 1; k >= 0; k--) if ((stack[k] as FrameL).id === id) return true;\n return false;\n}\n\n// ---- timers ---------------------------------------------------------------------\n\nfunction timerCount(live: Live, state: number, d: number): void {\n if (state === T_WAITING) live.tWaiting += d;\n else if (state === T_RUNNING) live.tRunning += d;\n else if (state === T_DONE) live.tDone += d;\n else if (state === T_CLEARED) live.tCleared += d;\n}\n\n/**\n * Bring the timer bookkeeping of one item up to date after event `i`.\n * `before` is the timer's state before the event. Both states come from the\n * same function of the index, so counts, lists and TimerView.state agree.\n */\nfunction timerMoved(live: Live, index: RunIndex, rec: ItemRec, before: number, i: number): void {\n const after = index.timerStateAt(rec, i + 1, inStack(live, rec.id));\n if (after === before) return;\n if (before === T_NONE) live.tSet++;\n timerCount(live, before, -1);\n timerCount(live, after, 1);\n const activeAfter = after === T_WAITING || after === T_RUNNING;\n const activeBefore = before === T_WAITING || before === T_RUNNING;\n if (activeAfter && !activeBefore) {\n live.timersActive.add(rec.id);\n const k = live.timersRecent.indexOf(rec.id);\n if (k >= 0) live.timersRecent.splice(k, 1);\n } else if (!activeAfter) {\n live.timersActive.delete(rec.id);\n const k = live.timersRecent.indexOf(rec.id);\n if (k >= 0) live.timersRecent.splice(k, 1);\n live.timersRecent.push(rec.id);\n if (live.timersRecent.length > RECENT_TIMERS) live.timersRecent.shift();\n }\n}\n\n/**\n * The timers among `frames` (callbacks about to leave the stack), each once,\n * with its state at position `i`, to hand to timerMoved after the stack changed.\n */\nfunction stackTimers(live: Live, index: RunIndex, frames: readonly FrameL[], i: number): [ItemRec, number][] {\n const out: [ItemRec, number][] = [];\n for (const f of frames) {\n const rec = index.items.get(f.id);\n if (rec === undefined || rec.timer === null) continue;\n let seen = false;\n for (const o of out) if (o[0] === rec) seen = true;\n if (!seen) out.push([rec, index.timerStateAt(rec, i, true)]);\n }\n return out;\n}\n\n// ---- pool -----------------------------------------------------------------------\n\nfunction dropFrom(list: string[], job: string): boolean {\n const k = list.indexOf(job);\n if (k < 0) return false;\n list.splice(k, 1);\n return true;\n}\n\nfunction ensureThread(live: Live, thread: number): void {\n while (live.threads.length < thread) live.threads.push({ job: null, tid: -1, jobs: 0 });\n}\n\n/** Take a job out of wherever it is shown: the waiting list, its thread, the done list. Its record stays. */\nfunction detach(live: Live, job: JobL): void {\n if (job.state === JOB_WAITING) {\n dropFrom(live.poolWaiting, job.job);\n return;\n }\n const th = job.thread > 0 ? live.threads[job.thread - 1] : undefined;\n if (th !== undefined && th.job === job.job) live.threads[job.thread - 1] = { job: null, tid: th.tid, jobs: th.jobs };\n if (job.done) doneRemove(live, job);\n}\n\n/** Put a job at the end of the done list. */\nfunction doneAdd(live: Live, job: JobL): void {\n live.jobs.set(job.job, job.done ? job : { ...job, done: true });\n live.poolDone.push(job.job);\n if (job.id < 0) live.doneUntied++;\n}\n\n/** Take a job out of the done list (its record is left to the caller). */\nfunction doneRemove(live: Live, job: JobL): void {\n if (!dropFrom(live.poolDone, job.job)) return;\n if (job.id < 0) live.doneUntied--;\n}\n\n/** Thread `thread` now holds job `name`. `started`: count it as a job the thread started. */\nfunction occupy(live: Live, thread: number, name: string, tid: number | undefined, started: boolean): void {\n ensureThread(live, thread);\n const th = live.threads[thread - 1] as ThreadL;\n if (th.job !== null && th.job !== name) {\n // The thread was shown with another job that never reported its end.\n // One thread holds one job: the old one is no longer there.\n live.inconsistent++;\n live.jobs.delete(th.job);\n }\n live.threads[thread - 1] = { job: name, tid: tid === undefined ? th.tid : tid, jobs: th.jobs + (started ? 1 : 0) };\n}\n\n/**\n * The callback of an item started, or the item went away: the results of\n * its pool jobs have reached the loop (rule \"replay:delivered\").\n *\n * - A job in the done list leaves it.\n * - A job that still shows as waiting leaves too. File system requests and\n * dns.lookup run on the pool without any report from the thread (rule W6\n * of the event format): their job is only ever \"queued\", and the callback\n * is the one sign that the work was done.\n * - A job shown on a thread stays until that thread reports its end: the\n * report is on its way (thread-side times are approximate), and when it\n * arrives finishJob sees that the callback has already run.\n *\n * The item's jobs are found through the index (the names tied to it before\n * this event), so nothing is searched when the item has none.\n */\nfunction deliver(live: Live, rec: ItemRec, i: number): void {\n const names = rec.jobNames;\n for (let k = 0; k < names.length && (rec.jobIndexes[k] as number) < i; k++) {\n const job = live.jobs.get(names[k] as string);\n if (job === undefined || job.id !== rec.id) continue;\n if (job.state === JOB_WAITING) dropFrom(live.poolWaiting, job.job);\n else if (job.done) doneRemove(live, job);\n else continue;\n live.jobs.delete(job.job);\n live.pDelivered++;\n }\n}\n\n/** A finished job joins the done list, unless its result evidently arrived already. */\nfunction finishJob(live: Live, index: RunIndex, job: JobL, i: number): void {\n if (job.id >= 0) {\n const rec = index.items.get(job.id);\n // Thread-side times are approximate against the main thread (`tq`), so\n // \"finished\" can land after the callback that consumed the result. The\n // callback is the stronger fact: the result was delivered.\n const since = job.queuedIndex >= 0 ? job.queuedIndex : job.startedIndex;\n if (rec !== undefined && ((rec.goneIndex >= 0 && rec.goneIndex <= i) || lastBelow(rec.starts, i + 1) > since)) {\n live.jobs.delete(job.job);\n live.pDelivered++;\n return;\n }\n }\n doneAdd(live, job);\n // Jobs of no known item can never be seen leaving; keep only the latest few (see UNLINKED_DONE_LIMIT).\n for (let k = 0; live.doneUntied > UNLINKED_DONE_LIMIT && k < live.poolDone.length; ) {\n const name = live.poolDone[k] as string;\n if ((live.jobs.get(name) as JobL).id < 0) {\n live.poolDone.splice(k, 1);\n live.jobs.delete(name);\n live.pDropped++;\n live.doneUntied--;\n } else k++;\n }\n}\n\n// ---- callbacks ----------------------------------------------------------------------\n\n/** Which rule lets us say how a callback of this type got onto the main thread, when the item was in no queue. */\nfunction viaFromType(type: string, platform: string): { via: number; rule: string } | null {\n if (type === 'TickObject') return { via: VIA_TICK, rule: 'K1' };\n if (type === 'PROMISE' || type === 'Microtask') return { via: VIA_MICRO, rule: 'M1' };\n if (type === 'Timeout') return { via: VIA_PHASE, rule: 'T1' };\n if (type === 'Immediate') return { via: VIA_PHASE, rule: 'I1' };\n if (isPoolBackedType(type)) return { via: VIA_PHASE, rule: platform === 'win32' ? 'P1w' : 'P1u' };\n if (isIoRequestType(type) || PERSISTENT_HANDLE_TYPES.has(type)) return { via: VIA_PHASE, rule: 'P2' };\n // Anything else (a user AsyncResource, for example) can be run from anywhere.\n return null;\n}\n\nfunction setStatus(live: Live): void {\n if (live.endIndex >= 0) live.status = 'ended';\n else if (live.startIndex < 0) live.status = 'idle';\n else if (live.paused) live.status = 'paused';\n else if (live.gateStopped) live.status = 'gate';\n else live.status = 'running';\n}\n\nfunction leavePhase(live: Live, i: number): void {\n if (live.phase === 0) return;\n live.lastPhase = live.phase;\n live.lastPhaseEntered = live.phaseIndex;\n live.lastPhaseLeft = i;\n live.phase = 0;\n live.phaseIndex = -1;\n}\n\n/** The loop did something: the main script is over. */\nfunction loopActivity(live: Live, i: number): void {\n if (live.mainScript) {\n live.mainScript = false;\n if (live.stack.length === 0) live.idleIndex = i;\n }\n}\n\n/**\n * Apply the event at index `i` to `live`. `flags` are the event's flags from\n * the index, which must already contain this event. `events` is the whole\n * list (earlier events are read for details such as the platform).\n *\n * Returns 1 + the TIMELINE_CLASSES index this event counts as, or 0.\n */\nexport function applyEvent(live: Live, e: NmEvent, i: number, flags: number, index: RunIndex, events: readonly NmEvent[]): number {\n if ((flags & F_SKIP) !== 0) {\n if ((flags & F_UNKNOWN) !== 0) live.unknown++;\n else live.malformed++;\n return 0;\n }\n if (e.at !== undefined && e.at !== '') live.focusIndex = i;\n let cls = 0;\n\n switch (e.k) {\n case 'run.start': {\n if (live.startIndex >= 0) live.inconsistent++;\n live.startIndex = i;\n live.endIndex = -1;\n live.mainScript = true;\n live.poolPosts = e.caps.poolThreads === 'live';\n live.poolSizeIndex = -1;\n const size = Math.max(0, Math.min(1024, Math.floor(e.poolSize)));\n ensureThread(live, size);\n setStatus(live);\n break;\n }\n case 'run.end': {\n live.endIndex = i;\n // Nothing runs in a process that has exited. Queues and pool lists are\n // left as they were: that is what never got to run.\n const cut = stackTimers(live, index, live.stack, i);\n if (live.stack.length > 0) live.stack = [];\n for (const [rec, before] of cut) timerMoved(live, index, rec, before, i);\n live.mainScript = false;\n live.idleIndex = i;\n leavePhase(live, i);\n if (live.paused) {\n live.paused = false;\n live.lastPausedIndex = live.pausedIndex;\n live.lastResumedIndex = -1;\n }\n live.gateStopped = false;\n live.clockFrozen = false;\n setStatus(live);\n break;\n }\n case 'output':\n live.outputCount++;\n cls = e.stream === 'stdout' ? 9 : 10;\n break;\n case 'item.new': {\n const rec = index.items.get(e.id);\n if (rec !== undefined && rec.newIndex !== i) live.inconsistent++; // a second item.new for the same id\n break;\n }\n case 'callback.start': {\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = index.timerStateAt(rec, i, inStack(live, e.id));\n live.mainScript = false;\n const depth = live.stack.length;\n // The type as this very event states it, so that applying the event\n // again later (after a jump) cannot come out differently.\n const type = e.type;\n let via = VIA_UNKNOWN;\n let viaIndex = -1;\n let viaRule: string | null = null;\n let queue = -1;\n const mask = live.where.get(e.id);\n if (mask !== undefined) {\n for (let q = 0; q < 7; q++) {\n if ((mask & (1 << q)) === 0) continue;\n if (q === 5 && PERSISTENT_HANDLE_TYPES.has(type)) {\n // A handle stays in \"io\" across its callbacks.\n const io = live.queues[5] as QueueL;\n const k = queueFind(io, e.id);\n if (k >= 0) {\n const entry = io.items[k] as QEntry;\n io.items[k] = { id: entry.id, index: entry.index, runs: entry.runs + 1 };\n if (queue < 0) {\n queue = q;\n viaIndex = entry.index;\n }\n }\n continue;\n }\n const entry = queueTake(live, q, e.id);\n if (entry !== null && queue < 0) {\n queue = q;\n viaIndex = entry.index;\n }\n }\n }\n if (queue >= 0) {\n via = queue === 0 ? VIA_TICK : queue === 1 ? VIA_MICRO : VIA_PHASE;\n } else {\n const start = live.startIndex >= 0 ? events[live.startIndex] : undefined;\n const platform = start !== undefined && start.k === 'run.start' ? start.node.platform : '';\n const guess = viaFromType(type, platform);\n if (guess !== null) {\n via = guess.via;\n viaRule = guess.rule;\n }\n }\n live.stack.push({ id: e.id, index: i, via, viaIndex, viaRule, queue, phase: depth === 0 ? live.phase : 0, phaseIndex: depth === 0 ? live.phaseIndex : -1, depth });\n deliver(live, rec, i);\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n cls = queue >= 0 ? queue + 1 : 8;\n break;\n }\n case 'callback.end': {\n const stack = live.stack;\n let k = stack.length - 1;\n while (k >= 0 && (stack[k] as FrameL).id !== e.id) k--;\n if (k < 0) {\n live.inconsistent++; // an end without a start\n break;\n }\n if (k !== stack.length - 1) live.inconsistent++; // callbacks above it never ended; they cannot still be running\n const closing = stack.slice(k);\n const moved = stackTimers(live, index, closing, i);\n stack.length = k;\n if (k === 0) live.idleIndex = i;\n for (const [rec, before] of moved) timerMoved(live, index, rec, before, i);\n break;\n }\n case 'item.gone': {\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = index.timerStateAt(rec, i, inStack(live, e.id));\n const mask = live.where.get(e.id);\n if (mask !== undefined) for (let q = 0; q < 7; q++) if ((mask & (1 << q)) !== 0) queueTake(live, q, e.id);\n deliver(live, rec, i);\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'promise.settled':\n break;\n case 'timer.set': {\n const rec = index.items.get(e.id) as ItemRec;\n if (rec.timer !== null && rec.timer.setIndex !== i) live.inconsistent++; // set twice: the index treats it as armed again\n timerMoved(live, index, rec, index.timerStateAt(rec, i, inStack(live, e.id)), i);\n break;\n }\n case 'loop.sample':\n live.sampleIndex = i;\n break;\n case 'scope':\n // Node reports these two from inside the loop: the main script is over.\n if (e.name === 'RunTimers' || e.name === 'CheckImmediate') loopActivity(live, i);\n live.scopeIndex = i;\n break;\n case 'pool.thread': {\n if (e.tid === undefined) break;\n const old = live.tids.get(e.tid);\n const starts = (old === undefined ? 0 : old.starts) + (e.edge === 'start' ? 1 : 0);\n const ends = (old === undefined ? 0 : old.ends) + (e.edge === 'end' ? 1 : 0);\n live.tids.set(e.tid, { tid: e.tid, busy: e.edge === 'start', name: e.name, index: i, starts, ends });\n break;\n }\n case 'signal':\n break;\n case 'queue.add': {\n const q = queueCode(e.queue);\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = q === 2 ? index.timerStateAt(rec, i, inStack(live, e.id)) : T_NONE;\n const mask = live.where.get(e.id) ?? 0;\n // Already there (a handle the helper reports again): one entry, waiting since the first report.\n if ((mask & (1 << q)) === 0) queuePush(live, q, { id: e.id, index: i, runs: 0 });\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'queue.remove': {\n const q = queueCode(e.queue);\n const rec = index.items.get(e.id);\n const timerBefore = q === 2 && rec !== undefined ? index.timerStateAt(rec, i, inStack(live, e.id)) : T_NONE;\n queueTake(live, q, e.id);\n if (rec !== undefined && timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'loop.turn':\n loopActivity(live, i);\n // A new turn: the phase shown from the turn before is over.\n leavePhase(live, i);\n live.turn = e.n;\n live.turnIndex = i;\n break;\n case 'phase.enter': {\n loopActivity(live, i);\n leavePhase(live, i);\n live.phase = phaseCode(e.phase);\n live.phaseIndex = i;\n if (e.pollTimeoutMs !== undefined) live.pollIndex = i;\n if (e.turn !== undefined && e.turn !== live.turn) {\n live.turn = e.turn;\n live.turnIndex = i;\n }\n break;\n }\n case 'phase.leave': {\n const p = phaseCode(e.phase);\n if (live.phase === p) leavePhase(live, i);\n else if (live.phase === 0) {\n // We did not see it start.\n live.lastPhase = p;\n live.lastPhaseEntered = -1;\n live.lastPhaseLeft = i;\n } else live.inconsistent++; // leaving a phase that is not the one shown; the shown one started later, keep it\n break;\n }\n case 'timer.fired':\n loopActivity(live, i);\n live.firedCount++;\n live.firedIndex = i;\n break;\n case 'pool.queued': {\n const old = live.jobs.get(e.job);\n if (old !== undefined) {\n // The same job name twice: the new report replaces the old job.\n live.inconsistent++;\n detach(live, old);\n }\n live.jobs.set(e.job, {\n job: e.job,\n kind: e.kind,\n op: e.op === undefined ? null : e.op,\n id: e.id === undefined ? -1 : e.id,\n linkIndex: e.id === undefined ? -1 : i,\n state: JOB_WAITING,\n thread: 0,\n queuedIndex: i,\n startedIndex: -1,\n finishedIndex: -1,\n postedIndex: -1,\n done: false,\n atIndex: e.at === undefined ? -1 : i,\n });\n live.poolWaiting.push(e.job);\n live.pQueued++;\n cls = 12;\n break;\n }\n case 'pool.started': {\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n // Started without a \"queued\" report (reports can be lost, rule G1): show what we know.\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n if (job.state !== JOB_WAITING) live.inconsistent++; // started twice, or after it finished\n detach(live, job);\n }\n occupy(live, e.thread, e.job, e.tid, true);\n live.jobs.set(e.job, { ...job, state: JOB_RUNNING, thread: e.thread, startedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i });\n live.pStarted++;\n cls = 12;\n break;\n }\n case 'pool.finished': {\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n // Finished on another thread than it started on, or finished twice. (Waiting: the \"started\" report was lost; that is rule G1, not a contradiction.)\n if ((job.state === JOB_RUNNING && job.thread !== e.thread) || job.state >= JOB_FINISHED) live.inconsistent++;\n detach(live, job);\n }\n live.pFinished++;\n const finished: JobL = { ...job, state: JOB_FINISHED, thread: e.thread, finishedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i };\n if (live.poolPosts) {\n // This binary reports the posting of results (probe build). Until\n // `pool.posted` the thread still holds the job: it has to hand the\n // result to the loop, and a \"poolPost\" gate can hold it right here.\n occupy(live, e.thread, e.job, e.tid, false);\n live.jobs.set(e.job, finished);\n } else {\n // An official build says nothing more about this job. Its thread is\n // free for the next one and the result is on its way to the loop.\n finishJob(live, index, finished, i);\n }\n cls = 12;\n break;\n }\n case 'pool.posted': {\n live.poolPosts = true;\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n if (job.state === JOB_POSTED) live.inconsistent++; // posted twice\n detach(live, job);\n }\n live.pPosted++;\n finishJob(live, index, { ...job, state: JOB_POSTED, thread: e.thread, postedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i }, i);\n cls = 12;\n break;\n }\n case 'pool.delivered': {\n const job = live.jobs.get(e.job);\n cls = 12;\n if (job === undefined) break; // already off the screen (cancelled, or its item's callback was seen first)\n if (job.state === JOB_WAITING || job.state === JOB_RUNNING) live.inconsistent++; // a result with no report of the work ending\n detach(live, job);\n live.jobs.delete(e.job);\n live.pDelivered++;\n break;\n }\n case 'pool.cancelled': {\n const job = live.jobs.get(e.job);\n cls = 12;\n if (job === undefined) break;\n if (job.state !== JOB_WAITING) {\n live.inconsistent++; // a thread had picked it up; it cannot have been cancelled, so it stays where it is\n break;\n }\n detach(live, job);\n live.jobs.delete(e.job);\n live.pCancelled++;\n break;\n }\n case 'pool.size': {\n // The pool has this many threads from here on. Lanes above the new\n // size go, unless the events have shown them at work: a lane that\n // holds a job or ran one stays, and shows as \"extra\".\n live.poolSizeIndex = i;\n ensureThread(live, e.size);\n while (live.threads.length > e.size) {\n const last = live.threads[live.threads.length - 1] as ThreadL;\n if (last.job !== null || last.jobs > 0) break;\n live.threads.pop();\n }\n cls = 12;\n break;\n }\n case 'pool.link': {\n const job = live.jobs.get(e.job);\n if (job === undefined) break; // a link for a job that is not on screen\n if (job.done) {\n // Now that we know whose job it is: was its result consumed already?\n doneRemove(live, job);\n live.jobs.delete(e.job);\n finishJob(live, index, { ...job, id: e.id, linkIndex: i, done: false }, i);\n } else live.jobs.set(e.job, { ...job, id: e.id, linkIndex: i });\n break;\n }\n case 'debug.paused':\n live.paused = true;\n live.pausedIndex = i;\n live.pauses++;\n setStatus(live);\n cls = 11;\n break;\n case 'debug.resumed':\n live.lastPausedIndex = live.paused ? live.pausedIndex : -1;\n live.lastResumedIndex = i;\n live.paused = false;\n live.pausedIndex = -1;\n setStatus(live);\n break;\n case 'gate.stopped':\n live.gateStopped = true;\n live.gateIndex = i;\n live.gateStops++;\n setStatus(live);\n cls = 11;\n break;\n case 'gate.released':\n live.gateStopped = false;\n live.gateReleasedIndex = i;\n setStatus(live);\n break;\n case 'clock.frozen':\n live.clockFrozen = true;\n live.clockIndex = i;\n break;\n case 'clock.unfrozen':\n live.clockFrozen = false;\n live.clockUnfrozenIndex = i;\n live.hiddenMs += e.hiddenMs;\n break;\n case 'note':\n live.noteCount++;\n cls = 13;\n break;\n default:\n break;\n }\n return cls;\n}\n","/**\n * Rules this package applies itself.\n *\n * Almost everything on screen is a direct reflection of an event and carries\n * that event's certainty and rule. In a few places the reducer has to\n * conclude something that no event states. Each such conclusion is listed\n * here, is always marked \"inferred\", and names its rule in the Fact it puts\n * into the view, so the UI can show the reasoning exactly as it does for the\n * helper's rules (RULES in @nodejs-map/event-format). Ids start with\n * \"replay:\" so they can never collide with those.\n *\n * `cites` use the same atlas id scheme as the event format's rules. The ids\n * below follow the naming of ids that rules.ts of the event format already\n * cites; they have not been checked against a built atlas from here (the\n * proof suite that does this reads RULES, not this list).\n */\n\nimport type { Rule } from '@nodejs-map/event-format';\n\nexport const RULE_MAIN = 'replay:main';\nexport const RULE_DUE = 'replay:due';\nexport const RULE_HANDLE = 'replay:handle';\nexport const RULE_DELIVERED = 'replay:delivered';\n\nexport const REPLAY_RULES: readonly Rule[] = [\n {\n id: RULE_MAIN,\n title: 'The main script is running',\n statement:\n 'The run has started and no callback has started and the event loop has reported nothing yet. Node runs its start-up code and then the main script before it enters the loop, so the main thread is running one of the two. For an ES module the body itself runs inside promise callbacks, which then show as callbacks.',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:lib/internal/modules/run_main.js#executeUserEntryPoint', 'o:loop.run'],\n },\n {\n id: RULE_DUE,\n title: 'When a timer is due',\n statement:\n \"A timer was armed (set, or put back after a run) with a delay. We show it as due at the time of that event plus the delay, and measure lateness against that. Node starts the delay from the loop's cached clock, which was read at the start of the current loop turn, so the real due time can be earlier than shown by the time the current callback had already been running.\",\n yields: 'inferred',\n platform: 'all',\n cites: ['s:lib/internal/timers.js#Timeout.prototype.constructor', 's:lib/internal/timers.js#insert', 'o:timers.listOnTimeout'],\n },\n {\n id: RULE_HANDLE,\n title: 'A handle keeps waiting after its callback',\n statement:\n 'An item whose type is a libuv handle (a socket, a server, a pipe, a child process, a watcher) was waiting on the operating system and one of its callbacks ran. A handle stays registered with the loop until it is closed, so it is still shown as waiting. It leaves when it is reported destroyed.',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:src/handle_wrap.cc#node::HandleWrap::OnClose', 'o:phase.poll'],\n },\n {\n id: RULE_DELIVERED,\n title: 'The result of a pool job reached the loop',\n statement:\n 'The callback of an item started, or the item was destroyed, while a pool job of that item was shown as finished or as still queued. The after-work callback on the main thread is what leads to that callback, so the work is done and its result is no longer waiting to be delivered. (File system requests and dns.lookup report nothing from the pool thread; for them the callback is the only sign that the work ran.)',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:deps/uv/src/threadpool.c#uv__work_done', 'o:pool.done'],\n },\n];\n\nconst BY_ID = new Map<string, Rule>(REPLAY_RULES.map((r) => [r.id, r]));\n\n/** The replay rule with this id, or undefined. */\nexport function replayRuleById(id: string): Rule | undefined {\n return BY_ID.get(id);\n}\n","/**\n * Builds the public ViewState (plain data) from the live state at a\n * position, the run index and the event list.\n *\n * Cost is proportional to what is on screen (capped by ViewOptions), not to\n * the length of the run.\n *\n * Internal: not part of the public API.\n */\n\nimport type { Certainty, EventKind, NmEvent, Phase, QueueName } from '@nodejs-map/event-format';\nimport type {\n CallbackFrame,\n CallbackVia,\n DebugView,\n Fact,\n FocusView,\n ItemRef,\n ItemState,\n ItemView,\n LogEntry,\n LoopView,\n MainThreadView,\n NoteView,\n OutputChunk,\n PoolJobState,\n PoolJobView,\n PoolThreadView,\n PoolTidView,\n PoolView,\n QueueEntryView,\n QueueView,\n RunView,\n TimerState,\n TimerView,\n TimersView,\n ViewOptions,\n ViewState,\n WaitingPlace,\n} from './types.ts';\nimport { F_SKIP, PHASES, QUEUE_NAMES, countBelow, factOf, lastBelow, weaker } from './run-index.ts';\nimport type { ItemRec, RunIndex } from './run-index.ts';\nimport { JOB_RUNNING, JOB_WAITING } from './reducer.ts';\nimport type { FrameL, JobL, Live, QEntry, QueueL } from './reducer.ts';\nimport { RULE_DUE, RULE_MAIN } from './rules.ts';\n\nexport interface ViewContext {\n index: RunIndex;\n events: readonly NmEvent[];\n length: number;\n ready: number;\n live: boolean;\n version: number;\n}\n\nexport const DEFAULT_VIEW: Required<ViewOptions> = { maxEntries: 200, maxOutput: 200, maxNotes: 50, maxLog: 50, items: 'none' };\n\nexport function resolveOptions(base: Required<ViewOptions>, o: ViewOptions | undefined): Required<ViewOptions> {\n if (o === undefined) return base;\n const cap = (v: number | undefined, d: number): number => (typeof v === 'number' && v >= 0 ? Math.floor(v) : d);\n return {\n maxEntries: cap(o.maxEntries, base.maxEntries),\n maxOutput: cap(o.maxOutput, base.maxOutput),\n maxNotes: cap(o.maxNotes, base.maxNotes),\n maxLog: cap(o.maxLog, base.maxLog),\n items: o.items === 'all' || o.items === 'none' ? o.items : base.items,\n };\n}\n\nconst VIA_NAMES: readonly CallbackVia[] = ['unknown', 'phase', 'nextTick', 'microtask'];\nconst TIMER_STATES: readonly (TimerState | null)[] = [null, 'waiting', 'running', 'done', 'cleared'];\n\nfunction fact(ctx: ViewContext, i: number): Fact {\n return factOf(ctx.events[i] as NmEvent, i);\n}\n\nfunction factOrNull(ctx: ViewContext, i: number): Fact | null {\n return i < 0 ? null : fact(ctx, i);\n}\n\nfunction inStack(live: Live, id: number): boolean {\n for (const f of live.stack) if (f.id === id) return true;\n return false;\n}\n\nexport function refOf(ctx: ViewContext, id: number, p: number): ItemRef {\n const rec = ctx.index.items.get(id);\n if (rec === undefined || rec.firstIndex >= p) return { id, type: '?', label: null, trigger: 0, loc: null, created: null };\n return ctx.index.refAt(rec, p);\n}\n\nexport function timerView(ctx: ViewContext, live: Live, rec: ItemRec, p: number): TimerView | null {\n const tm = rec.timer;\n if (tm === null || tm.setIndex >= p) return null;\n const events = ctx.events;\n const armIndex = lastBelow(tm.arms, p);\n const startIndex = lastBelow(rec.starts, p);\n const state = TIMER_STATES[ctx.index.timerStateAt(rec, p, inStack(live, rec.id))] as TimerState;\n const armed = fact(ctx, armIndex);\n const delayUs = tm.delayMs * 1000;\n let lateMs: number | null = null;\n if (startIndex >= 0) {\n const armAtStart = lastBelow(tm.arms, startIndex);\n if (armAtStart >= 0) lateMs = ((events[startIndex] as NmEvent).t - ((events[armAtStart] as NmEvent).t + delayUs)) / 1000;\n }\n return {\n item: ctx.index.refAt(rec, p),\n delayMs: tm.delayMs,\n repeat: tm.repeat,\n set: fact(ctx, tm.setIndex),\n armed,\n dueT: armed.t + delayUs,\n dueFrom: { c: 'inferred', rule: RULE_DUE, index: armIndex, t: armed.t },\n state,\n runs: countBelow(rec.starts, p),\n lastRun: factOrNull(ctx, startIndex),\n lateMs,\n cleared: tm.clearedIndex >= 0 && tm.clearedIndex < p ? fact(ctx, tm.clearedIndex) : null,\n };\n}\n\nexport function itemView(ctx: ViewContext, live: Live, rec: ItemRec, p: number): ItemView {\n const ref = ctx.index.refAt(rec, p);\n const runs = countBelow(rec.starts, p);\n const ends = countBelow(rec.ends, p);\n const gone = rec.goneIndex >= 0 && rec.goneIndex < p;\n const mask = live.where.get(rec.id) ?? 0;\n const queues: QueueName[] = [];\n for (let q = 0; q < 7; q++) if ((mask & (1 << q)) !== 0) queues.push(QUEUE_NAMES[q] as QueueName);\n let state: ItemState;\n if (gone) state = 'gone';\n else if (inStack(live, rec.id)) state = 'running';\n else if (queues.length > 0) state = 'waiting';\n else if (runs > 0) state = 'ran';\n else state = 'created';\n const jobs = countBelow(rec.jobIndexes, p);\n return {\n id: ref.id,\n type: ref.type,\n label: ref.label,\n trigger: ref.trigger,\n loc: ref.loc,\n created: ref.created,\n state,\n queues,\n runs,\n lastStart: runs > 0 ? fact(ctx, rec.starts[runs - 1] as number) : null,\n lastEnd: ends > 0 ? fact(ctx, rec.ends[ends - 1] as number) : null,\n gone: gone ? fact(ctx, rec.goneIndex) : null,\n settled: rec.settledIndex >= 0 && rec.settledIndex < p ? fact(ctx, rec.settledIndex) : null,\n timer: timerView(ctx, live, rec, p),\n job: jobs > 0 ? (rec.jobNames[jobs - 1] as string) : null,\n children: countBelow(rec.children, p),\n };\n}\n\nfunction frameView(ctx: ViewContext, f: FrameL, p: number): CallbackFrame {\n const from = fact(ctx, f.index);\n let viaFrom: Fact | null = null;\n if (f.viaIndex >= 0) viaFrom = fact(ctx, f.viaIndex);\n else if (f.viaRule !== null) viaFrom = { c: 'inferred', rule: f.viaRule, index: f.index, t: from.t };\n return {\n item: refOf(ctx, f.id, p),\n from,\n via: VIA_NAMES[f.via] as CallbackVia,\n viaFrom,\n queue: f.queue >= 0 ? (QUEUE_NAMES[f.queue] as QueueName) : null,\n phase: PHASES[f.phase] as Phase | null,\n phaseFrom: factOrNull(ctx, f.phaseIndex),\n phaseAfterPoll: afterPollAt(ctx, f.phaseIndex),\n depth: f.depth,\n };\n}\n\nconst JOB_STATES: readonly PoolJobState[] = ['waiting', 'running', 'finished', 'posted'];\n\n/** The gate event that holds the target right now, when it names a job. */\nfunction heldGate(ctx: ViewContext, live: Live): (NmEvent & { k: 'gate.stopped' }) | null {\n if (!live.gateStopped || live.gateIndex < 0) return null;\n const e = ctx.events[live.gateIndex] as NmEvent;\n return e.k === 'gate.stopped' && e.job !== undefined && (e.gate === 'poolStart' || e.gate === 'poolPost' || e.gate === 'poolDone') ? e : null;\n}\n\nfunction jobView(ctx: ViewContext, job: JobL, p: number, gate: (NmEvent & { k: 'gate.stopped' }) | null): PoolJobView {\n const atEvent = job.atIndex >= 0 ? (ctx.events[job.atIndex] as NmEvent) : undefined;\n return {\n job: job.job,\n kind: job.kind,\n op: job.op,\n state: JOB_STATES[job.state] as PoolJobState,\n item: job.id >= 0 ? refOf(ctx, job.id, p) : null,\n itemFrom: factOrNull(ctx, job.linkIndex),\n thread: job.thread > 0 ? job.thread : null,\n queued: factOrNull(ctx, job.queuedIndex),\n started: factOrNull(ctx, job.startedIndex),\n finished: factOrNull(ctx, job.finishedIndex),\n posted: factOrNull(ctx, job.postedIndex),\n at: atEvent !== undefined && atEvent.at !== undefined ? atEvent.at : null,\n held: gate !== null && gate.job === job.job ? gate.gate : null,\n };\n}\n\nfunction runView(ctx: ViewContext, live: Live): RunView {\n const start = live.startIndex >= 0 ? (ctx.events[live.startIndex] as NmEvent) : undefined;\n const end = live.endIndex >= 0 ? (ctx.events[live.endIndex] as NmEvent) : undefined;\n const s = start !== undefined && start.k === 'run.start' ? start : undefined;\n const x = end !== undefined && end.k === 'run.end' ? end : undefined;\n return {\n status: live.status,\n node: s === undefined ? null : s.node,\n caps: s === undefined ? null : s.caps,\n program: s === undefined ? null : s.program,\n mode: s === undefined ? null : s.mode,\n poolSize: s === undefined ? null : s.poolSize,\n exitCode: x === undefined || x.code === undefined ? null : x.code,\n signal: x === undefined || x.signal === undefined ? null : x.signal,\n started: factOrNull(ctx, live.startIndex),\n ended: factOrNull(ctx, live.endIndex),\n };\n}\n\nfunction mainView(ctx: ViewContext, live: Live, p: number): MainThreadView {\n if (live.stack.length > 0) {\n const stack = live.stack.map((f) => frameView(ctx, f, p));\n return { doing: 'callback', from: (stack[stack.length - 1] as CallbackFrame).from, stack };\n }\n if (live.mainScript && live.startIndex >= 0) {\n const start = fact(ctx, live.startIndex);\n // `run.start` is observed; that the main script is what runs after it is our conclusion.\n return { doing: 'main', from: { c: 'inferred', rule: RULE_MAIN, index: start.index, t: start.t }, stack: [] };\n }\n return { doing: 'nothing', from: factOrNull(ctx, live.idleIndex), stack: [] };\n}\n\n/** Does the phase event at index `i` mark the second run of pending callbacks, right after poll? */\nfunction afterPollAt(ctx: ViewContext, i: number): boolean {\n if (i < 0) return false;\n const e = ctx.events[i] as NmEvent;\n return (e.k === 'phase.enter' || e.k === 'phase.leave') && e.afterPoll === true;\n}\n\nfunction loopView(ctx: ViewContext, live: Live): LoopView {\n const scope = live.scopeIndex >= 0 ? (ctx.events[live.scopeIndex] as NmEvent) : undefined;\n const sample = live.sampleIndex >= 0 ? (ctx.events[live.sampleIndex] as NmEvent) : undefined;\n const pollEvent = live.pollIndex >= 0 ? (ctx.events[live.pollIndex] as NmEvent) : undefined;\n return {\n turn: live.turnIndex >= 0 ? live.turn : null,\n turnFrom: factOrNull(ctx, live.turnIndex),\n phase: PHASES[live.phase] as Phase | null,\n phaseFrom: live.phase === 0 ? null : factOrNull(ctx, live.phaseIndex),\n afterPoll: live.phase !== 0 && afterPollAt(ctx, live.phaseIndex),\n poll:\n pollEvent !== undefined && pollEvent.k === 'phase.enter' && pollEvent.pollTimeoutMs !== undefined\n ? { timeoutMs: pollEvent.pollTimeoutMs, current: live.phase !== 0 && live.phaseIndex === live.pollIndex, from: fact(ctx, live.pollIndex) }\n : null,\n lastPhase:\n live.lastPhase === 0\n ? null\n : {\n phase: PHASES[live.lastPhase] as Phase,\n // Said by the enter event, or by the leave event when the enter was not seen.\n afterPoll: afterPollAt(ctx, live.lastPhaseEntered) || afterPollAt(ctx, live.lastPhaseLeft),\n entered: factOrNull(ctx, live.lastPhaseEntered),\n left: fact(ctx, live.lastPhaseLeft),\n },\n lastScope: scope !== undefined && scope.k === 'scope' ? { name: scope.name, durUs: scope.durUs, from: fact(ctx, live.scopeIndex) } : null,\n lastSample:\n sample !== undefined && sample.k === 'loop.sample'\n ? { loopCount: sample.loopCount, events: sample.events, eventsWaiting: sample.eventsWaiting, from: fact(ctx, live.sampleIndex) }\n : null,\n };\n}\n\nfunction queueView(ctx: ViewContext, name: QueueName, q: QueueL, p: number, max: number, ended: boolean): QueueView {\n const total = q.items.length - q.head;\n const n = Math.min(total, max);\n const entries: QueueEntryView[] = [];\n for (let k = 0; k < n; k++) {\n const entry = q.items[q.head + k] as QEntry;\n const e = ctx.events[entry.index] as NmEvent;\n entries.push({ item: refOf(ctx, entry.id, p), from: factOf(e, entry.index), at: e.at === undefined ? null : e.at, runs: entry.runs });\n }\n return { name, total, entries, truncated: n < total, leftAtEnd: ended && total > 0 };\n}\n\nfunction timersView(ctx: ViewContext, live: Live, p: number, max: number): TimersView {\n // Order by due time first (two numbers per timer), then build views for the ones that are shown only.\n const order: { rec: ItemRec; due: number; set: number }[] = [];\n for (const id of live.timersActive) {\n const rec = ctx.index.items.get(id);\n const tm = rec === undefined ? null : rec.timer;\n if (rec === undefined || tm === null || tm.setIndex >= p) continue;\n order.push({ rec, due: (ctx.events[lastBelow(tm.arms, p)] as NmEvent).t + tm.delayMs * 1000, set: tm.setIndex });\n }\n order.sort((a, b) => a.due - b.due || a.set - b.set);\n const truncated = order.length > max;\n const active: TimerView[] = [];\n for (let k = 0; k < order.length && k < max; k++) {\n const v = timerView(ctx, live, (order[k] as (typeof order)[number]).rec, p);\n if (v !== null) active.push(v);\n }\n const recent: TimerView[] = [];\n for (const id of live.timersRecent) {\n const rec = ctx.index.items.get(id);\n const v = rec === undefined ? null : timerView(ctx, live, rec, p);\n if (v !== null) recent.push(v);\n }\n const firedEvent = live.firedIndex >= 0 ? (ctx.events[live.firedIndex] as NmEvent) : undefined;\n return {\n active,\n recent,\n counts: { set: live.tSet, waiting: live.tWaiting, running: live.tRunning, done: live.tDone, cleared: live.tCleared },\n fired: {\n count: live.firedCount,\n last: firedEvent !== undefined && firedEvent.k === 'timer.fired' ? { lateMs: firedEvent.lateMs === undefined ? null : firedEvent.lateMs, from: fact(ctx, live.firedIndex) } : null,\n },\n truncated,\n leftAtEnd: live.endIndex >= 0 && live.tWaiting > 0,\n };\n}\n\nfunction poolView(ctx: ViewContext, live: Live, p: number, max: number, startSize: number | null): PoolView {\n // The size in effect: the latest pool.size, else what run.start said.\n const sizeEvent = live.poolSizeIndex >= 0 ? (ctx.events[live.poolSizeIndex] as NmEvent) : undefined;\n const size = sizeEvent !== undefined && sizeEvent.k === 'pool.size' ? sizeEvent.size : startSize;\n const sizeFrom = sizeEvent !== undefined && sizeEvent.k === 'pool.size' ? fact(ctx, live.poolSizeIndex) : factOrNull(ctx, live.startIndex);\n const gate = heldGate(ctx, live);\n let held: PoolView['held'] = null;\n if (gate !== null) {\n const name = gate.job as string;\n const job = live.jobs.get(name);\n let thread: number | null = null;\n if (gate.gate !== 'poolDone') {\n if (job !== undefined && job.state !== JOB_WAITING && job.thread > 0) thread = job.thread;\n else if (gate.tid !== undefined) {\n const k = live.threads.findIndex((th) => th.tid === gate.tid);\n if (k >= 0) thread = k + 1;\n }\n }\n held = {\n gate: gate.gate,\n job: name,\n where: gate.gate === 'poolDone' ? 'loop' : 'thread',\n thread,\n view: job === undefined ? null : jobView(ctx, job, p, gate),\n from: fact(ctx, live.gateIndex),\n };\n }\n const threads: PoolThreadView[] = [];\n for (let k = 0; k < live.threads.length; k++) {\n const th = live.threads[k] as (typeof live.threads)[number];\n const job = th.job === null ? undefined : live.jobs.get(th.job);\n threads.push({ thread: k + 1, job: job === undefined ? null : jobView(ctx, job, p, gate), tid: th.tid >= 0 ? th.tid : null, jobs: th.jobs, extra: size !== null && k + 1 > size });\n }\n const list = (names: string[]): PoolJobView[] => {\n const out: PoolJobView[] = [];\n for (let k = 0; k < names.length && out.length < max; k++) {\n const job = live.jobs.get(names[k] as string);\n if (job !== undefined) out.push(jobView(ctx, job, p, gate));\n }\n return out;\n };\n const tids: PoolTidView[] = [];\n for (const t of live.tids.values()) tids.push({ tid: t.tid, busy: t.busy, name: t.name, from: fact(ctx, t.index), starts: t.starts, ends: t.ends });\n tids.sort((a, b) => a.tid - b.tid);\n return {\n size,\n sizeFrom,\n threads,\n waiting: list(live.poolWaiting),\n done: list(live.poolDone),\n held,\n tids,\n counts: {\n queued: live.pQueued,\n started: live.pStarted,\n finished: live.pFinished,\n posted: live.pPosted,\n delivered: live.pDelivered,\n cancelled: live.pCancelled,\n droppedUnlinked: live.pDropped,\n },\n truncated: live.poolWaiting.length > max || live.poolDone.length > max,\n leftAtEnd: live.endIndex >= 0 && live.jobs.size > 0,\n };\n}\n\nfunction debugView(ctx: ViewContext, live: Live): DebugView {\n const paused = live.paused && live.pausedIndex >= 0 ? (ctx.events[live.pausedIndex] as NmEvent) : undefined;\n const pe = paused !== undefined && paused.k === 'debug.paused' ? paused : undefined;\n let lastPause: DebugView['lastPause'] = null;\n if (live.lastResumedIndex >= 0) {\n const resumed = ctx.events[live.lastResumedIndex] as NmEvent;\n const before = live.lastPausedIndex >= 0 ? (ctx.events[live.lastPausedIndex] as NmEvent) : undefined;\n if (resumed.k === 'debug.resumed') {\n lastPause = {\n pausedMs: resumed.pausedMs,\n timeKeptRunning: before !== undefined && before.k === 'debug.paused' ? before.timeKeptRunning : false,\n paused: factOrNull(ctx, live.lastPausedIndex),\n resumed: fact(ctx, live.lastResumedIndex),\n };\n }\n }\n const gate = live.gateStopped && live.gateIndex >= 0 ? (ctx.events[live.gateIndex] as NmEvent) : undefined;\n const ge = gate !== undefined && gate.k === 'gate.stopped' ? gate : undefined;\n const released = live.gateReleasedIndex >= 0 ? (ctx.events[live.gateReleasedIndex] as NmEvent) : undefined;\n const unfrozen = live.clockUnfrozenIndex >= 0 ? (ctx.events[live.clockUnfrozenIndex] as NmEvent) : undefined;\n const frozen = live.clockFrozen && live.clockIndex >= 0 ? (ctx.events[live.clockIndex] as NmEvent) : undefined;\n return {\n paused: live.paused,\n reason: pe === undefined ? null : pe.reason,\n frames: pe === undefined ? [] : pe.frames,\n timeKeptRunning: pe === undefined ? false : pe.timeKeptRunning,\n from: pe === undefined ? null : fact(ctx, live.pausedIndex),\n lastPause,\n pauses: live.pauses,\n gate: {\n stopped: live.gateStopped,\n gate: ge === undefined ? null : ge.gate,\n phase: ge === undefined || ge.phase === undefined ? null : ge.phase,\n job: ge === undefined || ge.job === undefined ? null : ge.job,\n from: ge === undefined ? null : fact(ctx, live.gateIndex),\n lastStoppedMs: released !== undefined && released.k === 'gate.released' ? released.stoppedMs : null,\n stops: live.gateStops,\n },\n clock: {\n frozen: live.clockFrozen,\n why: frozen !== undefined && frozen.k === 'clock.frozen' && (frozen.why === 'gate' || frozen.why === 'breakpoint') ? frozen.why : null,\n from: live.clockFrozen ? factOrNull(ctx, live.clockIndex) : null,\n lastHiddenMs: unfrozen !== undefined && unfrozen.k === 'clock.unfrozen' ? unfrozen.hiddenMs : null,\n hiddenMs: live.hiddenMs,\n },\n };\n}\n\nfunction focusView(ctx: ViewContext, live: Live, p: number): FocusView {\n const places = new Map<string, WaitingPlace>();\n const placeAt = (at: string | undefined, c: Certainty): WaitingPlace | null => {\n if (at === undefined || at === '') return null;\n let place = places.get(at);\n if (place === undefined) {\n place = { at, count: 0, c, waiting: 0, poolWaiting: 0, poolRunning: 0, poolDone: 0, queues: [], pool: false };\n places.set(at, place);\n }\n place.count++;\n place.c = weaker(place.c, c);\n return place;\n };\n for (let q = 0; q < 7; q++) {\n const queue = live.queues[q] as QueueL;\n const name = QUEUE_NAMES[q] as QueueName;\n for (let k = queue.head; k < queue.items.length; k++) {\n const entry = queue.items[k] as QEntry;\n if (q === 4) {\n // A request in the \"pool\" queue whose job is known is that job: the\n // job is counted below, at its own place, and the entry is not.\n const rec = ctx.index.items.get(entry.id);\n if (rec !== undefined && countBelow(rec.jobIndexes, p) > 0) continue;\n }\n const e = ctx.events[entry.index] as NmEvent;\n const place = placeAt(e.at, e.c);\n if (place === null) continue;\n place.waiting++;\n if (!place.queues.includes(name)) place.queues.push(name);\n }\n }\n for (const job of live.jobs.values()) {\n if (job.atIndex < 0) continue;\n const e = ctx.events[job.atIndex] as NmEvent;\n const place = placeAt(e.at, e.c);\n if (place === null) continue;\n place.pool = true;\n if (job.state === JOB_WAITING) place.poolWaiting++;\n else if (job.state === JOB_RUNNING) place.poolRunning++;\n else place.poolDone++;\n }\n const waiting = [...places.values()].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const fe = live.focusIndex >= 0 ? (ctx.events[live.focusIndex] as NmEvent) : undefined;\n return {\n at: fe === undefined || fe.at === undefined ? null : fe.at,\n from: fe === undefined ? null : fact(ctx, live.focusIndex),\n kind: fe === undefined ? null : (fe.k as EventKind),\n waiting,\n };\n}\n\nexport function logEntries(ctx: ViewContext, from: number, to: number): LogEntry[] {\n const a = Math.max(0, Math.floor(from));\n const b = Math.min(ctx.ready, Math.floor(to));\n const out: LogEntry[] = [];\n for (let i = a; i < b; i++) out.push({ index: i, event: ctx.events[i] as NmEvent, skipped: ((ctx.index.flags[i] as number) & F_SKIP) !== 0 });\n return out;\n}\n\nexport function outputRange(ctx: ViewContext, live: Live, fromSeq: number, toSeq: number): OutputChunk[] {\n const a = Math.max(0, Math.floor(fromSeq));\n const b = Math.min(live.outputCount, Math.floor(toSeq));\n return a < b ? ctx.index.output.slice(a, b) : [];\n}\n\nexport function itemsRange(ctx: ViewContext, live: Live, p: number, from: number, limit: number): ItemView[] {\n const total = ctx.index.itemsBefore(p);\n const a = Math.max(0, Math.floor(from));\n const b = Math.min(total, a + Math.max(0, Math.floor(limit)));\n const out: ItemView[] = [];\n for (let k = a; k < b; k++) out.push(itemView(ctx, live, ctx.index.order[k] as ItemRec, p));\n return out;\n}\n\n/** The view at position `p`, where `live` is the live state at `p`. */\nexport function buildView(ctx: ViewContext, live: Live, p: number, o: Required<ViewOptions>): ViewState {\n const index = ctx.index;\n const run = runView(ctx, live);\n const queues = {} as Record<QueueName, QueueView>;\n for (let q = 0; q < 7; q++) {\n const name = QUEUE_NAMES[q] as QueueName;\n queues[name] = queueView(ctx, name, live.queues[q] as QueueL, p, o.maxEntries, live.endIndex >= 0);\n }\n const itemsTotal = index.itemsBefore(p);\n const notes: NoteView[] = [];\n for (let k = Math.max(0, live.noteCount - o.maxNotes); k < live.noteCount; k++) {\n const i = index.notes[k] as number;\n const e = ctx.events[i] as NmEvent;\n if (e.k === 'note') notes.push({ seq: k, level: e.level, text: e.text, from: factOf(e, i) });\n }\n const outTotal = live.outputCount;\n return {\n position: p,\n length: ctx.length,\n ready: ctx.ready,\n live: ctx.live,\n version: ctx.version,\n t: p === 0 ? (ctx.ready > 0 ? (index.tMono[0] as number) : 0) : (index.tMono[p - 1] as number),\n endT: ctx.ready === 0 ? 0 : (index.tMono[ctx.ready - 1] as number),\n run,\n main: mainView(ctx, live, p),\n loop: loopView(ctx, live),\n queues,\n items: { total: itemsTotal, all: o.items === 'all' ? itemsRange(ctx, live, p, 0, itemsTotal) : null },\n timers: timersView(ctx, live, p, o.maxEntries),\n pool: poolView(ctx, live, p, o.maxEntries, run.poolSize),\n output: {\n total: outTotal,\n chars: outTotal === 0 ? 0 : (index.outputChars[outTotal - 1] as number),\n chunks: index.output.slice(Math.max(0, outTotal - o.maxOutput), outTotal),\n },\n debug: debugView(ctx, live),\n notes: { total: live.noteCount, items: notes },\n focus: focusView(ctx, live, p),\n log: logEntries(ctx, p - o.maxLog, p),\n problems: { unknown: live.unknown, malformed: live.malformed, inconsistent: live.inconsistent },\n };\n}\n","/**\n * The timeline summary for the scrubber.\n *\n * \"Computed incrementally\" here means: what each event contributes (its\n * class, the loop phase after it, paused or not, a callback running or not)\n * is worked out once, when the event is indexed, and stored in two bytes per\n * event (RunIndex.tlState and tlClass). Cutting the run into buckets for a\n * given width is then one pass over those bytes with no allocation per\n * event: about a millisecond for 100,000 events (see the measurements in the\n * test folder), cheap enough to redo on every resize and for every batch of\n * a live run. A prefix-sum structure would make it independent of the run\n * length, at 4 bytes per class per event; the single pass was chosen because\n * it is fast enough and costs no memory.\n */\n\nimport { TIMELINE_CLASSES } from './types.ts';\nimport type { NoteMarker, PauseMarker, TimelineAxis, TimelineClass, TimelineMarkers, TimelineSummary } from './types.ts';\nimport type { NmEvent } from '@nodejs-map/event-format';\nimport type { RunIndex } from './run-index.ts';\n\nconst CLASSES = TIMELINE_CLASSES.length;\nexport const MAX_TIMELINE_WIDTH = 8192;\n\n/**\n * Cut the first `n` events into `width` buckets.\n *\n * A bucket without events (more pixels than events, or a quiet stretch on\n * the time axis) shows the state left by the last event before it: the loop\n * was still in that phase, the program was still paused.\n */\nexport function buildTimeline(index: RunIndex, n: number, width: number, axis: TimelineAxis, version: number): TimelineSummary {\n const W = Math.max(1, Math.min(MAX_TIMELINE_WIDTH, Math.floor(Number.isFinite(width) ? width : 1)));\n const start = new Uint32Array(W);\n const events = new Uint32Array(W);\n const phase = new Uint8Array(W);\n const phaseCertainty = new Uint8Array(W);\n const paused = new Uint8Array(W);\n const busy = new Uint8Array(W);\n const counts = new Uint32Array(W * CLASSES);\n const tlState = index.tlState;\n const tlClass = index.tlClass;\n const tMono = index.tMono;\n const t0 = n === 0 ? 0 : (tMono[0] as number);\n const t1 = n === 0 ? 0 : (tMono[n - 1] as number);\n const byTime = axis === 'time';\n const span = t1 - t0;\n const hist = new Uint32Array(8);\n\n let i = 0;\n let carry = 0;\n for (let b = 0; b < W; b++) {\n start[b] = i;\n // The first event index that belongs to a later bucket.\n let end: number;\n if (b === W - 1) end = n;\n else if (!byTime) end = Math.min(n, Math.ceil(((b + 1) * n) / W));\n else if (span <= 0) end = n;\n else {\n const limit = t0 + ((b + 1) * span) / W;\n end = i;\n while (end < n && (tMono[end] as number) < limit) end++;\n }\n if (end <= i) {\n phase[b] = carry & 7;\n phaseCertainty[b] = (carry >> 3) & 3;\n paused[b] = (carry & 32) !== 0 ? 1 : 0;\n busy[b] = (carry & 64) !== 0 ? 1 : 0;\n continue;\n }\n hist.fill(0);\n let cert = 0;\n let bits = 0;\n const row = b * CLASSES;\n for (; i < end; i++) {\n const s = tlState[i] as number;\n const ph = s & 7;\n if (ph !== 0) {\n hist[ph] = (hist[ph] as number) + 1;\n const c = (s >> 3) & 3;\n if (c > cert) cert = c;\n }\n bits |= s;\n const cls = tlClass[i] as number;\n if (cls !== 0) counts[row + cls - 1] = (counts[row + cls - 1] as number) + 1;\n carry = s;\n }\n events[b] = end - (start[b] as number);\n let best = 0;\n let bestCount = 0;\n for (let ph = 1; ph < 8; ph++) {\n if ((hist[ph] as number) > bestCount) {\n best = ph;\n bestCount = hist[ph] as number;\n }\n }\n phase[b] = best;\n phaseCertainty[b] = best === 0 ? 0 : cert;\n paused[b] = (bits & 32) !== 0 ? 1 : 0;\n busy[b] = (bits & 64) !== 0 ? 1 : 0;\n }\n return {\n axis: byTime ? 'time' : 'index',\n width: W,\n version,\n length: n,\n from: byTime ? t0 : 0,\n to: byTime ? t1 : n,\n start,\n events,\n phase,\n phaseCertainty,\n paused,\n busy,\n counts,\n };\n}\n\nexport function buildMarkers(index: RunIndex, events: readonly NmEvent[], version: number): TimelineMarkers {\n const notes: NoteMarker[] = [];\n for (const i of index.notes) {\n const e = events[i] as NmEvent;\n if (e.k === 'note') notes.push({ index: i, t: e.t, level: e.level, text: e.text });\n }\n const outputIndex = new Uint32Array(index.output.length);\n const outputStream = new Uint8Array(index.output.length);\n for (let k = 0; k < index.output.length; k++) {\n const chunk = index.output[k] as (typeof index.output)[number];\n outputIndex[k] = chunk.index;\n outputStream[k] = chunk.stream === 'stderr' ? 1 : 0;\n }\n return {\n version,\n // Copies: the index updates its own markers when a pause ends.\n pauses: index.pauses.map((m): PauseMarker => ({ ...m })),\n notes,\n turnIndex: Uint32Array.from(index.turns),\n turnNumber: Uint32Array.from(index.turnNumbers),\n outputIndex,\n outputStream,\n };\n}\n\n/** The bucket that holds the event at `index`, clamped to the summary. Works for both axes. */\nexport function bucketOfIndex(summary: TimelineSummary, index: number): number {\n // The last bucket whose first event is at or before `index`.\n const start = summary.start;\n let lo = 0;\n let hi = summary.width;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((start[mid] as number) <= index) lo = mid + 1;\n else hi = mid;\n }\n return Math.max(0, lo - 1);\n}\n\n/** The bucket that holds time `t` in microseconds on a time-axis summary, clamped to the summary. */\nexport function bucketOfTime(summary: TimelineSummary, t: number): number {\n const span = summary.to - summary.from;\n if (!(span > 0)) return 0;\n const b = Math.floor(((t - summary.from) / span) * summary.width);\n return Math.max(0, Math.min(summary.width - 1, b));\n}\n\n/** The counts of one bucket as an object keyed by class. */\nexport function bucketCounts(summary: TimelineSummary, bucket: number): Record<TimelineClass, number> {\n const out = {} as Record<TimelineClass, number>;\n const row = Math.max(0, Math.min(summary.width - 1, Math.floor(bucket))) * CLASSES;\n for (let c = 0; c < CLASSES; c++) out[TIMELINE_CLASSES[c] as TimelineClass] = summary.counts[row + c] as number;\n return out;\n}\n","/**\n * Replay: the view state at any position of one run.\n *\n * How it is built\n * ---------------\n * Three things are kept:\n *\n * 1. The run index (run-index.ts): everything that only grows with the run,\n * stored once, tagged with event indexes.\n * 2. The frontier: the live state (reducer.ts) after all indexed events. New\n * events are applied to it as they arrive, so the tail of a live run - the\n * position the screen shows most of the time - never needs a jump.\n * 3. Keyframes: copies of the frontier taken on the way. To show another\n * position, the nearest keyframe at or before it is copied and the events\n * from there are applied again (the \"cursor\"). Stepping forward advances\n * the cursor by one event; stepping back restores and replays.\n *\n * Keyframe interval\n * -----------------\n * A jump costs one keyframe copy plus at most `interval` events. Applying an\n * event that is already indexed measured about 0.3 microseconds on a loaded\n * laptop (test/bench.ts: a random jump over a 100,000-event run took 0.09 ms\n * at the median and 0.19 ms at the 95th percentile, view not included). So\n * 512 events are at most about 0.15 ms, 0.6 ms under the 4x CPU throttle of\n * the brief: far inside one frame, which is what makes dragging the scrubber\n * and stepping backwards feel immediate. A keyframe of a normal program is\n * about a hundred slots, so 100,000 events need 195 keyframes and about\n * 0.6 MB (measured). Halving the interval would double that memory to save\n * time nobody can see; doubling it would save 0.3 MB and bring a backward\n * step on a slow phone close to a millisecond for no real gain. 512 is the\n * point where neither cost matters.\n *\n * A program with very long queues (ten thousand pending timers) makes every\n * keyframe large. The interval therefore grows with the size of the state:\n * the next keyframe is taken after max(interval, slots / 4) events. That\n * bounds keyframe memory to about 4 slots per event whatever the program\n * does, and keeps the copy and the replay of a jump in proportion.\n *\n * A late tail\n * -----------\n * When the store reports that events from index `from` changed, the index is\n * cut back to `from`, keyframes after `from` are dropped, the frontier is\n * rebuilt from the last keyframe that is left, and the new tail is applied.\n * The result is the same as if the events had arrived in that order to begin\n * with (the tests check this).\n */\n\nimport type { NmEvent } from '@nodejs-map/event-format';\nimport type { EventStore } from './store.ts';\nimport type {\n ItemView,\n LogEntry,\n OutputChunk,\n ReplayAnswer,\n ReplayQuery,\n StepKind,\n StoreChange,\n TimelineAxis,\n TimelineMarkers,\n TimelineSummary,\n ViewOptions,\n ViewState,\n} from './types.ts';\nimport { F_CALLBACK, F_OUTPUT, F_PAUSE, F_PHASE, F_STEP, F_TURN, RunIndex } from './run-index.ts';\nimport type { ItemRec } from './run-index.ts';\nimport { applyEvent, cloneLive, createLive, liveSize } from './reducer.ts';\nimport type { Live } from './reducer.ts';\nimport { DEFAULT_VIEW, buildView, itemView, itemsRange, logEntries, outputRange, resolveOptions } from './view.ts';\nimport type { ViewContext } from './view.ts';\nimport { buildMarkers, buildTimeline } from './timeline.ts';\n\n/** Events between keyframes; see the comment at the top of this file for the reasoning. */\nexport const DEFAULT_KEYFRAME_INTERVAL = 512;\n\n/** The most events one 'events' query returns. */\nconst MAX_EVENTS_PER_QUERY = 1000;\n/** The longest trigger chain why() follows. */\nconst MAX_CHAIN = 1000;\n\nexport interface ReplayOptions {\n /** Events between keyframes. Default DEFAULT_KEYFRAME_INTERVAL. */\n keyframeInterval?: number;\n /**\n * true (default): new events are indexed inside EventStore.apply.\n * false: they are indexed by pump(), in slices, so no single call is long\n * (opening a 100,000-event recording on the main thread).\n */\n eager?: boolean;\n /** Defaults for view(). */\n view?: ViewOptions;\n}\n\nexport interface ReplayStats {\n /** Events indexed. */\n ready: number;\n keyframes: number;\n /** Container slots held by all keyframes together (a slot is one reference, about 8 bytes, or one map entry, about 40). */\n keyframeSlots: number;\n keyframeInterval: number;\n}\n\nconst CERT_CODE: Record<string, number> = { observed: 1, inferred: 2, model: 3 };\n\nconst now: () => number = typeof performance !== 'undefined' && typeof performance.now === 'function' ? () => performance.now() : () => Date.now();\n\nfunction maskOf(kind: StepKind): number {\n switch (kind) {\n case 'step':\n return F_STEP;\n case 'callback':\n return F_CALLBACK;\n case 'phase':\n return F_PHASE;\n case 'turn':\n return F_TURN;\n case 'output':\n return F_OUTPUT;\n case 'pause':\n return F_PAUSE;\n default:\n return 0xff; // 'event': anything (see find)\n }\n}\n\n/** The view state at any position of one run. */\nexport class Replay {\n readonly store: EventStore;\n #index = new RunIndex();\n #ready = 0;\n #frontier: Live = createLive();\n #keyframes: Live[] = [];\n #keyframePos: number[] = [];\n #keyframeSlots = 0;\n #nextKeyframe: number;\n #interval: number;\n #eager: boolean;\n /** The position asked for. The position shown is min(target, ready). */\n #target = 0;\n #cursor: Live | null = null;\n #cursorPos = 0;\n #viewDefaults: Required<ViewOptions>;\n #listeners = new Set<(change: StoreChange) => void>();\n #unsubscribe: () => void;\n #timelines = new Map<string, TimelineSummary>();\n #markers: TimelineMarkers | null = null;\n #markersReady = -1;\n\n constructor(store: EventStore, options?: ReplayOptions) {\n this.store = store;\n const k = options?.keyframeInterval;\n this.#interval = typeof k === 'number' && k >= 1 ? Math.floor(k) : DEFAULT_KEYFRAME_INTERVAL;\n this.#nextKeyframe = this.#interval;\n this.#eager = options?.eager !== false;\n this.#viewDefaults = resolveOptions(DEFAULT_VIEW, options?.view);\n this.#unsubscribe = store.subscribe((change) => this.#onChange(change));\n if (this.#eager) this.#ingest(Infinity);\n }\n\n // ---- taking in events ---------------------------------------------------------\n\n #onChange(change: StoreChange): void {\n if (change.rejected === null) {\n if (change.replaced) this.#target = 0;\n if (change.from < this.#ready) this.#rollback(change.from);\n if (this.#target > change.length) this.#target = change.length;\n if (this.#eager) this.#ingest(Infinity);\n }\n for (const listener of [...this.#listeners]) listener(change);\n }\n\n /** Forget everything computed from events at `from` and above. */\n #rollback(from: number): void {\n this.#index.truncate(from);\n while (this.#keyframePos.length > 0 && (this.#keyframePos[this.#keyframePos.length - 1] as number) > from) {\n this.#keyframePos.pop();\n this.#keyframeSlots -= liveSize(this.#keyframes.pop() as Live);\n }\n const k = this.#keyframePos.length - 1;\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n const live = k >= 0 ? cloneLive(this.#keyframes[k] as Live) : createLive();\n this.#replay(live, base, from);\n this.#frontier = live;\n this.#ready = from;\n this.#nextKeyframe = base + (k >= 0 ? this.#gap(this.#keyframes[k] as Live) : this.#interval);\n if (this.#cursor !== null && this.#cursorPos > from) this.#cursor = null;\n }\n\n #gap(keyframe: Live): number {\n return Math.max(this.#interval, liveSize(keyframe) >> 2);\n }\n\n /** Apply the already indexed events [from, to) to `live`. */\n #replay(live: Live, from: number, to: number): void {\n const events = this.store.events;\n const index = this.#index;\n const flags = index.flags;\n for (let i = from; i < to; i++) applyEvent(live, events[i] as NmEvent, i, flags[i] as number, index, events);\n }\n\n /** Index events until the store is exhausted or the budget is spent. */\n #ingest(budgetMs: number): void {\n const events = this.store.events;\n const n = events.length;\n let i = this.#ready;\n if (i >= n) return;\n const index = this.#index;\n const live = this.#frontier;\n const deadline = budgetMs === Infinity ? Infinity : now() + budgetMs;\n while (i < n) {\n const e = events[i] as NmEvent;\n const flags = index.add(e, i);\n index.tlClass[i] = applyEvent(live, e, i, flags, index, events);\n let state = live.phase;\n if (state !== 0) state |= (CERT_CODE[(events[live.phaseIndex] as NmEvent).c] ?? 0) << 3;\n if (live.paused || live.gateStopped) state |= 32;\n if (live.stack.length > 0) state |= 64;\n index.tlState[i] = state;\n i++;\n if (i === this.#nextKeyframe) {\n const copy = cloneLive(live);\n this.#keyframes.push(copy);\n this.#keyframePos.push(i);\n this.#keyframeSlots += liveSize(copy);\n this.#nextKeyframe = i + this.#gap(copy);\n }\n if ((i & 255) === 0 && deadline !== Infinity && now() >= deadline) break;\n }\n this.#ready = i;\n }\n\n /** Events indexed so far; positions up to here can be shown. */\n get ready(): number {\n return this.#ready;\n }\n\n /**\n * Index more events, for at most `budgetMs` milliseconds (default 4).\n * Returns true when more remain. Only needed with `eager: false`.\n */\n pump(budgetMs = 4): boolean {\n this.#ingest(Math.max(0, budgetMs));\n return this.#ready < this.store.length;\n }\n\n // ---- position -------------------------------------------------------------------\n\n /** Events applied to the current view: 0 to `ready`. */\n get position(): number {\n return Math.min(this.#target, this.#ready);\n }\n\n /** Index of the last keyframe at or before `p`, or -1. */\n #keyframeBefore(p: number): number {\n const pos = this.#keyframePos;\n let lo = 0;\n let hi = pos.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((pos[mid] as number) <= p) lo = mid + 1;\n else hi = mid;\n }\n return lo - 1;\n }\n\n /** A fresh live state at position `p`. */\n #stateAt(p: number): Live {\n const k = this.#keyframeBefore(p);\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n const live = k >= 0 ? cloneLive(this.#keyframes[k] as Live) : createLive();\n this.#replay(live, base, p);\n return live;\n }\n\n /** The live state at the current position. Not to be changed by the caller. */\n #live(): Live {\n const p = this.position;\n if (p === this.#ready) return this.#frontier;\n const k = this.#keyframeBefore(p);\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n if (this.#cursor !== null && this.#cursorPos <= p && this.#cursorPos >= base) {\n // The cursor is at least as close as the keyframe: walk on from it.\n this.#replay(this.#cursor, this.#cursorPos, p);\n } else {\n this.#cursor = this.#stateAt(p);\n }\n this.#cursorPos = p;\n return this.#cursor;\n }\n\n /** Jump to a position (clamped to 0..length). Returns the position reached, which is lower while events are still being indexed. */\n seek(position: number): number {\n const p = Number.isFinite(position) ? Math.floor(position) : position > 0 ? this.store.length : 0;\n this.#target = Math.max(0, Math.min(this.store.length, p));\n return this.position;\n }\n\n /** Jump to time `t` (microseconds): the state after every event up to and including that time. */\n seekTime(t: number): number {\n return this.seek(this.positionAtTime(t));\n }\n\n /** The position that shows time `t`: the number of events whose time is `t` or earlier. */\n positionAtTime(t: number): number {\n const tMono = this.#index.tMono;\n let lo = 0;\n let hi = this.#ready;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((tMono[mid] as number) <= t) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n /**\n * Time at a position, microseconds: the time of the event applied last,\n * made non-decreasing (an event stamped earlier than its predecessor\n * counts as simultaneous with it). Position 0 has the time of the first\n * event.\n */\n timeAt(position: number): number {\n if (this.#ready === 0) return 0;\n const p = Math.max(1, Math.min(this.#ready, Math.floor(position)));\n return this.#index.tMono[p - 1] as number;\n }\n\n /**\n * The position step() would move to from `from` (default: the current\n * position), without moving. A stop is the position just after an event\n * of the kind. null: there is no such stop in that direction. Going back\n * with \"event\" or \"step\" from the first stop reaches position 0.\n */\n find(kind: StepKind, direction: 1 | -1, from?: number): number | null {\n const ready = this.#ready;\n const p = from === undefined ? this.position : Math.max(0, Math.min(ready, Math.floor(from)));\n if (kind === 'event') {\n const q = direction > 0 ? p + 1 : p - 1;\n return q < 0 || q > ready ? null : q;\n }\n const mask = maskOf(kind);\n if (direction > 0) {\n const i = this.#index.nextWith(mask, p);\n return i < 0 || i >= ready ? null : i + 1;\n }\n const i = this.#index.previousWith(mask, p - 2);\n if (i >= 0) return i + 1;\n return kind === 'step' && p > 0 ? 0 : null;\n }\n\n /** Move to the next or previous stop of a kind. Returns the new position, or null when there is none (the position is then unchanged). */\n step(kind: StepKind, direction: 1 | -1): number | null {\n const q = this.find(kind, direction);\n if (q === null) return null;\n this.#target = q;\n return q;\n }\n\n // ---- views ------------------------------------------------------------------------\n\n #context(): ViewContext {\n return { index: this.#index, events: this.store.events, length: this.store.length, ready: this.#ready, live: this.store.live, version: this.store.version };\n }\n\n /** The view at the current position. A new object on every call. */\n view(options?: ViewOptions): ViewState {\n return buildView(this.#context(), this.#live(), this.position, resolveOptions(this.#viewDefaults, options));\n }\n\n /** The view at another position, without moving. */\n viewAt(position: number, options?: ViewOptions): ViewState {\n const p = Math.max(0, Math.min(this.#ready, Math.floor(position)));\n const live = p === this.position ? this.#live() : this.#stateAt(p);\n return buildView(this.#context(), live, p, resolveOptions(this.#viewDefaults, options));\n }\n\n /** What the main thread is doing at the current position (cheap; the player uses it to word dead time). */\n doing(): 'main' | 'callback' | 'nothing' {\n const live = this.#live();\n if (live.stack.length > 0) return 'callback';\n return live.mainScript && live.startIndex >= 0 ? 'main' : 'nothing';\n }\n\n /** One item with its life up to the current position. null: not seen yet. */\n item(id: number): ItemView | null {\n const p = this.position;\n const rec = this.#index.items.get(id);\n if (rec === undefined || rec.firstIndex >= p) return null;\n return itemView(this.#context(), this.#live(), rec, p);\n }\n\n /**\n * \"Why did this run?\": the item, then the item during whose callback it\n * was created, and so on. The chain ends at an item whose trigger is the\n * main script (0 or 1) or is not known to this run.\n */\n why(id: number): ItemView[] {\n const p = this.position;\n const ctx = this.#context();\n const live = this.#live();\n const chain: ItemView[] = [];\n const seen = new Set<number>();\n let next = id;\n while (chain.length < MAX_CHAIN && !seen.has(next)) {\n seen.add(next);\n const rec: ItemRec | undefined = this.#index.items.get(next);\n if (rec === undefined || rec.firstIndex >= p) break;\n const v = itemView(ctx, live, rec, p);\n chain.push(v);\n if (v.created === null) break; // nothing is known about who made it\n next = v.trigger;\n }\n return chain;\n }\n\n /** Items seen up to the current position, in creation order. */\n items(from = 0, limit = Infinity): ItemView[] {\n const p = this.position;\n const total = this.#index.itemsBefore(p);\n return itemsRange(this.#context(), this.#live(), p, from, Math.min(limit, total));\n }\n\n /** How many items exist at the current position. */\n itemCount(): number {\n return this.#index.itemsBefore(this.position);\n }\n\n /** Output chunks by seq (`toSeq` excluded), up to the current position. */\n output(fromSeq: number, toSeq: number): OutputChunk[] {\n return outputRange(this.#context(), this.#live(), fromSeq, toSeq);\n }\n\n /** Events by index (`to` excluded), whatever the position. */\n events(from: number, to: number): LogEntry[] {\n return logEntries(this.#context(), from, to);\n }\n\n /** The run cut into `width` buckets. Cached until the run or the arguments change. */\n timeline(width: number, axis: TimelineAxis = 'index'): TimelineSummary {\n const key = axis + ':' + width;\n const cached = this.#timelines.get(key);\n const version = this.store.version;\n if (cached !== undefined && cached.version === version && cached.length === this.#ready) return cached;\n const summary = buildTimeline(this.#index, this.#ready, width, axis, version);\n // Keep the map small: widths change on resize and old ones are not coming back.\n if (this.#timelines.size >= 4) this.#timelines.clear();\n this.#timelines.set(key, summary);\n return summary;\n }\n\n /** Pauses, notes, loop turns and output positions. Cached until the run changes. */\n markers(): TimelineMarkers {\n const version = this.store.version;\n const m = this.#markers;\n if (m !== null && m.version === version && this.#markersReady === this.#ready) return m;\n this.#markers = buildMarkers(this.#index, this.store.events, version);\n this.#markersReady = this.#ready;\n return this.#markers;\n }\n\n /** Answer a ReplayQuery (the worker protocol uses this). */\n query(q: ReplayQuery): ReplayAnswer {\n switch (q.what) {\n case 'item':\n return { what: 'item', item: this.item(q.id) };\n case 'why':\n return { what: 'why', chain: this.why(q.id) };\n case 'items':\n return { what: 'items', items: this.items(q.from, q.limit), total: this.itemCount() };\n case 'output':\n return { what: 'output', chunks: this.output(q.from, q.to) };\n case 'events': {\n const from = Math.max(0, Math.floor(q.from));\n return { what: 'events', entries: this.events(from, Math.min(q.to, from + MAX_EVENTS_PER_QUERY)) };\n }\n case 'viewAt':\n return { what: 'viewAt', view: this.viewAt(q.position) };\n default:\n throw new TypeError('unknown query');\n }\n }\n\n /** Numbers about the replay itself, for a developer overlay and the benchmarks. */\n stats(): ReplayStats {\n return { ready: this.#ready, keyframes: this.#keyframes.length, keyframeSlots: this.#keyframeSlots, keyframeInterval: this.#interval };\n }\n\n /** Calls `listener` after the replay has taken in a store change. Returns a function that stops it. */\n subscribe(listener: (change: StoreChange) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n /** Stop listening to the store. */\n dispose(): void {\n this.#unsubscribe();\n this.#listeners.clear();\n }\n}\n","/**\n * The player: play, pause, speed, follow, over a Replay.\n *\n * It owns no timer. The caller supplies the clock by calling tick(now), from\n * requestAnimationFrame, from a worker timer or from a test.\n *\n * The default pace\n * ----------------\n * A real program finishes in milliseconds: fifty milliseconds can hold a few\n * hundred events. Played as a fraction of real time there is no good factor:\n * slow enough to see a burst of microtasks (microseconds apart) makes a\n * 100 ms timer wait take minutes, and the other way round. So the default\n * pace ignores real time and gives every meaningful step the same time on\n * screen: DEFAULT_STEPS_PER_SECOND steps per second at 1x.\n *\n * Why 5: one step has to leave room for one short animation (an item moving\n * from a queue to the stack, about 150 ms) and for reading one label, and a\n * typical small lesson (a timer, an immediate, a nextTick, a promise and a\n * file read: about 40 to 80 meaningful steps) should play in 10 to 15\n * seconds, like a short clip, without anyone touching the speed. With the\n * speed range of 0.05x to 20x this spans one step every 4 seconds (talking\n * through it in class) to 100 steps a second (skimming a 3,000-step run in\n * half a minute; beyond that the scrubber is the tool). The number is a\n * judgement, not a measurement: it has not been tried on learners yet.\n *\n * Time is not thrown away. A gap between two events that is longer than\n * `deadTimeUs` of program time (default 2 ms: far longer than any pause\n * between events of one callback, shorter than any timer or file read worth\n * showing) plays as one short extra pause and is reported in\n * PlayerState.deadTime, so the UI can say \"nothing happened for 98 ms\".\n *\n * Two other paces exist for other needs: \"time\" plays program time in slow\n * motion (1x = 100 times slower than real, so 50 ms take 5 s), for seeing\n * rhythm in a long run; \"tick\" applies exactly one event per tick() call,\n * for stepping through a very fast stretch frame by frame.\n */\n\nimport type { Replay } from './replay.ts';\nimport type { DeadTime, Pace, PlayerCommand, PlayerOptions, PlayerState, PlayerTick, StepKind } from './types.ts';\n\nexport const SPEED_MIN = 0.05;\nexport const SPEED_MAX = 20;\n/** \"steps\" pace at 1x. See the comment at the top of this file. */\nexport const DEFAULT_STEPS_PER_SECOND = 5;\n/** \"time\" pace at 1x: 0.01 s of program time per second, that is 100 times slower than real. */\nexport const DEFAULT_TIME_SCALE = 0.01;\n/** A gap longer than this, in microseconds of program time, is played as a short pause. */\nexport const DEFAULT_DEAD_TIME_US = 2000;\n/** How long that pause is at 1x, in milliseconds. */\nexport const DEFAULT_DEAD_TIME_PAUSE_MS = 600;\n\n/** The most steps one tick applies in \"steps\" pace; a guard against a huge stepsPerSecond, far above anything a frame needs. */\nconst MAX_STEPS_PER_TICK = 2000;\n\nconst clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);\n\n/**\n * Plays a Replay. It has no timer of its own: call tick(now) from\n * requestAnimationFrame or a worker timer.\n *\n * Follow is on by default: events that arrive through EventStore.apply are\n * a live run and the view goes to its tail, also when the whole run arrives\n * and ends before the first tick. A recording is not a live run: put it\n * into the store with EventStore.load and it starts at the beginning.\n */\nexport class Player {\n readonly replay: Replay;\n #playing = false;\n #speed = 1;\n #pace: Pace = 'steps';\n #stepsPerSecond = DEFAULT_STEPS_PER_SECOND;\n #timeScale = DEFAULT_TIME_SCALE;\n #deadTimeUs = DEFAULT_DEAD_TIME_US;\n #deadTimePauseMs = DEFAULT_DEAD_TIME_PAUSE_MS;\n #follow = true;\n #maxTickMs = 250;\n /** Clock time of the previous tick while playing; null right after play() or a jump. */\n #last: number | null = null;\n /** Playback time not yet spent, in milliseconds at 1x. */\n #credit = 0;\n #deadTime: DeadTime | null = null;\n #waiting = false;\n /** True while the view is being held on the tail of a run that is live, or was live a moment ago and has not been shown to its end. */\n #atTail = false;\n #previous: PlayerState | null = null;\n\n #unsubscribe: () => void;\n\n constructor(replay: Replay, options?: PlayerOptions) {\n this.replay = replay;\n if (options !== undefined) this.setOptions(options);\n // A short program can start and end between two ticks. A view that\n // follows must still end up on its last event, so following is armed the\n // moment live events arrive, not at the next tick. A run that is loaded\n // whole (a recording) was never live and starts at the beginning.\n this.#unsubscribe = replay.subscribe((change) => {\n if (change.replaced) this.#atTail = false;\n if (change.status === 'live' && this.#follow) this.#atTail = true;\n });\n }\n\n /** Stop listening to the replay. */\n dispose(): void {\n this.#unsubscribe();\n }\n\n get state(): PlayerState {\n const replay = this.replay;\n const position = replay.position;\n const length = replay.ready;\n const live = replay.store.live;\n return {\n playing: this.#playing,\n speed: this.#speed,\n pace: this.#pace,\n follow: this.#follow,\n following: this.#follow && live && position === length,\n position,\n length,\n live,\n atEnd: !live && length > 0 && position === length && replay.store.length === length,\n waiting: this.#waiting,\n deadTime: this.#deadTime,\n t: replay.timeAt(position),\n };\n }\n\n /** Start playing. At the end of a finished run, playing starts again from the beginning. */\n play(): void {\n const replay = this.replay;\n if (!replay.store.live && replay.position >= replay.store.length && replay.store.length > 0) replay.seek(0);\n this.#playing = true;\n this.#resetClock();\n }\n\n /** Stop playing. Also leaves the live tail: a paused view does not move. */\n pause(): void {\n this.#playing = false;\n this.#follow = false;\n this.#atTail = false;\n this.#resetClock();\n }\n\n toggle(): void {\n if (this.#playing) this.pause();\n else this.play();\n }\n\n /** Clamped to SPEED_MIN..SPEED_MAX. */\n setSpeed(speed: number): void {\n if (Number.isFinite(speed)) this.#speed = clamp(speed, SPEED_MIN, SPEED_MAX);\n }\n\n setPace(pace: Pace): void {\n if (pace !== 'steps' && pace !== 'time' && pace !== 'tick') return;\n this.#pace = pace;\n this.#resetClock();\n }\n\n /** Stick to the tail while the run is live. Turning it on jumps to the tail at the next tick. */\n setFollow(on: boolean): void {\n this.#follow = on === true;\n this.#atTail = this.#follow && this.replay.store.live;\n }\n\n setOptions(o: PlayerOptions): void {\n if (o.speed !== undefined) this.setSpeed(o.speed);\n if (o.pace !== undefined) this.setPace(o.pace);\n if (typeof o.stepsPerSecond === 'number' && o.stepsPerSecond > 0) this.#stepsPerSecond = o.stepsPerSecond;\n if (typeof o.timeScale === 'number' && o.timeScale > 0) this.#timeScale = o.timeScale;\n if (typeof o.deadTimeUs === 'number' && o.deadTimeUs >= 0) this.#deadTimeUs = o.deadTimeUs;\n if (typeof o.deadTimePauseMs === 'number' && o.deadTimePauseMs >= 0) this.#deadTimePauseMs = o.deadTimePauseMs;\n if (o.follow !== undefined) this.setFollow(o.follow);\n if (typeof o.maxTickMs === 'number' && o.maxTickMs > 0) this.#maxTickMs = o.maxTickMs;\n }\n\n /** Jump. Follow stays on only when the jump lands on the tail of a live run. */\n seek(position: number): void {\n const replay = this.replay;\n const reached = replay.seek(position);\n if (!(replay.store.live && reached >= replay.ready)) {\n this.#follow = false;\n this.#atTail = false;\n }\n this.#resetClock();\n }\n\n /** Jump to a time in microseconds. */\n seekTime(t: number): void {\n this.seek(this.replay.positionAtTime(t));\n }\n\n /** Step and pause. Returns false when there is no such stop. */\n step(kind: StepKind, direction: 1 | -1): boolean {\n this.#playing = false;\n this.#follow = false;\n this.#atTail = false;\n this.#resetClock();\n return this.replay.step(kind, direction) !== null;\n }\n\n /** The same controls as data (the worker protocol uses this). Unknown commands are ignored. */\n command(cmd: PlayerCommand): void {\n switch (cmd.do) {\n case 'play':\n return this.play();\n case 'pause':\n return this.pause();\n case 'toggle':\n return this.toggle();\n case 'speed':\n return this.setSpeed(cmd.speed);\n case 'pace':\n return this.setPace(cmd.pace);\n case 'follow':\n return this.setFollow(cmd.on);\n case 'seek':\n return this.seek(cmd.position);\n case 'seekTime':\n return this.seekTime(cmd.t);\n case 'step':\n this.step(cmd.kind, cmd.direction);\n return;\n case 'options':\n return this.setOptions(cmd.options);\n default:\n return;\n }\n }\n\n #resetClock(): void {\n this.#last = null;\n this.#credit = 0;\n this.#deadTime = null;\n this.#waiting = false;\n }\n\n /**\n * Advance playback to clock time `nowMs` (any steady millisecond clock).\n * Call it once per frame whether playing or not: it also keeps a\n * following view on the tail.\n */\n tick(nowMs: number): PlayerTick {\n const replay = this.replay;\n const before = replay.position;\n const ready = replay.ready;\n const live = replay.store.live;\n\n if (this.#follow && (live || this.#atTail)) {\n // Live-follow: the newest state, whatever the pace. The run can end\n // between two ticks, with its last events arriving just before; the\n // view that was following must still reach them, so following goes on\n // until the end of the finished list has been shown once.\n if (before !== ready) replay.seek(ready);\n this.#atTail = live || replay.store.length > ready;\n this.#last = nowMs;\n this.#credit = 0;\n this.#deadTime = null;\n this.#waiting = false;\n } else if (this.#playing) {\n const dt = this.#last === null ? 0 : clamp(nowMs - this.#last, 0, this.#maxTickMs);\n this.#last = nowMs;\n if (this.#pace === 'tick') this.#tickOne(ready);\n else if (this.#pace === 'time') this.#tickTime(dt, ready);\n else this.#tickSteps(dt, ready);\n const position = replay.position;\n if (position >= ready) {\n this.#deadTime = null;\n this.#credit = 0;\n if (live || replay.store.length > ready) {\n // More events can come: wait at the tail.\n this.#waiting = true;\n } else {\n this.#waiting = false;\n this.#playing = false;\n this.#last = null;\n }\n } else this.#waiting = false;\n }\n\n const state = this.state;\n const prev = this.#previous;\n const changed =\n prev === null ||\n prev.position !== state.position ||\n prev.playing !== state.playing ||\n prev.speed !== state.speed ||\n prev.pace !== state.pace ||\n prev.follow !== state.follow ||\n prev.following !== state.following ||\n prev.length !== state.length ||\n prev.live !== state.live ||\n prev.atEnd !== state.atEnd ||\n prev.waiting !== state.waiting ||\n (prev.deadTime === null) !== (state.deadTime === null) ||\n (prev.deadTime !== null && state.deadTime !== null && prev.deadTime.progress !== state.deadTime.progress);\n this.#previous = state;\n return { moved: state.position !== before, changed, state };\n }\n\n #tickOne(ready: number): void {\n const p = this.replay.position;\n if (p < ready) this.replay.seek(p + 1);\n }\n\n /** The gap in program time between positions `a` and `b`, when it counts as dead time; otherwise 0. */\n #deadGap(a: number, b: number): number {\n if (this.#deadTimeUs <= 0 || a <= 0) return 0;\n const gap = this.replay.timeAt(b) - this.replay.timeAt(a);\n return gap > this.#deadTimeUs ? gap : 0;\n }\n\n #report(gapUs: number, from: number, to: number, progress: number): void {\n const p = clamp(progress, 0, 1);\n const old = this.#deadTime;\n if (old !== null && old.afterIndex === from - 1 && old.beforeIndex === to - 1) {\n if (old.progress !== p) this.#deadTime = { ...old, progress: p };\n return;\n }\n this.#deadTime = { ms: gapUs / 1000, afterIndex: from - 1, beforeIndex: to - 1, during: this.replay.doing(), progress: p };\n }\n\n /**\n * \"steps\" pace. From position p the next stop is the next meaningful\n * event. The step on screen is held for one step time; if dead time\n * follows it, the pause plays next; then the stop is applied.\n */\n #tickSteps(dt: number, ready: number): void {\n const replay = this.replay;\n const stepMs = 1000 / this.#stepsPerSecond;\n this.#credit += dt * this.#speed;\n let p = replay.position;\n for (let n = 0; n < MAX_STEPS_PER_TICK && p < ready; n++) {\n let next = replay.find('step', 1, p);\n if (next === null) {\n // Only signals are left. On a finished run they are applied with no wait; on a live run they wait for their step.\n if (replay.store.live || replay.store.length > ready) {\n next = ready;\n } else {\n p = ready;\n break;\n }\n }\n const gap = this.#deadGap(p, next);\n const pauseMs = gap > 0 ? this.#deadTimePauseMs : 0;\n const hold = p === 0 ? 0 : stepMs; // nothing is on screen yet at position 0\n const cost = hold + pauseMs;\n if (this.#credit < cost) {\n if (gap > 0 && this.#credit >= hold) {\n if (p !== replay.position) replay.seek(p); // the report describes the state during the gap\n this.#report(gap, p, next, pauseMs === 0 ? 1 : (this.#credit - hold) / pauseMs);\n } else this.#deadTime = null;\n break;\n }\n this.#credit -= cost;\n this.#deadTime = null;\n p = next;\n }\n if (p !== replay.position) replay.seek(p);\n }\n\n /** \"time\" pace: program time, slowed by timeScale; dead gaps play as the short pause. */\n #tickTime(dt: number, ready: number): void {\n const replay = this.replay;\n this.#credit += dt * this.#speed;\n const usToMs = 1 / (1000 * this.#timeScale);\n let p = replay.position;\n this.#deadTime = null;\n while (p < ready) {\n const gapUs = p === 0 ? 0 : replay.timeAt(p + 1) - replay.timeAt(p);\n const dead = this.#deadTimeUs > 0 && gapUs > this.#deadTimeUs;\n // A dead gap never plays longer than it would in plain slow motion.\n const cost = dead ? Math.min(this.#deadTimePauseMs, gapUs * usToMs) : gapUs * usToMs;\n if (this.#credit < cost) {\n if (dead) {\n if (p !== replay.position) replay.seek(p);\n this.#report(gapUs, p, p + 1, cost === 0 ? 1 : this.#credit / cost);\n }\n break;\n }\n this.#credit -= cost;\n p++;\n }\n if (p !== replay.position) replay.seek(p);\n }\n}\n","/**\n * Recording files and share links.\n *\n * Safety: a recording or a link is untrusted input (anyone can send one).\n * Everything here treats it as data only. Bytes are unpacked with the\n * platform's own gzip (DecompressionStream) under a size cap, decoded as\n * UTF-8, and handed to the event-format decoder, which uses JSON.parse and\n * validates every header field and every event. Nothing is evaluated,\n * imported, fetched or run; source text carried in a recording stays text.\n *\n * Uses only globals that browsers, Web Workers and Node 26 all have:\n * CompressionStream, DecompressionStream, TextEncoder, TextDecoder.\n */\n\nimport { RecordingError, decodeRecording, encodeRecording } from '@nodejs-map/event-format';\nimport type { Recording } from '@nodejs-map/event-format';\nimport type { OpenOptions, SaveOptions, ShareOptions, ShareResult } from './types.ts';\n\n/**\n * The longest fragment recordingToFragment will produce, in characters.\n *\n * A link is only useful if it survives being pasted. The fragment never\n * reaches a server, so server limits do not matter; what matters is where\n * people paste links and what browsers accept. Figures as documented by the\n * vendors, from memory, not re-checked while writing this:\n *\n * browsers Chrome and Edge accept URLs up to 2 MB; Firefox about 1 MB;\n * Safari has handled tens of thousands of characters for years\n * chat apps Slack 40,000 characters per message; WhatsApp 65,536;\n * Microsoft Teams about 28 KB; Telegram 4,096; Discord 2,000\n *\n * 24,000 stays under Slack, WhatsApp and Teams with room for the page URL\n * and a sentence around it, and far under every browser. It holds roughly\n * 18 KB of gzip, which is a run of one to three thousand events: every\n * lesson-sized program. Anything longer is better as a file anyway: nobody\n * can read, check or trust a link of a hundred thousand characters.\n *\n * Telegram and Discord cut a message well below any limit that would be\n * useful here, so they get a flag instead of a limit: ShareResult.fitsEverywhere\n * is true only up to SHARE_LINK_SAFE_CHARS, and the UI can offer the file\n * for those places.\n */\nexport const SHARE_LINK_MAX_CHARS = 24_000;\n\n/** At or below this many characters a link also fits the tightest message limits (Discord: 2,000). */\nexport const SHARE_LINK_SAFE_CHARS = 2_000;\n\n/**\n * Refuse a recording that unpacks to more than this many bytes. A gzip file\n * of a few kilobytes can unpack to gigabytes; the cap is checked while\n * unpacking, so such a file costs at most this much memory. 256 MB is about\n * ten times the largest recording we expect (a million events).\n */\nexport const MAX_RECORDING_BYTES = 256 * 1024 * 1024;\n\n/** The same cap for links, which are small by construction. */\nconst MAX_FRAGMENT_BYTES = 32 * 1024 * 1024;\n/** Refuse to even look at a fragment longer than this (Chrome's URL limit). */\nconst MAX_FRAGMENT_CHARS = 2 * 1024 * 1024;\n\n/**\n * A fragment is `rec=1.<data>`: the key \"rec\", the link format version \"1\"\n * (gzip of the recording text, then base64url without padding), a dot, the\n * data. A key=value form lets the app keep other state in the fragment\n * next to it, separated by \"&\".\n */\nexport const FRAGMENT_PREFIX = 'rec=1.';\n\n// ---- bytes ----------------------------------------------------------------------\n\nfunction toBytes(input: ArrayBuffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array ? input : new Uint8Array(input);\n}\n\n/** Push `bytes` through a compression or decompression stream and collect the result, at most `maxBytes`. */\nasync function pipe(stream: { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes: Uint8Array, maxBytes: number, tooBig: string): Promise<Uint8Array> {\n const writer = stream.writable.getWriter();\n // Writing and reading must go on at the same time (the stream applies\n // back-pressure). Failures of the write side surface on the read side\n // too; these handlers only keep them from being reported twice.\n writer.write(bytes).catch(() => {});\n writer.close().catch(() => {});\n const reader = stream.readable.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n reader.cancel().catch(() => {});\n throw new RecordingError(tooBig);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nfunction gzip(bytes: Uint8Array): Promise<Uint8Array> {\n return pipe(new CompressionStream('gzip') as unknown as { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes, Infinity, '');\n}\n\nasync function gunzip(bytes: Uint8Array, maxBytes: number): Promise<Uint8Array> {\n const tooBig = `the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB when unpacked`;\n try {\n return await pipe(new DecompressionStream('gzip') as unknown as { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes, maxBytes, tooBig);\n } catch (error) {\n if (error instanceof RecordingError) throw error;\n throw new RecordingError('not a valid gzip file');\n }\n}\n\nfunction isGzip(bytes: Uint8Array): boolean {\n return bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b;\n}\n\nfunction utf8(bytes: Uint8Array): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new RecordingError('not a text file (invalid UTF-8)');\n }\n}\n\nfunction parse(text: string): Recording {\n let recording: Recording;\n try {\n recording = decodeRecording(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n } catch (error) {\n if (error instanceof RecordingError) throw error;\n // The decoder is meant to throw RecordingError only; anything else is still just a bad file.\n throw new RecordingError('not a nodejs-map recording');\n }\n if (recording === null || typeof recording !== 'object' || recording.header === undefined || recording.header === null || !Array.isArray(recording.events)) {\n throw new RecordingError('not a nodejs-map recording');\n }\n return recording;\n}\n\n// ---- base64url ------------------------------------------------------------------\n\nconst B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst B64_VALUE = new Int8Array(128).fill(-1);\nfor (let i = 0; i < 64; i++) B64_VALUE[B64.charCodeAt(i)] = i;\n\nfunction toBase64Url(bytes: Uint8Array): string {\n const parts: string[] = [];\n let piece = '';\n const n = bytes.length;\n for (let i = 0; i < n; i += 3) {\n const a = bytes[i] as number;\n const b = i + 1 < n ? (bytes[i + 1] as number) : 0;\n const c = i + 2 < n ? (bytes[i + 2] as number) : 0;\n piece += B64[a >> 2] as string;\n piece += B64[((a & 3) << 4) | (b >> 4)] as string;\n if (i + 1 < n) piece += B64[((b & 15) << 2) | (c >> 6)] as string;\n if (i + 2 < n) piece += B64[c & 63] as string;\n if (piece.length >= 8192) {\n parts.push(piece);\n piece = '';\n }\n }\n parts.push(piece);\n return parts.join('');\n}\n\nfunction fromBase64Url(text: string): Uint8Array {\n const n = text.length;\n if (n % 4 === 1) throw new RecordingError('the link is damaged (wrong length)');\n const out = new Uint8Array(Math.floor((n * 3) / 4));\n let o = 0;\n for (let i = 0; i < n; i += 4) {\n const v = [0, 0, 0, 0];\n for (let k = 0; k < 4; k++) {\n if (i + k >= n) break;\n const code = text.charCodeAt(i + k);\n const value = code < 128 ? (B64_VALUE[code] as number) : -1;\n if (value < 0) throw new RecordingError('the link is damaged (unexpected character)');\n v[k] = value;\n }\n const [a, b, c, d] = v as [number, number, number, number];\n out[o++] = (a << 2) | (b >> 4);\n if (i + 2 < n) out[o++] = ((b & 15) << 4) | (c >> 2);\n if (i + 3 < n) out[o++] = ((c & 3) << 6) | d;\n }\n return out;\n}\n\n// ---- public -----------------------------------------------------------------------\n\n/**\n * Parse a recording from text, or from bytes that are UTF-8 text or gzip\n * (told apart by the gzip signature). Rejects with RecordingError for\n * anything that is not a valid recording. Nothing is executed.\n */\nexport async function openRecording(input: string | ArrayBuffer | Uint8Array, options?: OpenOptions): Promise<Recording> {\n const maxBytes = options?.maxBytes !== undefined && options.maxBytes > 0 ? options.maxBytes : MAX_RECORDING_BYTES;\n if (typeof input === 'string') {\n if (input.length > maxBytes) throw new RecordingError(`the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB`);\n return parse(input);\n }\n if (!(input instanceof Uint8Array) && !(input instanceof ArrayBuffer)) throw new RecordingError('not a recording: expected text or bytes');\n let bytes = toBytes(input);\n if (isGzip(bytes)) bytes = await gunzip(bytes, maxBytes);\n else if (bytes.byteLength > maxBytes) throw new RecordingError(`the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB`);\n return parse(utf8(bytes));\n}\n\n/** Encode a recording as file bytes: the UTF-8 text of the event-format codec, or gzip of it. */\nexport async function saveRecording(recording: Recording, options?: SaveOptions): Promise<Uint8Array> {\n const bytes = new TextEncoder().encode(encodeRecording(recording));\n return options?.gzip === true ? gzip(bytes) : bytes;\n}\n\n/**\n * Encode a recording for the URL fragment (gzip, then base64url). When the\n * result would be longer than the limit, nothing is produced and the result\n * says so: share the file instead.\n */\nexport async function recordingToFragment(recording: Recording, options?: ShareOptions): Promise<ShareResult> {\n const limit = options?.maxChars !== undefined && options.maxChars > 0 ? Math.floor(options.maxChars) : SHARE_LINK_MAX_CHARS;\n const packed = await gzip(new TextEncoder().encode(encodeRecording(recording)));\n const length = FRAGMENT_PREFIX.length + Math.ceil((packed.byteLength * 4) / 3);\n if (length > limit) {\n return {\n ok: false,\n reason: 'too-big',\n length,\n limit,\n message: `This recording is too big to share as a link (${length.toLocaleString('en-US')} characters; links work up to ${limit.toLocaleString('en-US')}). Save it and share the file instead.`,\n };\n }\n const fragment = FRAGMENT_PREFIX + toBase64Url(packed);\n return { ok: true, fragment, length: fragment.length, fitsEverywhere: fragment.length <= SHARE_LINK_SAFE_CHARS };\n}\n\n/**\n * Parse a fragment made by recordingToFragment. Accepts it with or without\n * the leading \"#\", alone or among other \"&\"-separated parts. Rejects with\n * RecordingError. Nothing is executed.\n */\nexport async function recordingFromFragment(fragment: string, options?: OpenOptions): Promise<Recording> {\n if (typeof fragment !== 'string') throw new RecordingError('not a recording link');\n if (fragment.length > MAX_FRAGMENT_CHARS) throw new RecordingError('the link is too long to be a recording link');\n const body = fragment.startsWith('#') ? fragment.slice(1) : fragment;\n let value: string | undefined;\n for (const part of body.split('&')) {\n if (part.startsWith('rec=')) {\n value = part.slice(4);\n break;\n }\n }\n if (value === undefined) throw new RecordingError('this link does not contain a recording');\n const dot = value.indexOf('.');\n if (dot < 0 || value.slice(0, dot) !== '1') throw new RecordingError('this link was made by a newer version of nodejs-map');\n const packed = fromBase64Url(value.slice(dot + 1));\n if (!isGzip(packed)) throw new RecordingError('the link is damaged');\n const maxBytes = options?.maxBytes !== undefined && options.maxBytes > 0 ? Math.min(options.maxBytes, MAX_FRAGMENT_BYTES) : MAX_FRAGMENT_BYTES;\n return parse(utf8(await gunzip(packed, maxBytes)));\n}\n","/**\n * View patches: post only what changed.\n *\n * A full view is a few to a few dozen kilobytes, and most of it is the same\n * from one step to the next (the node info, the thread lanes, the queues\n * nothing touched, the older output chunks and log entries). A patch carries\n * the top-level parts of the view that differ from the view before it, and\n * for the two append-mostly lists (output chunks, log entries) only the new\n * entries.\n *\n * applyViewPatch rebuilds the full view on the receiving side. The parts\n * that did not change are the very same objects as in the view before, so a\n * UI that compares by identity can skip every panel whose part is untouched;\n * that saves more main-thread time than the smaller message does.\n *\n * Both functions work on plain data and are pure.\n */\n\nimport type { QueueName } from '@nodejs-map/event-format';\nimport type { ListPatch, LogEntry, OutputChunk, QueueView, ViewPatch, ViewState } from './types.ts';\n\nconst QUEUES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n\n/** The parts of a view that are replaced whole when they differ. */\nconst PARTS = ['run', 'main', 'loop', 'items', 'timers', 'pool', 'debug', 'notes', 'focus', 'problems'] as const;\n/** The plain values at the top of a view. */\nconst SCALARS = ['position', 'length', 'ready', 'live', 'version', 't', 'endT'] as const;\n\n/** Deep equality of plain data (objects, arrays, primitives, null). */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!same(a[i], b[i])) return false;\n return true;\n }\n if (Array.isArray(b)) return false;\n const ka = Object.keys(a);\n if (ka.length !== Object.keys(b).length) return false;\n for (const k of ka) if (!same((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n return true;\n}\n\n/**\n * What of an ordered list (entries numbered by `key`, never changing while\n * the run is unchanged) can stay, and what has to be sent.\n */\nfunction listPatch<T>(before: readonly T[], after: readonly T[], key: (entry: T) => number, comparable: boolean): ListPatch<T> | null {\n if (!comparable || before.length === 0 || after.length === 0) {\n return before.length === 0 && after.length === 0 ? null : { from: 0, to: 0, prepend: [], append: after.slice() };\n }\n // Both lists are consecutive runs of numbers. Keep the overlap; send what\n // comes before it (a step back) and what comes after it (a step forward).\n const a0 = key(before[0] as T);\n const a1 = key(before[before.length - 1] as T);\n const b0 = key(after[0] as T);\n const b1 = key(after[after.length - 1] as T);\n if (a0 === b0 && a1 === b1) return null;\n const from = Math.max(a0, b0);\n const to = Math.min(a1, b1) + 1;\n if (from >= to) return { from: 0, to: 0, prepend: [], append: after.slice() }; // nothing in common\n const prepend: T[] = [];\n const append: T[] = [];\n for (const entry of after) {\n const k = key(entry);\n if (k < from) prepend.push(entry);\n else if (k >= to) append.push(entry);\n }\n return { from, to, prepend, append };\n}\n\nfunction listApply<T>(before: readonly T[], patch: ListPatch<T> | null, key: (entry: T) => number): T[] {\n if (patch === null) return before as T[];\n const out: T[] = patch.prepend.slice();\n for (const entry of before) {\n const k = key(entry);\n if (k >= patch.from && k < patch.to) out.push(entry);\n }\n for (const entry of patch.append) out.push(entry);\n return out;\n}\n\nconst chunkKey = (c: OutputChunk): number => c.seq;\nconst logKey = (l: LogEntry): number => l.index;\n\n/**\n * The patch that turns `previous` into `next`. With `previous` null the\n * patch is a full one: it carries everything and applies to nothing.\n */\nexport function diffView(previous: ViewState | null, next: ViewState): ViewPatch {\n const set: Record<string, unknown> = {};\n const queues: Partial<Record<QueueName, QueueView>> = {};\n if (previous === null) {\n for (const k of SCALARS) set[k] = next[k];\n for (const k of PARTS) set[k] = next[k];\n for (const q of QUEUES) queues[q] = next.queues[q];\n return {\n full: true,\n set: set as ViewPatch['set'],\n queues,\n output: { total: next.output.total, chars: next.output.chars, from: 0, to: 0, prepend: [], append: next.output.chunks.slice() },\n log: { from: 0, to: 0, prepend: [], append: next.log.slice() },\n };\n }\n for (const k of SCALARS) if (previous[k] !== next[k]) set[k] = next[k];\n for (const k of PARTS) if (!same(previous[k], next[k])) set[k] = next[k];\n for (const q of QUEUES) if (!same(previous.queues[q], next.queues[q])) queues[q] = next.queues[q];\n // Chunk and log numbers mean the same thing only while the event list is unchanged.\n const comparable = previous.version === next.version;\n const chunks = listPatch(previous.output.chunks, next.output.chunks, chunkKey, comparable);\n const output = chunks === null && previous.output.total === next.output.total && previous.output.chars === next.output.chars ? null : { total: next.output.total, chars: next.output.chars, ...(chunks ?? { from: 0, to: Number.MAX_SAFE_INTEGER, prepend: [], append: [] }) };\n return { full: false, set: set as ViewPatch['set'], queues, output, log: listPatch(previous.log, next.log, logKey, comparable) };\n}\n\n/**\n * The view that `patch` describes, given the view before it (null for a\n * full patch). Parts the patch does not mention are the same objects as in\n * `previous`. Throws when a patch that is not full is applied to nothing:\n * ask the host for a full one (`configure` with `views: 'patch'` again).\n */\nexport function applyViewPatch(previous: ViewState | null, patch: ViewPatch): ViewState {\n if (previous === null) {\n if (!patch.full) throw new Error('a view patch needs the view before it');\n const s = patch.set as ViewState;\n return {\n ...s,\n queues: patch.queues as Record<QueueName, QueueView>,\n output: { total: patch.output?.total ?? 0, chars: patch.output?.chars ?? 0, chunks: patch.output?.append ?? [] },\n log: patch.log?.append ?? [],\n };\n }\n let queues = previous.queues;\n for (const q of QUEUES) {\n const changed = patch.queues[q];\n if (changed !== undefined) {\n if (queues === previous.queues) queues = { ...previous.queues };\n queues[q] = changed;\n }\n }\n const o = patch.output;\n return {\n ...previous,\n ...patch.set,\n queues,\n output: o === null ? previous.output : { total: o.total, chars: o.chars, chunks: patch.full ? o.append : listApply(previous.output.chunks, o, chunkKey) },\n log: patch.full ? (patch.log?.append ?? []) : listApply(previous.log, patch.log, logKey),\n };\n}\n","/**\n * ReplayHost: store, replay and player behind one small message protocol\n * (HostRequest in, HostMessage out; see types.ts).\n *\n * The worker entry (worker.ts) is a shell around this class, so the event\n * store, the reducer and the player run off the main thread. The class has\n * no worker in it: on the main thread, create one with a callback and call\n * handle() - same messages, same behaviour (useful where workers are not\n * available, and in tests).\n *\n * How it keeps every task short\n * - Events are stored at once (a push) and indexed in slices of a few\n * milliseconds, with a turn of the event loop between slices, so commands\n * and ticks are served while a 100,000-event recording is being indexed.\n * - A view is posted at most once per tick: one tick message from the UI\n * (normally one per animation frame), or one turn of the host's own\n * 16 ms timer when the UI sends no ticks. Nothing is posted when nothing\n * changed.\n * - A view is capped (ViewOptions), so its size depends on what is on\n * screen, not on the length of the run.\n */\n\nimport type { NmEvent, Recording } from '@nodejs-map/event-format';\nimport { EventStore } from './store.ts';\nimport { Replay } from './replay.ts';\nimport { Player } from './player.ts';\nimport { openRecording, recordingFromFragment, recordingToFragment, saveRecording } from './recording.ts';\nimport { diffView } from './patch.ts';\nimport type { HostMessage, HostRequest, TimelineAxis, ViewOptions, ViewState } from './types.ts';\n\n/** What the host needs from its surroundings. All optional: defaults use the globals every target has. */\nexport interface HostEnvironment {\n /** A steady millisecond clock. Default: performance.now. */\n now?: () => number;\n /** Run `fn` after about `ms` milliseconds; returns a function that cancels. Default: setTimeout. */\n defer?: (fn: () => void, ms: number) => () => void;\n}\n\n/** The view options a host starts with (see the comment at ReplayHost's #viewOptions). */\nexport const HOST_VIEW_DEFAULTS: Readonly<Required<Pick<ViewOptions, 'maxEntries' | 'maxOutput' | 'maxLog'>>> = { maxEntries: 60, maxOutput: 50, maxLog: 30 };\n\n/** Milliseconds of indexing per slice. */\nconst PUMP_SLICE_MS = 6;\n/** The host's own tick when the UI sends none. */\nconst FRAME_MS = 16;\n/** While a run is live, timeline summaries and markers are re-sent at most this often. */\nconst SUMMARY_INTERVAL_MS = 100;\n\nexport class ReplayHost {\n readonly store: EventStore;\n readonly replay: Replay;\n readonly player: Player;\n #post: (message: HostMessage, transfer?: ArrayBuffer[]) => void;\n #now: () => number;\n #defer: (fn: () => void, ms: number) => () => void;\n /**\n * A posted view is copied twice (out of the worker and into the page), so\n * the host's defaults are smaller than those of Replay.view(): 60 entries\n * per list is more than a panel shows without scrolling; totals are always\n * exact, and the rest can be asked for with a query or a larger\n * `configure.view`.\n */\n #viewOptions: ViewOptions = { ...HOST_VIEW_DEFAULTS };\n #views: 'full' | 'patch' = 'full';\n /** Patch mode: the view posted last, which the next patch builds on. null: the next patch is a full one. */\n #posted: ViewState | null = null;\n #clock: 'internal' | 'external' = 'internal';\n #timeline: { width: number; axis: TimelineAxis } | null = null;\n #wantMarkers = false;\n #dirty = true;\n #summaryDirty = true;\n #lastSummary = -Infinity;\n #cancelFrame: (() => void) | null = null;\n #cancelPump: (() => void) | null = null;\n #disposed = false;\n /** Counts open/reset requests, so a slow `open` that was overtaken does not replace a newer run. */\n #generation = 0;\n\n constructor(post: (message: HostMessage, transfer?: ArrayBuffer[]) => void, env?: HostEnvironment) {\n this.#post = post;\n this.#now = env?.now ?? (typeof performance !== 'undefined' ? () => performance.now() : () => Date.now());\n this.#defer =\n env?.defer ??\n ((fn, ms) => {\n const handle = setTimeout(fn, ms);\n return () => clearTimeout(handle);\n });\n this.store = new EventStore();\n this.replay = new Replay(this.store, { eager: false });\n this.player = new Player(this.replay);\n this.#send({ op: 'ready' });\n }\n\n /** Take one request. Never throws: failures are posted as { op: 'error' }. */\n handle(request: HostRequest): void {\n if (this.#disposed) return;\n const re = request !== null && typeof request === 'object' && 'id' in request && typeof request.id === 'number' ? request.id : null;\n try {\n this.#handle(request);\n } catch (error) {\n this.#send({ op: 'error', re, message: messageOf(error) });\n }\n this.#wake();\n }\n\n /** Stop timers and stop posting. */\n dispose(): void {\n this.#disposed = true;\n if (this.#cancelFrame !== null) this.#cancelFrame();\n if (this.#cancelPump !== null) this.#cancelPump();\n this.#cancelFrame = null;\n this.#cancelPump = null;\n this.player.dispose();\n this.replay.dispose();\n }\n\n #send(message: HostMessage, transfer?: ArrayBuffer[]): void {\n if (!this.#disposed) this.#post(message, transfer);\n }\n\n #handle(request: HostRequest): void {\n if (request === null || typeof request !== 'object') throw new TypeError('not a request');\n switch (request.op) {\n case 'reset':\n this.#generation++;\n this.store.reset();\n // A new run starts the way the first one did: not playing, on the live tail.\n this.player.pause();\n this.player.setFollow(true);\n this.#changed();\n break;\n case 'events': {\n const change = this.store.apply({ base: request.base, events: request.events });\n if (change.rejected !== null) {\n throw new RangeError(\n change.rejected === 'gap'\n ? `events refused: the batch starts at ${request.base} but only ${change.length} events are known`\n : 'events refused: the batch is not of the form { base, events }',\n );\n }\n this.#changed();\n break;\n }\n case 'ended':\n this.store.end();\n this.#changed();\n break;\n case 'open':\n this.#open(request.id, openRecording(request.data));\n break;\n case 'openFragment':\n this.#open(request.id, recordingFromFragment(request.fragment));\n break;\n case 'save': {\n const id = request.id;\n saveRecording({ header: request.header, events: this.store.events as NmEvent[] }, { gzip: request.gzip === true }).then(\n (bytes) => this.#send({ op: 'saved', re: id, bytes }, bytes.buffer instanceof ArrayBuffer ? [bytes.buffer] : undefined),\n (error: unknown) => this.#send({ op: 'error', re: id, message: messageOf(error) }),\n );\n break;\n }\n case 'share': {\n const id = request.id;\n recordingToFragment({ header: request.header, events: this.store.events as NmEvent[] }).then(\n (result) => this.#send({ op: 'shared', re: id, result }),\n (error: unknown) => this.#send({ op: 'error', re: id, message: messageOf(error) }),\n );\n break;\n }\n case 'player':\n this.player.command(request.cmd);\n this.#dirty = true;\n break;\n case 'tick':\n // A tick from the UI means the UI drives the clock.\n if (this.#clock !== 'external') {\n this.#clock = 'external';\n if (this.#cancelFrame !== null) this.#cancelFrame();\n this.#cancelFrame = null;\n }\n this.#frame(typeof request.now === 'number' ? request.now : this.#now());\n break;\n case 'configure':\n if (request.view !== undefined) {\n this.#viewOptions = { ...this.#viewOptions, ...request.view };\n this.#dirty = true;\n }\n if (request.views === 'full' || request.views === 'patch') {\n this.#views = request.views;\n this.#posted = null; // the next post carries everything\n this.#dirty = true;\n }\n if (request.clock === 'external' || request.clock === 'internal') this.#clock = request.clock;\n if (request.timeline !== undefined) {\n this.#timeline = request.timeline === null ? null : { width: request.timeline.width, axis: request.timeline.axis === 'time' ? 'time' : 'index' };\n this.#summaryDirty = true;\n this.#lastSummary = -Infinity;\n }\n if (request.markers !== undefined) {\n this.#wantMarkers = request.markers === true;\n this.#summaryDirty = true;\n this.#lastSummary = -Infinity;\n }\n break;\n case 'query':\n this.#send({ op: 'answer', re: request.id, answer: this.replay.query(request.q) });\n break;\n default:\n throw new TypeError('unknown request');\n }\n }\n\n #open(id: number, loading: Promise<Recording>): void {\n const generation = ++this.#generation;\n loading.then(\n (recording) => {\n if (this.#disposed || generation !== this.#generation) return; // overtaken by a newer open or reset\n this.store.load(recording.events);\n this.player.pause();\n this.#changed();\n this.#send({ op: 'opened', re: id, header: recording.header, events: recording.events.length });\n this.#wake();\n },\n (error: unknown) => this.#send({ op: 'error', re: id, message: messageOf(error) }),\n );\n }\n\n #changed(): void {\n this.#dirty = true;\n this.#summaryDirty = true;\n this.#pump();\n }\n\n /** Index pending events in slices, yielding between them. */\n #pump(): void {\n if (this.#cancelPump !== null || this.#disposed) return;\n if (this.replay.ready >= this.store.length) return;\n this.#cancelPump = this.#defer(() => {\n this.#cancelPump = null;\n const more = this.replay.pump(PUMP_SLICE_MS);\n this.#dirty = true;\n this.#summaryDirty = true;\n if (more) this.#pump();\n this.#wake();\n }, 0);\n }\n\n /** Make sure a frame will come when the host drives its own clock. */\n #wake(): void {\n if (this.#disposed || this.#clock !== 'internal' || this.#cancelFrame !== null) return;\n if (!this.#busy()) return;\n this.#cancelFrame = this.#defer(() => {\n this.#cancelFrame = null;\n this.#frame(this.#now());\n this.#wake();\n }, FRAME_MS);\n }\n\n /** Is there anything a frame could change? */\n #busy(): boolean {\n if (this.#dirty || this.#summaryDirty) return true;\n const s = this.player.state;\n return s.playing || (s.follow && s.live && s.position < s.length);\n }\n\n /** One tick: advance the player and post what changed. */\n #frame(now: number): void {\n const tick = this.player.tick(now);\n if (tick.changed) this.#dirty = true;\n if (this.#dirty) {\n this.#dirty = false;\n const view = this.replay.view(this.#viewOptions);\n if (this.#views === 'patch') {\n this.#send({ op: 'patch', patch: diffView(this.#posted, view), player: tick.state });\n this.#posted = view;\n } else this.#send({ op: 'view', view, player: tick.state });\n }\n if (this.#summaryDirty && (this.#timeline !== null || this.#wantMarkers)) {\n // While events pour in, the scrubber does not need every intermediate state.\n const settled = !this.store.live && this.replay.ready >= this.store.length;\n if (settled || now - this.#lastSummary >= SUMMARY_INTERVAL_MS) {\n this.#summaryDirty = false;\n this.#lastSummary = now;\n // Posted as copies (no transfer): the replay keeps these objects in its cache.\n if (this.#timeline !== null) this.#send({ op: 'timeline', summary: this.replay.timeline(this.#timeline.width, this.#timeline.axis) });\n if (this.#wantMarkers) this.#send({ op: 'markers', markers: this.replay.markers() });\n }\n } else if (this.#timeline === null && !this.#wantMarkers) this.#summaryDirty = false;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","// Atlas ids the live view points at. Each is a feature box in the overlay (o:...), so it\n// survives releases: the overlay is updated when Node's code moves, the id stays.\n// The atlas builder fails if any of these ids is missing from a built atlas.\n// Meanings are true for Node v26.13.1 (libuv 1.52.1); each box links to the exact code.\n\nexport interface WellKnownEntry {\n readonly id: string;\n /** One line, plain English. */\n readonly meaning: string;\n}\n\nexport const WELL_KNOWN = {\n // ---- the event loop (libuv)\n uvRun: { id: 'o:loop.run', meaning: 'uv_run: the event loop. Runs due timers once, then turns: pending, idle, prepare, poll, pending again, check, close, timers.' },\n phaseTimers: { id: 'o:phase.timers', meaning: 'Timers phase: uv__run_timers runs every libuv timer whose time has come (Node uses one for all JS timers).' },\n phasePending: { id: 'o:phase.pending', meaning: 'Pending phase: callbacks deferred from the previous turn; on Windows, completed I/O requests run here.' },\n phaseIdle: { id: 'o:phase.idle', meaning: 'Idle phase: idle handles; Node keeps one active while immediates are queued so poll does not block.' },\n phasePrepare: { id: 'o:phase.prepare', meaning: 'Prepare phase: prepare handles, just before the loop waits for I/O.' },\n phasePoll: { id: 'o:phase.poll', meaning: 'Poll phase: waits for I/O (epoll, kqueue or IOCP) up to the next timer and runs what is ready.' },\n phaseCheck: { id: 'o:phase.check', meaning: 'Check phase: check handles; Node runs setImmediate callbacks here.' },\n phaseClosing: { id: 'o:phase.close', meaning: 'Close phase: close callbacks of handles closed during this turn.' },\n loopTime: { id: 'o:loop.updateTime', meaning: 'The loop clock: libuv reads the time once per turn; timers compare against this cached time.' },\n spinEventLoop: { id: 'o:loop.spin', meaning: \"Node's loop driver: calls uv_run until there is no more work, then emits beforeExit.\" },\n\n // ---- nextTick and microtasks\n tickEnqueue: { id: 'o:tick.nextTick', meaning: 'process.nextTick: pushes a callback onto the nextTick queue.' },\n tickDrain: { id: 'o:tick.drain', meaning: 'processTicksAndRejections: runs the nextTick queue, then microtasks, until both are empty.' },\n runNextTicks: { id: 'o:tick.runNextTicks', meaning: 'runNextTicks: drains nextTicks and microtasks between two timer or immediate callbacks.' },\n microtaskEnqueue: { id: 'o:microtask.queueMicrotask', meaning: 'queueMicrotask: puts a callback on V8\\'s microtask queue.' },\n microtaskCallback: { id: 'o:microtask.runCallback', meaning: 'runMicrotask: the wrapper that runs a queueMicrotask callback with async_hooks before/after.' },\n microtaskCheckpoint: { id: 'o:microtask.checkpoint', meaning: 'MicrotaskQueue::PerformCheckpoint: V8 runs all queued microtasks if it is not already doing so.' },\n microtaskDrain: { id: 'o:microtask.run', meaning: 'MicrotaskQueue::RunMicrotasks: V8 runs every queued microtask (promise reactions, queueMicrotask callbacks).' },\n runMicrotasksBinding: { id: 'o:microtask.binding', meaning: 'runMicrotasks(): the C++ binding processTicksAndRejections calls to make V8 drain the microtask queue.' },\n\n // ---- promises in V8\n promiseThen: { id: 'o:v8.promiseThen', meaning: 'Promise.prototype.then (V8 Torque builtin).' },\n performPromiseThen: { id: 'o:v8.performPromiseThen', meaning: 'PerformPromiseThen: stores the reaction, or queues a reaction job at once if the promise is already settled.' },\n triggerPromiseReactions: { id: 'o:v8.triggerReactions', meaning: 'TriggerPromiseReactions: when a promise settles, turns each stored reaction into a queued job.' },\n promiseReactionEnqueue: { id: 'o:v8.enqueueMicrotask', meaning: 'EnqueueMicrotask builtin: where a promise reaction job (or any microtask) is appended to the microtask queue.' },\n runMicrotasksBuiltin: { id: 'o:v8.runMicrotasksBuiltin', meaning: 'RunMicrotasks builtin: the loop inside V8 that takes jobs off the microtask queue.' },\n runSingleMicrotask: { id: 'o:v8.runSingleMicrotask', meaning: 'RunSingleMicrotask: runs one job, dispatching on its kind (callable, promise reaction, ...).' },\n promiseReactionRun: { id: 'o:v8.promiseReactionJob', meaning: 'PromiseReactionJob: runs a .then/.catch handler with the settled value and settles the derived promise.' },\n\n // ---- timers\n timerSet: { id: 'o:timers.setTimeout', meaning: 'setTimeout: creates a Timeout and inserts it into the timer lists.' },\n setInterval: { id: 'o:timers.setInterval', meaning: 'setInterval: a Timeout that is re-inserted after each run.' },\n timerInsert: { id: 'o:timers.insert', meaning: 'insert: appends the timer to the list for its duration; a new earliest list reschedules the libuv timer.' },\n scheduleTimer: { id: 'o:timers.scheduleTimer', meaning: 'Environment::ScheduleTimer: starts the single libuv timer for the earliest JS timer.' },\n timersNative: { id: 'o:timers.runTimers', meaning: 'Environment::RunTimers: the libuv timer callback; calls processTimers in JS and reschedules.' },\n timersProcess: { id: 'o:timers.processTimers', meaning: 'processTimers: walks the due timer lists in expiry order.' },\n listOnTimeout: { id: 'o:timers.listOnTimeout', meaning: 'listOnTimeout: runs each due timer of one list; nextTicks and microtasks run between timers.' },\n uvRunTimers: { id: 'o:phase.timers', meaning: 'uv__run_timers: libuv runs timers whose timeout is not later than the loop time.' },\n\n // ---- immediates\n immediateSet: { id: 'o:immediate.setImmediate', meaning: 'setImmediate: creates an Immediate and appends it to the immediate queue.' },\n immediateNative: { id: 'o:immediate.check', meaning: 'Environment::CheckImmediate: the check-phase callback that calls processImmediate.' },\n immediateProcess: { id: 'o:immediate.process', meaning: 'processImmediate: runs the queued immediates; nextTicks and microtasks run between them.' },\n toggleImmediateRef: { id: 'o:immediate.toggleRef', meaning: 'Environment::ToggleImmediateRef: starts/stops an idle handle so poll does not block while immediates wait.' },\n\n // ---- thread pool (libuv)\n poolQueueWork: { id: 'o:pool.queue_work', meaning: 'uv_queue_work: the public \"run this function on the thread pool\" call.' },\n poolSubmit: { id: 'o:pool.submit', meaning: 'uv__work_submit: queues work for the pool (starts the threads on first use).' },\n poolPost: { id: 'o:pool.post', meaning: 'post: appends to the shared work queue and wakes an idle pool thread.' },\n poolWorker: { id: 'o:pool.worker', meaning: 'worker: a pool thread; waits, runs one work item, posts the result back.' },\n poolDone: { id: 'o:pool.done', meaning: 'uv__work_done: on the main thread, runs the after-work callbacks of finished items.' },\n poolWake: { id: 'o:pool.asyncSend', meaning: 'uv_async_send: wakes the loop from another thread (eventfd/pipe on Unix, a completion packet on Windows).' },\n scheduleWork: { id: 'o:cb.ScheduleWork', meaning: \"ThreadPoolWork::ScheduleWork: Node's wrapper around uv_queue_work for fs, crypto and zlib jobs.\" },\n\n // ---- calling back into JavaScript\n asyncWrapMakeCallback: { id: 'o:cb.MakeCallback', meaning: 'AsyncWrap::MakeCallback: calls a JS callback for an async resource (async_hooks before/after).' },\n makeCallback: { id: 'o:cb.InternalMakeCallback', meaning: 'InternalMakeCallback: opens a callback scope, calls the function, closes the scope.' },\n callbackScopeClose: { id: 'o:cb.ScopeClose', meaning: 'InternalCallbackScope::Close: after a callback, runs microtasks or the nextTick drain.' },\n\n // ---- debugger\n inspectorPause: { id: 'o:inspector.pause', meaning: 'runMessageLoopOnPause: the main thread waits here while a breakpoint holds JavaScript.' },\n\n // ---- fs\n fsReadFile: { id: 'o:fs.readFile', meaning: 'fs.readFile: small files in one thread-pool job (ReadFileJob), large ones in chunks.' },\n fsReadFileJobRun: { id: 'o:fs.ReadFileJob.Run', meaning: 'ReadFileJob::Run: schedules the whole read on the thread pool.' },\n fsReadFileJobWork: { id: 'o:fs.ReadFileJob.DoThreadPoolWork', meaning: 'ReadFileJob::DoThreadPoolWork: open, fstat, read, close on a pool thread.' },\n fsReadFileJobAfter: { id: 'o:fs.ReadFileJob.AfterThreadPoolWork', meaning: 'ReadFileJob::AfterThreadPoolWork: builds the Buffer and calls back into JS.' },\n fsReqCallback: { id: 'o:fs.reqCallback', meaning: 'FSReqCallback::Resolve: delivers the result of an async fs request to its JS callback.' },\n fsReqPromise: { id: 'o:fs.reqPromise', meaning: 'FSReqPromise::Resolve: settles the promise of an fs/promises request.' },\n\n // ---- crypto\n cryptoPbkdf2: { id: 'o:crypto.pbkdf2', meaning: 'crypto.pbkdf2: creates a PBKDF2Job and runs it on the thread pool.' },\n cryptoRandomBytes: { id: 'o:crypto.randomBytes', meaning: 'crypto.randomBytes: creates a RandomBytesJob and runs it on the thread pool.' },\n cryptoJobRun: { id: 'o:crypto.jobRun', meaning: 'CryptoJob::Run: runs a crypto job now (sync) or schedules it on the thread pool (async).' },\n cryptoDeriveBitsWork: { id: 'o:crypto.deriveBitsWork', meaning: 'DeriveBitsJob::DoThreadPoolWork: the pool-thread side of pbkdf2, randomBytes, scrypt, hkdf...' },\n cryptoPbkdf2DeriveBits: { id: 'o:crypto.pbkdf2DeriveBits', meaning: 'PBKDF2Traits::DeriveBits: the PBKDF2 computation (OpenSSL) on a pool thread.' },\n cryptoRandomBytesDeriveBits: { id: 'o:crypto.randomBytesDeriveBits', meaning: 'RandomBytesTraits::DeriveBits: fills the buffer with random bytes on a pool thread.' },\n cryptoJobAfter: { id: 'o:crypto.jobAfter', meaning: 'CryptoJob::AfterThreadPoolWork: back on the main thread, calls job.ondone in JS.' },\n\n // ---- zlib\n zlibProcessChunk: { id: 'o:zlib.processChunk', meaning: 'processChunk: hands one chunk to the native zlib handle (async write).' },\n zlibWrite: { id: 'o:zlib.write', meaning: 'CompressionStream::Write: queues compression work on the thread pool.' },\n zlibWork: { id: 'o:zlib.work', meaning: 'ZlibContext::DoThreadPoolWork: runs deflate/inflate on a pool thread.' },\n zlibAfter: { id: 'o:zlib.after', meaning: 'CompressionStream::AfterThreadPoolWork: back on the main thread, calls the JS write callback.' },\n\n // ---- dns.lookup\n dnsLookup: { id: 'o:dns.lookup', meaning: 'dns.lookup: asks the OS resolver (getaddrinfo) on the thread pool, not c-ares.' },\n dnsGetAddrInfo: { id: 'o:dns.getAddrInfo', meaning: 'GetAddrInfo (C++): starts uv_getaddrinfo with AfterGetAddrInfo as callback.' },\n uvGetaddrinfo: { id: 'o:dns.uvGetaddrinfo', meaning: 'uv_getaddrinfo: queues the lookup as slow I/O work on the thread pool.' },\n getaddrinfoWork: { id: 'o:dns.getaddrinfoWork', meaning: 'uv__getaddrinfo_work: calls the OS getaddrinfo on a pool thread.' },\n dnsAfterGetAddrInfo: { id: 'o:dns.afterGetAddrInfo', meaning: 'AfterGetAddrInfo: back on the main thread, converts the addresses and calls oncomplete in JS.' },\n\n // ---- sockets, processes, http (async_hooks resources)\n streamRead: { id: 'o:net.streamRead', meaning: 'LibuvStreamWrap::OnUvRead: data arrived on a TCP socket, pipe or TTY; calls onread in JS.' },\n streamAfterWrite: { id: 'o:net.afterWrite', meaning: 'LibuvStreamWrap::AfterUvWrite: a write finished; calls the write callback.' },\n streamAfterShutdown: { id: 'o:net.afterShutdown', meaning: 'LibuvStreamWrap::AfterUvShutdown: the write side was shut down.' },\n onConnection: { id: 'o:net.onConnection', meaning: 'ConnectionWrap::OnConnection: a server accepted a connection.' },\n afterConnect: { id: 'o:net.afterConnect', meaning: 'ConnectionWrap::AfterConnect: an outgoing connect finished.' },\n udpRecv: { id: 'o:net.udpRecv', meaning: 'UDPWrap::OnRecv: a datagram arrived.' },\n processExit: { id: 'o:proc.onExit', meaning: 'ProcessWrap::OnExit: a child process exited.' },\n fsEvent: { id: 'o:fs.watchEvent', meaning: 'FSEventWrap::OnEvent: fs.watch saw a change.' },\n statWatcher: { id: 'o:fs.statWatcher', meaning: 'StatWatcher::Callback: fs.watchFile polled a changed stat.' },\n httpIncoming: { id: 'o:http.incoming', meaning: 'IncomingMessage: a received HTTP request (server) or response (client).' },\n httpClientRequest: { id: 'o:http.clientRequest', meaning: 'ClientRequest: an outgoing HTTP request.' },\n udpSendDone: { id: 'o:net.udpSendDone', meaning: 'UDPWrap::OnSendDone: a datagram send finished; calls oncomplete in JS.' },\n\n // ---- c-ares DNS (dns.resolve*, dns.Resolver)\n dnsChannel: { id: 'o:dns.channel', meaning: 'ChannelWrap::New: creates the c-ares resolver channel used by dns.resolve* and dns.Resolver.' },\n dnsQueryResponse: { id: 'o:dns.queryResponse', meaning: 'QueryWrap::QueueResponseCallback: defers a c-ares answer with SetImmediate, so its callback runs in the check phase.' },\n nativeImmediatesRun: { id: 'o:immediate.native', meaning: 'Environment::RunAndClearNativeImmediates: runs C++ SetImmediate callbacks (such as c-ares answers) from CheckImmediate.' },\n\n // ---- stream shutdown and handle close\n streamShutdownQueue: { id: 'o:uv.shutdown', meaning: 'uv_shutdown: on Unix, with no writes pending, puts the stream on the pending queue (uv__io_feed); on Windows (TCP), queues a pending request.' },\n streamShutdownRun: { id: 'o:uv.shutdownDone', meaning: 'Where the shutdown callback runs: uv__drain on Unix (from the pending phase), uv__process_tcp_shutdown_req on Windows (TCP).' },\n uvClose: { id: 'o:loop.uvClose', meaning: 'uv_close: starts closing a handle; its close callback always runs later, in the close phase.' },\n closeCallbacks: { id: 'o:loop.finishClose', meaning: 'Where a close callback runs: uv__finish_close (called by uv__run_closing_handles) on Unix, uv__process_endgames on Windows.' },\n handleOnClose: { id: 'o:cb.handleOnClose', meaning: \"HandleWrap::OnClose: Node's close callback for every handle; calls the JS handle's onclose.\" },\n\n // ---- streams and workers\n streamFinished: { id: 'o:streams.eos', meaning: 'eos (stream.finished): calls back once a stream has ended, finished or errored; used by pipeline.' },\n messagePortOnMessage: { id: 'o:worker.onMessage', meaning: 'MessagePort::OnMessage: delivers queued messages from another thread to the JS listener of the port.' },\n workerExit: { id: 'o:worker.onExit', meaning: 'Worker::JoinThread: after the worker thread stopped, calls onexit in the parent thread.' },\n} as const satisfies Record<string, WellKnownEntry>;\n\nexport type WellKnownName = keyof typeof WELL_KNOWN;\n\n/** The 7 phases in the order uv_run runs them in one turn (timers also run once before the first turn). */\nexport const PHASE_ORDER = ['pending', 'idle', 'prepare', 'poll', 'check', 'closing', 'timers'] as const;\nexport type PhaseName = (typeof PHASE_ORDER)[number];\nexport const PHASE_IDS: Readonly<Record<PhaseName, string>> = {\n timers: WELL_KNOWN.phaseTimers.id,\n pending: WELL_KNOWN.phasePending.id,\n idle: WELL_KNOWN.phaseIdle.id,\n prepare: WELL_KNOWN.phasePrepare.id,\n poll: WELL_KNOWN.phasePoll.id,\n check: WELL_KNOWN.phaseCheck.id,\n closing: WELL_KNOWN.phaseClosing.id,\n};\n\n/** Atlas id of an event-loop phase. */\nexport function phaseAtlasId(phase: PhaseName): string {\n return PHASE_IDS[phase];\n}\n\n/**\n * async_hooks resource types (as reported by Node v26.13.1, checked with a probe script) to\n * the atlas box where the resource's callback is made. Types not listed here map to nothing.\n */\nexport interface AsyncTypeInfo extends WellKnownEntry {\n /** Short label a student can read, shown as the item's title in the app (\"setTimeout\", \"pbkdf2 request\"). */\n readonly title: string;\n}\n\nexport const ASYNC_TYPE_INFO: Readonly<Record<string, AsyncTypeInfo>> = {\n Timeout: { id: WELL_KNOWN.listOnTimeout.id, title: 'setTimeout / setInterval timer', meaning: 'setTimeout / setInterval timer; its callback runs from listOnTimeout.' },\n Immediate: { id: WELL_KNOWN.immediateProcess.id, title: 'setImmediate', meaning: 'setImmediate; its callback runs from processImmediate in the check phase.' },\n TickObject: { id: WELL_KNOWN.tickDrain.id, title: 'process.nextTick', meaning: 'process.nextTick; its callback runs from processTicksAndRejections.' },\n PROMISE: { id: WELL_KNOWN.promiseReactionRun.id, title: 'promise', meaning: 'A promise (reported while an async hook is enabled); its reactions run as microtasks.' },\n Microtask: { id: WELL_KNOWN.microtaskCallback.id, title: 'queueMicrotask', meaning: 'queueMicrotask callback; runs from the microtask queue via runMicrotask.' },\n FSREQCALLBACK: { id: WELL_KNOWN.fsReqCallback.id, title: 'fs request (callback)', meaning: 'Callback-style fs request. fs.readFile\\'s ReadFileJob reports this type too (its callback comes from ReadFileJob::AfterThreadPoolWork).' },\n FSREQPROMISE: { id: WELL_KNOWN.fsReqPromise.id, title: 'fs/promises request', meaning: 'fs/promises request.' },\n PBKDF2REQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'pbkdf2 request', meaning: 'crypto.pbkdf2 job; work in PBKDF2Traits::DeriveBits on the pool.' },\n RANDOMBYTESREQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'randomBytes request', meaning: 'crypto.randomBytes / randomFill job; work in RandomBytesTraits::DeriveBits on the pool.' },\n SCRYPTREQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'scrypt request', meaning: 'crypto.scrypt job on the pool.' },\n GETADDRINFOREQWRAP: { id: WELL_KNOWN.dnsAfterGetAddrInfo.id, title: 'dns.lookup request', meaning: 'dns.lookup request; getaddrinfo runs on the pool.' },\n ZLIB: { id: WELL_KNOWN.zlibAfter.id, title: 'zlib stream', meaning: 'zlib stream; each chunk is compressed on the pool.' },\n TCPWRAP: { id: WELL_KNOWN.streamRead.id, title: 'TCP connection', meaning: 'TCP socket handle; reads arrive in the poll phase.' },\n TCPSERVERWRAP: { id: WELL_KNOWN.onConnection.id, title: 'TCP server', meaning: 'TCP server handle; new connections arrive in the poll phase.' },\n TCPCONNECTWRAP: { id: WELL_KNOWN.afterConnect.id, title: 'TCP connect request', meaning: 'Outgoing TCP connect request.' },\n PIPEWRAP: { id: WELL_KNOWN.streamRead.id, title: 'pipe', meaning: 'Pipe handle (also stdio pipes).' },\n PIPECONNECTWRAP: { id: WELL_KNOWN.afterConnect.id, title: 'pipe connect request', meaning: 'Outgoing pipe connect request.' },\n TTYWRAP: { id: WELL_KNOWN.streamRead.id, title: 'terminal (TTY)', meaning: 'TTY handle (terminal stdio).' },\n WRITEWRAP: { id: WELL_KNOWN.streamAfterWrite.id, title: 'stream write', meaning: 'A stream write request.' },\n SHUTDOWNWRAP: { id: WELL_KNOWN.streamAfterShutdown.id, title: 'stream shutdown', meaning: 'A stream shutdown request; on Unix uv__drain runs its callback - in the pending phase when no write was waiting, else in poll after the last write.' },\n UDPWRAP: { id: WELL_KNOWN.udpRecv.id, title: 'UDP socket', meaning: 'UDP socket handle.' },\n PROCESSWRAP: { id: WELL_KNOWN.processExit.id, title: 'child process', meaning: 'Child process handle.' },\n FSEVENTWRAP: { id: WELL_KNOWN.fsEvent.id, title: 'fs.watch watcher', meaning: 'fs.watch handle.' },\n STATWATCHER: { id: WELL_KNOWN.statWatcher.id, title: 'fs.watchFile watcher', meaning: 'fs.watchFile handle.' },\n HTTPINCOMINGMESSAGE: { id: WELL_KNOWN.httpIncoming.id, title: 'HTTP incoming message', meaning: 'HTTP incoming message (server request or client response).' },\n QUERYWRAP: { id: WELL_KNOWN.dnsQueryResponse.id, title: 'DNS query (dns.resolve*)', meaning: 'A c-ares query; the answer is deferred with SetImmediate, so the callback runs in the check phase.' },\n DNSCHANNEL: { id: WELL_KNOWN.dnsChannel.id, title: 'DNS resolver (c-ares)', meaning: 'The c-ares channel behind dns.resolve* and dns.Resolver; created when the dns module loads.' },\n PIPESERVERWRAP: { id: WELL_KNOWN.onConnection.id, title: 'pipe server', meaning: 'Pipe (named pipe / Unix socket) server handle; new connections arrive in the poll phase.' },\n UDPSENDWRAP: { id: WELL_KNOWN.udpSendDone.id, title: 'UDP send', meaning: 'A UDP send request.' },\n STREAM_END_OF_STREAM: { id: WELL_KNOWN.streamFinished.id, title: 'stream finished callback', meaning: 'stream.finished / pipeline callback, bound to the context where it was registered.' },\n MESSAGEPORT: { id: WELL_KNOWN.messagePortOnMessage.id, title: 'MessagePort (worker messages)', meaning: 'A message channel between threads; messages are delivered by MessagePort::OnMessage.' },\n WORKER: { id: WELL_KNOWN.workerExit.id, title: 'worker thread', meaning: 'A worker_threads Worker as seen from the parent thread.' },\n HTTPCLIENTREQUEST: { id: WELL_KNOWN.httpClientRequest.id, title: 'HTTP client request', meaning: 'HTTP client request.' },\n};\n\n/** async_hooks type string -> atlas id of the best place to point at for an item of that type. */\nexport const ASYNC_TYPE_AT: Readonly<Record<string, string>> = Object.fromEntries(\n Object.entries(ASYNC_TYPE_INFO).map(([type, e]) => [type, e.id]),\n);\n\n/** Every distinct well-known id (WELL_KNOWN plus the async type map). */\nexport function allWellKnownIds(): string[] {\n const ids = new Set<string>();\n for (const e of Object.values(WELL_KNOWN)) ids.add(e.id);\n for (const id of Object.values(ASYNC_TYPE_AT)) ids.add(id);\n return [...ids].sort();\n}\n","/**\n * Words and numbers for the screen. Pure functions; everything returned is plain text\n * that components render as text nodes (never as HTML).\n */\nimport type { EventKind, NmEvent, Phase, QueueName, SourceId } from '@nodejs-map/event-format';\nimport { ASYNC_TYPE_INFO } from '@nodejs-map/atlas-format';\n\nexport const QUEUE_ORDER: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n\nexport const QUEUE_LABEL: Readonly<Record<QueueName, string>> = {\n nextTick: 'nextTick queue',\n microtask: 'Microtask queue',\n timers: 'Timers',\n immediate: 'Immediates',\n pool: 'Thread pool requests',\n io: 'Pending I/O',\n close: 'Close callbacks',\n};\n\nexport const QUEUE_HELP: Readonly<Record<QueueName, string>> = {\n nextTick: 'process.nextTick callbacks. Drained after the current callback, before promises.',\n microtask: 'Promise reactions and queueMicrotask callbacks (V8). Drained after the nextTick queue.',\n timers: 'setTimeout and setInterval. Run in the timers phase when their time has come.',\n immediate: 'setImmediate callbacks. Run in the check phase.',\n pool: 'Requests whose work runs on the libuv thread pool.',\n io: 'Requests and handles waiting on the operating system.',\n close: 'Handles waiting for their close callback.',\n};\n\nexport const PHASE_LABEL: Readonly<Record<Phase, string>> = {\n timers: 'timers',\n pending: 'pending',\n idle: 'idle',\n prepare: 'prepare',\n poll: 'poll',\n check: 'check',\n closing: 'close',\n};\n\nexport const SOURCE_LABEL: Readonly<Record<SourceId, string>> = {\n hooks: 'async_hooks',\n trace: 'trace events',\n cdp: 'debugger',\n probe: 'probe build',\n helper: 'helper',\n rule: 'rule',\n};\n\nexport const SOURCE_HELP: Readonly<Record<SourceId, string>> = {\n hooks: 'Reported by async_hooks inside the program.',\n trace: \"Reported by Node's own trace events.\",\n cdp: 'Reported by the JavaScript debugger (DevTools protocol).',\n probe: 'Reported by the probe build from inside libuv and Node.',\n helper: 'Reported by the nodejs-map helper process.',\n rule: 'Worked out by a rule from other events.',\n};\n\nconst nf1 = new Intl.NumberFormat('en', { maximumFractionDigits: 1, minimumFractionDigits: 1 });\nconst nf3 = new Intl.NumberFormat('en', { maximumFractionDigits: 3, minimumFractionDigits: 3 });\nconst nf0 = new Intl.NumberFormat('en', { maximumFractionDigits: 0 });\n\n/** A point in time or a span given in microseconds: \"850 µs\", \"12.345 ms\", \"3.210 s\". */\nexport function formatMicros(us: number): string {\n if (!Number.isFinite(us)) return '-';\n const abs = Math.abs(us);\n if (abs < 1000) return `${nf0.format(us)} µs`;\n if (abs < 1_000_000) return `${nf3.format(us / 1000)} ms`;\n return `${nf3.format(us / 1_000_000)} s`;\n}\n\n/** A span given in milliseconds: \"0.4 ms\", \"12.0 ms\", \"3.2 s\". */\nexport function formatMillis(ms: number): string {\n if (!Number.isFinite(ms)) return '-';\n if (Math.abs(ms) < 1000) return `${nf1.format(ms)} ms`;\n return `${nf1.format(ms / 1000)} s`;\n}\n\nexport function formatCount(n: number): string {\n return nf0.format(n);\n}\n\nexport function plural(n: number, one: string, many = `${one}s`): string {\n return `${formatCount(n)} ${n === 1 ? one : many}`;\n}\n\n/** Last path segment of a URL or path: \"file:///a/b/c.js\" -> \"c.js\". Never throws. */\nexport function baseName(urlOrPath: string): string {\n const cut = urlOrPath.replace(/[?#].*$/, '');\n const parts = cut.split(/[\\\\/]/);\n for (let i = parts.length - 1; i >= 0; i--) {\n const part = parts[i];\n if (part) {\n try {\n return decodeURIComponent(part);\n } catch {\n return part;\n }\n }\n }\n return urlOrPath;\n}\n\n/** Does a script URL from the target name this program? Compared by base name. */\nexport function isSameProgram(scriptUrl: string, programName: string): boolean {\n if (scriptUrl === programName) return true;\n if (scriptUrl.startsWith('node:')) return false; // Node's own JavaScript is never the program\n return baseName(scriptUrl) === baseName(programName);\n}\n\n/** Text is shown on one line in lists: cut it and make control characters visible. */\nexport function oneLine(text: string, max = 160): string {\n let out = '';\n for (const ch of text) {\n if (out.length >= max) return `${out}…`;\n const code = ch.codePointAt(0) as number;\n if (ch === '\\n') out += '⏎';\n else if (ch === '\\t') out += ' ';\n else if (code < 0x20 || code === 0x7f) out += '�';\n else out += ch;\n }\n return out;\n}\n\n/**\n * Plain words for an async_hooks type, shown before the raw type (which stays visible next\n * to them). In order: the label the helper gave the item (\"setTimeout 5 ms\"), else the\n * title the atlas has for the type (ASYNC_TYPE_INFO), else the few words below for types\n * the atlas does not list. null: we have no words, the raw type is all there is.\n */\nconst OWN_WORDS: Readonly<Record<string, string>> = {\n GETNAMEINFOREQWRAP: 'dns.lookupService request',\n};\n\nexport function itemKindWords(type: string): string | null {\n const title = ASYNC_TYPE_INFO[type]?.title;\n if (title) return title;\n const own = OWN_WORDS[type];\n if (own) return own;\n // Crypto jobs are all named <WHAT>REQUEST (HKDFREQUEST, SIGNREQUEST, ...).\n const crypto = /^([A-Z0-9]{2,24})REQUEST$/.exec(type);\n if (crypto && crypto[1]) return `${crypto[1].toLowerCase()} request`;\n return null;\n}\n\n/** For labels and dialog titles: \"setTimeout 5 ms #12 (Timeout)\", \"TCP server #7 (TCPSERVERWRAP)\". */\nexport function itemTitle(item: { id: number; type: string; label: string | null }): string {\n const words = item.label ? oneLine(item.label, 60) : itemKindWords(item.type);\n return words ? `${words} #${item.id} (${item.type})` : `${item.type} #${item.id}`;\n}\n\n/** Groups for the event log filters. Every kind belongs to exactly one. */\nexport type LogGroup = 'run' | 'output' | 'callbacks' | 'queues' | 'loop' | 'timers' | 'pool' | 'items' | 'debug' | 'signals';\n\nexport const LOG_GROUPS: readonly LogGroup[] = ['run', 'output', 'callbacks', 'queues', 'loop', 'timers', 'pool', 'items', 'debug', 'signals'];\n\nexport const LOG_GROUP_LABEL: Readonly<Record<LogGroup, string>> = {\n run: 'Run',\n output: 'Output',\n callbacks: 'Callbacks',\n queues: 'Queues',\n loop: 'Loop',\n timers: 'Timers',\n pool: 'Pool',\n items: 'Items',\n debug: 'Debugger',\n signals: 'Raw signals',\n};\n\nexport const KIND_GROUP: Readonly<Record<EventKind, LogGroup>> = {\n 'run.start': 'run',\n 'run.end': 'run',\n note: 'run',\n output: 'output',\n 'item.new': 'items',\n 'item.gone': 'items',\n 'promise.settled': 'items',\n 'callback.start': 'callbacks',\n 'callback.end': 'callbacks',\n 'timer.set': 'timers',\n 'timer.fired': 'timers',\n 'loop.sample': 'signals',\n scope: 'signals',\n 'pool.thread': 'signals',\n signal: 'signals',\n 'queue.add': 'queues',\n 'queue.remove': 'queues',\n 'loop.turn': 'loop',\n 'phase.enter': 'loop',\n 'phase.leave': 'loop',\n 'pool.queued': 'pool',\n 'pool.started': 'pool',\n 'pool.finished': 'pool',\n 'pool.posted': 'pool',\n 'pool.delivered': 'pool',\n 'pool.cancelled': 'pool',\n 'pool.size': 'pool',\n 'pool.link': 'pool',\n 'debug.paused': 'debug',\n 'debug.resumed': 'debug',\n 'gate.stopped': 'debug',\n 'gate.released': 'debug',\n 'clock.frozen': 'debug',\n 'clock.unfrozen': 'debug',\n};\n\n/** One line that says what an event is. Used by the event log (built in the worker). */\nexport function summarizeEvent(e: NmEvent): string {\n switch (e.k) {\n case 'run.start':\n return `Run started: ${oneLine(e.program, 60)} on Node ${e.node.version} (${e.mode === 'debug' ? 'debug' : 'free run'}, pool size ${e.poolSize})`;\n case 'run.end':\n return e.signal ? `Run ended by signal ${e.signal}` : `Run ended with exit code ${String(e.code)}`;\n case 'output':\n return `${e.stream}: ${oneLine(e.text, 120)}`;\n case 'item.new':\n return `New ${e.label ? `${oneLine(e.label, 40)} (${e.type})` : e.type} #${e.id}, created during #${e.trigger}${e.loc ? ` at ${baseName(e.loc.url)}:${e.loc.line}` : ''}`;\n case 'callback.start':\n // `close` marks the close callback of a handle (a socket, a server, a child process).\n return `${e.close === true ? 'Close callback' : 'Callback'} of ${e.type} #${e.id} started`;\n case 'callback.end':\n return `Callback of #${e.id} returned`;\n case 'item.gone':\n return `#${e.id} destroyed`;\n case 'promise.settled':\n return `Promise #${e.id} settled`;\n case 'timer.set':\n return `${e.repeat ? 'setInterval' : 'setTimeout'} #${e.id}: ${formatMillis(e.delayMs)}`;\n case 'loop.sample':\n return `Loop counters: turn ${e.loopCount}, ${e.events} events, ${e.eventsWaiting} waiting`;\n case 'scope':\n return `Node scope ${oneLine(e.name, 40)} lasted ${formatMicros(e.durUs)}`;\n case 'pool.thread':\n return `A pool thread ${e.edge === 'start' ? 'started' : 'finished'} ${oneLine(e.name, 40)}`;\n case 'signal':\n return `${oneLine(e.cat, 40)} / ${oneLine(e.name, 40)} (${oneLine(e.ph, 4)})`;\n case 'queue.add':\n return `#${e.id} waits in ${QUEUE_LABEL[e.queue] ?? e.queue}`;\n case 'queue.remove':\n return `#${e.id} left ${QUEUE_LABEL[e.queue] ?? e.queue} (${e.why === 'cancel' ? 'cancelled' : 'gone'})`;\n case 'loop.turn':\n return `Loop turn ${e.n}`;\n case 'phase.enter':\n return `Entered the ${PHASE_LABEL[e.phase] ?? e.phase} phase`;\n case 'phase.leave':\n return `Left the ${PHASE_LABEL[e.phase] ?? e.phase} phase`;\n case 'timer.fired':\n return `Node's timer is due${e.lateMs === undefined ? '' : `, ${formatMillis(e.lateMs)} late`}`;\n case 'pool.queued':\n return `Pool job ${oneLine(e.job, 24)} queued (${e.kind}${e.op ? ` ${oneLine(e.op, 30)}` : ''})`;\n case 'pool.started':\n return `Pool thread ${e.thread} started job ${oneLine(e.job, 24)}`;\n case 'pool.finished':\n return `Pool thread ${e.thread} finished job ${oneLine(e.job, 24)}`;\n case 'pool.posted':\n return `Pool thread ${e.thread} posted the result of job ${oneLine(e.job, 24)} to the loop`;\n case 'pool.delivered':\n return `The loop took the result of pool job ${oneLine(e.job, 24)}`;\n case 'pool.cancelled':\n return `Pool job ${oneLine(e.job, 24)} was cancelled before a thread took it`;\n case 'pool.size':\n return `The thread pool has ${e.size} threads (the program changed the size before first use)`;\n case 'pool.link':\n return `Pool job ${oneLine(e.job, 24)} belongs to #${e.id}`;\n case 'debug.paused': {\n const top = e.frames[0];\n return `Paused (${e.reason})${top ? ` at ${baseName(top.loc.url)}:${top.loc.line}` : ''}`;\n }\n case 'debug.resumed':\n return `Resumed after ${formatMillis(e.pausedMs)}`;\n case 'gate.stopped':\n return `Stopped at the ${e.gate} gate${e.phase ? ` (${PHASE_LABEL[e.phase] ?? e.phase})` : ''}`;\n case 'gate.released':\n return `Gate released after ${formatMillis(e.stoppedMs)}`;\n case 'clock.frozen':\n return 'Loop clock frozen';\n case 'clock.unfrozen':\n return `Loop clock running again; ${formatMillis(e.hiddenMs)} hidden from the program`;\n case 'note':\n return `${e.level === 'warn' ? 'Warning from the tool' : 'Note from the tool'}: ${oneLine(e.text, 220)}`;\n default:\n // A kind from a newer format version: show its name rather than nothing.\n return String((e as { k: unknown }).k);\n }\n}\n","/**\n * The event log behind the Events panel: a filtered, windowed read over the whole event\n * list. Runs in the worker. The page asks for the rows it shows (a few dozen) and gets\n * small plain rows back; it never holds the list.\n *\n * The same class tracks what the run is doing at its tail (running, paused, at a gate),\n * because the run controls need that even while the player looks at an earlier position.\n */\nimport type { Certainty, EventKind, NmEvent, SourceId } from '@nodejs-map/event-format';\nimport { KIND_GROUP, LOG_GROUPS, summarizeEvent } from './format.ts';\nimport type { LogGroup } from './format.ts';\n\nexport interface LogFilter {\n /** Groups to show. */\n groups: readonly LogGroup[];\n /** Certainties to show. */\n certainty: readonly Certainty[];\n}\n\nexport const ALL_GROUPS_FILTER: LogFilter = { groups: LOG_GROUPS, certainty: ['observed', 'inferred', 'model'] };\n\n/** One row of the Events panel. Plain data, cheap to post. */\nexport interface LogRow {\n /** Index of the event in the run. */\n index: number;\n t: number;\n k: string;\n c: Certainty;\n src: SourceId;\n rule: string | null;\n at: string | null;\n approx: boolean;\n text: string;\n}\n\nexport interface LogWindow {\n /** Rows that match the filter in the whole run. */\n total: number;\n /** Row number of rows[0] in the filtered list. */\n offset: number;\n rows: LogRow[];\n /**\n * Row number, in the filtered list, of the latest matching event at or before the\n * position asked for (-1: none). The panel marks it as \"now\".\n */\n cursorRow: number;\n /** Events in the run when this was read. */\n length: number;\n /** True when the filter lets every event through: row n is then the event at index n. */\n all: boolean;\n /** The position cursorRow was worked out for. */\n position: number;\n}\n\n/**\n * Where the cursor is in a window that was read for another position, when that can be\n * told from the rows at hand: the row of the latest event before `position`. Returns\n * undefined when the answer lies outside the rows (the worker must be asked).\n */\nexport function cursorRowIn(window: LogWindow, position: number): number | undefined {\n if (window.all) return Math.min(position, window.total) - 1;\n const rows = window.rows;\n const first = rows[0];\n const last = rows[rows.length - 1];\n if (!first || !last) return window.total === 0 ? -1 : undefined;\n if (position <= first.index) return window.offset === 0 ? -1 : undefined;\n if (position > last.index + 1) return window.offset + rows.length === window.total ? window.total - 1 : undefined;\n let lo = 0;\n let hi = rows.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if ((rows[mid] as LogRow).index < position) lo = mid + 1;\n else hi = mid;\n }\n return window.offset + lo - 1;\n}\n\nexport type TailStatus = 'idle' | 'running' | 'paused' | 'gated' | 'ended';\n\nexport interface TailState {\n status: TailStatus;\n mode: 'free' | 'debug' | null;\n length: number;\n}\n\nconst CERTAINTY_BIT: Readonly<Record<Certainty, number>> = { observed: 1, inferred: 2, model: 4 };\n\nfunction filterKey(f: LogFilter): string {\n return `${[...f.groups].sort().join(',')}|${[...f.certainty].sort().join(',')}`;\n}\n\nfunction toRow(e: NmEvent, index: number): LogRow {\n let text: string;\n try {\n text = summarizeEvent(e);\n } catch {\n text = String(e.k); // a malformed event must not break the list\n }\n return {\n index,\n t: e.t,\n k: e.k,\n c: e.c,\n src: e.src,\n rule: e.rule ?? null,\n at: e.at ?? null,\n approx: e.tq !== undefined,\n text,\n };\n}\n\nfunction statusAfter(e: NmEvent): TailStatus | null {\n switch (e.k) {\n case 'run.start':\n return 'running';\n case 'run.end':\n return 'ended';\n case 'debug.paused':\n return 'paused';\n case 'gate.stopped':\n return 'gated';\n case 'debug.resumed':\n case 'gate.released':\n return 'running';\n default:\n return null;\n }\n}\n\nexport class LogIndex {\n #events: NmEvent[] = [];\n /** Indexes of the events that match the current filter, ascending. Grown in place. */\n #matches = new Uint32Array(1024);\n #matchCount = 0;\n /** Events already tested against the filter. */\n #scanned = 0;\n #key = filterKey(ALL_GROUPS_FILTER);\n #groupOn: ReadonlySet<LogGroup> = new Set(LOG_GROUPS);\n #certaintyMask = 7;\n #all = true;\n /** [event index, status] of every event that changes the tail status, ascending. */\n #statusMarks: Array<[number, TailStatus]> = [];\n #mode: 'free' | 'debug' | null = null;\n\n get length(): number {\n return this.#events.length;\n }\n\n reset(): void {\n this.#events = [];\n this.#matchCount = 0;\n this.#scanned = 0;\n this.#statusMarks = [];\n this.#mode = null;\n }\n\n /** The `events` message: keep the first `base` events, then append. Returns false when `base` leaves a gap. */\n apply(base: number, events: readonly NmEvent[]): boolean {\n if (!Number.isInteger(base) || base < 0 || base > this.#events.length) return false;\n if (base < this.#events.length) {\n this.#events.length = base;\n if (this.#scanned > base) {\n this.#scanned = base;\n let n = this.#matchCount;\n while (n > 0 && (this.#matches[n - 1] as number) >= base) n--;\n this.#matchCount = n;\n }\n while (this.#statusMarks.length > 0 && (this.#statusMarks[this.#statusMarks.length - 1] as [number, TailStatus])[0] >= base) {\n this.#statusMarks.pop();\n }\n }\n for (let i = 0; i < events.length; i++) {\n const e = events[i] as NmEvent;\n const index = this.#events.length;\n this.#events.push(e);\n if (typeof e !== 'object' || e === null) continue;\n const status = statusAfter(e);\n if (status) this.#statusMarks.push([index, status]);\n if (e.k === 'run.start') this.#mode = e.mode === 'debug' ? 'debug' : 'free';\n }\n return true;\n }\n\n tail(): TailState {\n const last = this.#statusMarks[this.#statusMarks.length - 1];\n return { status: last ? last[1] : 'idle', mode: this.#mode, length: this.#events.length };\n }\n\n #matchesFilter(e: NmEvent): boolean {\n if (typeof e !== 'object' || e === null) return this.#all;\n if (this.#all) return true;\n const group = KIND_GROUP[e.k as EventKind];\n if (group !== undefined && !this.#groupOn.has(group)) return false;\n // An unknown kind (newer format) is shown whenever any group is on: hiding it would hide evidence.\n return ((CERTAINTY_BIT[e.c] ?? 0) & this.#certaintyMask) !== 0;\n }\n\n #setFilter(filter: LogFilter): void {\n const key = filterKey(filter);\n if (key === this.#key) return;\n this.#key = key;\n this.#groupOn = new Set(filter.groups);\n this.#certaintyMask = filter.certainty.reduce((m, c) => m | (CERTAINTY_BIT[c] ?? 0), 0);\n this.#all = this.#groupOn.size === LOG_GROUPS.length && this.#certaintyMask === 7;\n this.#matchCount = 0;\n this.#scanned = 0;\n }\n\n #scan(): void {\n if (this.#all) {\n this.#scanned = this.#events.length;\n return;\n }\n for (let i = this.#scanned; i < this.#events.length; i++) {\n if (!this.#matchesFilter(this.#events[i] as NmEvent)) continue;\n if (this.#matchCount === this.#matches.length) {\n const bigger = new Uint32Array(this.#matches.length * 2);\n bigger.set(this.#matches);\n this.#matches = bigger;\n }\n this.#matches[this.#matchCount++] = i;\n }\n this.#scanned = this.#events.length;\n }\n\n /** Row number of the latest match with event index < position, or -1. */\n #rowBefore(position: number): number {\n if (this.#all) return Math.min(position, this.#events.length) - 1;\n let lo = 0;\n let hi = this.#matchCount;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if ((this.#matches[mid] as number) < position) lo = mid + 1;\n else hi = mid;\n }\n return lo - 1;\n }\n\n /**\n * Rows [offset, offset + limit) of the filtered list. `position` is the player position\n * (events applied); the row of the event applied last, or the nearest match before it,\n * comes back as cursorRow.\n */\n window(filter: LogFilter, offset: number, limit: number, position: number): LogWindow {\n this.#setFilter(filter);\n this.#scan();\n const total = this.#all ? this.#events.length : this.#matchCount;\n const from = Math.max(0, Math.min(Math.trunc(offset), total));\n const to = Math.max(from, Math.min(from + Math.max(0, Math.min(Math.trunc(limit), 500)), total));\n const rows: LogRow[] = [];\n for (let row = from; row < to; row++) {\n const index = this.#all ? row : (this.#matches[row] as number);\n const e = this.#events[index];\n if (e === undefined) break;\n rows.push(\n typeof e === 'object' && e !== null\n ? toRow(e, index)\n : { index, t: 0, k: '?', c: 'model', src: 'helper', rule: null, at: null, approx: false, text: 'Malformed event' },\n );\n }\n return { total, offset: from, rows, cursorRow: this.#rowBefore(position), length: this.#events.length, all: this.#all, position };\n }\n\n /** One event, for the \"go to this event\" detail. */\n eventAt(index: number): NmEvent | null {\n return this.#events[index] ?? null;\n }\n}\n","/**\n * The app's worker logic, without the worker: ReplayHost plus the \"app.\" messages of\n * protocol.ts. Kept free of worker globals so the unit tests run it in Node.\n */\nimport type { NmEvent, Recording } from '@nodejs-map/event-format';\nimport { ReplayHost, openRecording, recordingFromFragment } from '@nodejs-map/replay';\nimport type { HostEnvironment, HostMessage } from '@nodejs-map/replay';\nimport { LogIndex } from '../lib/logIndex.ts';\nimport type { TailState } from '../lib/logIndex.ts';\nimport type { AppRequest, WorkerMessage, WorkerRequest } from './protocol.ts';\n\ntype Post = (message: WorkerMessage, transfer?: ArrayBuffer[]) => void;\n\ninterface EventsFrame {\n op: 'events';\n run: string;\n base: number;\n events: NmEvent[];\n}\n\nfunction isEventsFrame(v: unknown): v is EventsFrame {\n if (typeof v !== 'object' || v === null) return false;\n const f = v as Record<string, unknown>;\n return f['op'] === 'events' && typeof f['run'] === 'string' && typeof f['base'] === 'number' && Array.isArray(f['events']);\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Recordings are fed to the host in slices so that one request never holds the worker for long. */\nconst OPEN_SLICE = 5000;\n\nexport class AppHost {\n readonly #post: Post;\n readonly #host: ReplayHost;\n readonly #log = new LogIndex();\n /** Run whose frames are accepted. */\n #run: string | null = null;\n /** True between app.newRun and the first frame (or app.run): the next run named is adopted. */\n #adopting = false;\n /** Runs that are over for us; their late frames are dropped. */\n readonly #stale = new Set<string>();\n #lastTail = '';\n /** Bumped whenever the run is replaced; an open that finishes late checks it. */\n #generation = 0;\n\n constructor(post: Post, env?: HostEnvironment) {\n this.#post = post;\n this.#host = new ReplayHost((m: HostMessage, transfer?: ArrayBuffer[]) => post(m, transfer), env);\n }\n\n handle(request: WorkerRequest): void {\n try {\n if (request.op.startsWith('app.')) this.#app(request as AppRequest);\n else {\n this.#host.handle(request as Exclude<WorkerRequest, AppRequest>);\n // The page sends its next tick only after this: it never queues ticks, and so\n // never receives more than one view per frame, however slow either side is.\n if (request.op === 'tick') this.#post({ op: 'app.ticked' });\n }\n } catch (e) {\n this.#post({ op: 'app.error', re: 'id' in request && typeof request.id === 'number' ? request.id : null, message: message(e) });\n }\n }\n\n dispose(): void {\n this.#host.dispose();\n }\n\n #replaceRun(): void {\n this.#generation++;\n if (this.#run !== null) this.#stale.add(this.#run);\n this.#run = null;\n this.#adopting = false;\n this.#log.reset();\n this.#host.handle({ op: 'reset' });\n }\n\n #tailChanged(): void {\n const tail: TailState = this.#log.tail();\n const key = `${tail.status}|${String(tail.mode)}|${String(this.#run)}`;\n if (key === this.#lastTail) return;\n this.#lastTail = key;\n this.#post({ op: 'app.tail', tail, run: this.#run });\n }\n\n #app(request: AppRequest): void {\n switch (request.op) {\n case 'app.newRun':\n this.#replaceRun();\n this.#adopting = true;\n this.#tailChanged();\n return;\n case 'app.run':\n if (this.#stale.has(request.run)) return;\n if (this.#adopting || this.#run === null) {\n this.#run = request.run;\n this.#adopting = false;\n this.#tailChanged();\n }\n return;\n case 'app.eventsText': {\n let frame: unknown;\n try {\n frame = JSON.parse(request.text);\n } catch {\n this.#post({ op: 'app.error', re: null, message: 'The helper sent an events message that is not valid JSON.' });\n return;\n }\n if (!isEventsFrame(frame)) return;\n if (this.#stale.has(frame.run)) return;\n if (this.#run === null) {\n if (!this.#adopting) return; // nobody asked for a run: do not show one\n this.#run = frame.run;\n this.#adopting = false;\n } else if (frame.run !== this.#run) return;\n if (!this.#log.apply(frame.base, frame.events)) {\n this.#post({ op: 'app.error', re: null, message: 'Events from the helper arrived with a gap; the view may be incomplete.' });\n return;\n }\n this.#host.handle({ op: 'events', base: frame.base, events: frame.events });\n this.#tailChanged();\n return;\n }\n case 'app.runEnded':\n if (request.run !== this.#run) return;\n this.#host.handle({ op: 'ended' });\n return;\n case 'app.open':\n void this.#open(request.id, () => openRecording(request.data));\n return;\n case 'app.openFragment':\n void this.#open(request.id, () => recordingFromFragment(request.fragment));\n return;\n case 'app.close':\n this.#replaceRun();\n this.#tailChanged();\n return;\n case 'app.log':\n this.#post({\n op: 'app.log',\n re: request.id,\n window: this.#log.window(request.filter, request.offset, request.limit, request.position),\n });\n return;\n }\n }\n\n async #open(id: number, decode: () => Promise<Recording>): Promise<void> {\n // Decoding validates every event and never evaluates anything (see event-format's codec).\n this.#replaceRun();\n const generation = this.#generation;\n let recording: Recording;\n try {\n recording = await decode();\n } catch (e) {\n this.#post({ op: 'app.error', re: id, message: message(e) });\n return;\n }\n if (generation !== this.#generation) {\n this.#post({ op: 'app.error', re: id, message: 'Opening was cancelled: another run or recording was opened meanwhile.' });\n return;\n }\n try {\n const events = recording.events;\n // A recording opens at its start and waits for the user: it must not race to its\n // end the way a live run follows its tail.\n this.#host.handle({ op: 'player', cmd: { do: 'follow', on: false } });\n this.#host.handle({ op: 'player', cmd: { do: 'pause' } });\n for (let base = 0; base < events.length || base === 0; base += OPEN_SLICE) {\n const slice = events.slice(base, base + OPEN_SLICE);\n this.#log.apply(base, slice);\n this.#host.handle({ op: 'events', base, events: slice });\n if (events.length === 0) break;\n }\n this.#host.handle({ op: 'ended' });\n this.#host.handle({ op: 'player', cmd: { do: 'seek', position: 0 } });\n this.#post({ op: 'app.opened', re: id, header: recording.header, events: events.length });\n this.#tailChanged();\n } catch (e) {\n this.#post({ op: 'app.error', re: id, message: message(e) });\n }\n }\n}\n","/**\n * Worker entry: a thin shell around AppHost. Everything that touches the event list\n * (parsing, decoding, reducing, indexing) happens on this thread.\n */\nimport { AppHost } from './appHost.ts';\nimport type { WorkerMessage, WorkerRequest } from './protocol.ts';\n\n/** The two things used from the worker global scope; declared here so the app project needs no \"webworker\" lib. */\ninterface WorkerScope {\n postMessage(message: unknown, transfer: ArrayBuffer[]): void;\n addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n}\n\nconst scope = globalThis as unknown as WorkerScope;\nconst host = new AppHost((message: WorkerMessage, transfer?: ArrayBuffer[]) => scope.postMessage(message, transfer ?? []));\nscope.addEventListener('message', (event) => host.handle(event.data as WorkerRequest));\n"],"mappings":"AA8vBA,MAAaE,EAAmB,CAC9B,cACA,eACA,YACA,eACA,UACA,QACA,WACA,WACA,SACA,SACA,QACA,OACA,MACF,EC3vBA,IAAaC,EAAb,KAAwB,CACtBC,GAAqB,CAAC,EACtBC,GAAW,EACXC,GAAS,GACTC,mBAAa,IAAI,IAGjB,IAAI,QAA6B,CAC/B,OAAO,KAAKH,EACd,CAEA,IAAI,QAAiB,CACnB,OAAO,KAAKA,GAAQ,MACtB,CAGA,IAAI,SAAkB,CACpB,OAAO,KAAKC,EACd,CAOA,IAAI,QAAsB,CAExB,OADI,KAAKC,GAAe,QACjB,KAAKF,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