@full-self-browsing/phantom-stream 0.2.1 → 0.3.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.
@@ -0,0 +1,487 @@
1
+ // PhantomStream recorder: a timestamped capture transport plus the portable
2
+ // recording format ('phantomstream-recording/1').
3
+ //
4
+ // createRecorder() returns a Transport that capture sends into directly.
5
+ // Every message is stamped { t, type, payload } with the recorder clock, so a
6
+ // recording holds exactly the post-masking wire messages capture sends: the
7
+ // recorder never reads the page, and masking (blockSelector,
8
+ // maskTextSelector, maskInputs, the asset URL maskers) has already run in
9
+ // capture before a message reaches it. Hosts add their own timeline entries
10
+ // with mark() and agent highlights with overlay(). Optional chunk mode emits
11
+ // keyframe-aligned chunks for streaming upload instead of retaining events.
12
+ //
13
+ // No DOM access and no side effects at import: the module only reads the
14
+ // protocol constants, so it imports in bare Node, workers, and pages alike.
15
+ // There are no timers either; chunks are cut on the next event or flush().
16
+
17
+ import { STREAM } from '../protocol/messages.js';
18
+
19
+ /** Recording format id carried in every recording. */
20
+ export const RECORDING_FORMAT = 'phantomstream-recording/1';
21
+
22
+ /** Recording schema version carried in every recording. */
23
+ export const RECORDING_VERSION = 1;
24
+
25
+ /** Event type of host timeline marks. Never a wire message type. */
26
+ export const HOST_MARK_TYPE = 'host:mark';
27
+
28
+ // Chunk mode defaults: a chunk is cut after this many events, or before an
29
+ // event that would make it span more than this many ms of recorder time.
30
+ var DEFAULT_CHUNK_MAX_EVENTS = 200; // events per chunk
31
+ var DEFAULT_CHUNK_MAX_MS = 1000; // 1 s of recorder time per chunk
32
+
33
+ /**
34
+ * One recorded message: the recorder clock time in ms, the wire type (or
35
+ * HOST_MARK_TYPE), and the payload exactly as it was sent.
36
+ *
37
+ * @typedef {Object} RecordingEvent
38
+ * @property {number} t
39
+ * Recorder clock time in ms. Never decreases within a recording.
40
+ * @property {string} type
41
+ * A STREAM.* protocol string, or HOST_MARK_TYPE for host marks.
42
+ * @property {Object} payload
43
+ * The wire payload (same reference as sent), or the JSON-safe mark data
44
+ * with its `kind`.
45
+ */
46
+
47
+ /**
48
+ * A portable recording. JSON-safe whenever its payloads are (capture
49
+ * payloads and host marks always are).
50
+ *
51
+ * @typedef {Object} Recording
52
+ * @property {string} format
53
+ * Exactly RECORDING_FORMAT.
54
+ * @property {number} version
55
+ * Exactly RECORDING_VERSION.
56
+ * @property {number} startedAt
57
+ * Recorder clock ms of the first event.
58
+ * @property {number} endedAt
59
+ * Recorder clock ms of the end of the recording (the last flush, never
60
+ * below the last event's t).
61
+ * @property {Object} meta
62
+ * Host metadata, shallow-copied from toRecording(meta).
63
+ * @property {RecordingEvent[]} events
64
+ * Non-decreasing t; at least one STREAM.SNAPSHOT for playback.
65
+ */
66
+
67
+ /**
68
+ * One chunk-mode upload unit. A chunk whose first event is a snapshot is a
69
+ * keyframe: playback can start from it without any earlier chunk.
70
+ *
71
+ * @typedef {Object} RecordingChunk
72
+ * @property {number} seq
73
+ * 0-based chunk counter.
74
+ * @property {number} t0
75
+ * t of the first event in the chunk.
76
+ * @property {number} t1
77
+ * t of the last event in the chunk.
78
+ * @property {boolean} keyframe
79
+ * True when events[0] is a STREAM.SNAPSHOT.
80
+ * @property {RecordingEvent[]} events
81
+ * At most one snapshot, and only at index 0.
82
+ */
83
+
84
+ /**
85
+ * @typedef {Object} RecorderOptions
86
+ * @property {() => number} [now]
87
+ * Clock in ms. Defaults to Date.now(). A non-finite reading reuses the
88
+ * previous event time.
89
+ * @property {(chunk: RecordingChunk) => void} [onChunk]
90
+ * Enables chunk mode: events are not retained, and each finished chunk is
91
+ * handed to this callback synchronously.
92
+ * @property {number} [chunkMaxEvents]
93
+ * Positive integer. Chunk mode cuts a chunk once it holds this many
94
+ * events. Default 200.
95
+ * @property {number} [chunkMaxMs]
96
+ * Positive finite ms. Chunk mode cuts before an event that would make the
97
+ * chunk span more than this. Default 1000.
98
+ * @property {boolean} [recordReady]
99
+ * Record STREAM.READY readiness pings too. Default false.
100
+ */
101
+
102
+ /**
103
+ * Capture-compatible transport returned on the recorder handle.
104
+ *
105
+ * @typedef {Object} RecorderTransport
106
+ * @property {(type: string, payload: Object) => void} send
107
+ * Stamp and record one wire message.
108
+ * @property {() => void} flush
109
+ * Same function as Recorder.flush; capture.stop() calls it.
110
+ */
111
+
112
+ /**
113
+ * @typedef {Object} RecorderIdentity
114
+ * @property {string} streamSessionId
115
+ * @property {number} snapshotId
116
+ */
117
+
118
+ /**
119
+ * @typedef {Object} Recorder
120
+ * @property {RecorderTransport} transport
121
+ * Pass to createCapture({ transport }).
122
+ * @property {(kind: string, data?: Object) => boolean} mark
123
+ * Record a JSON-safe host mark. Returns false (recording nothing) for an
124
+ * empty kind or data that cannot be serialized.
125
+ * @property {(payload: Object) => boolean} overlay
126
+ * Record a STREAM.OVERLAY with the current identity stamped last. Returns
127
+ * false (recording nothing) before the first snapshot.
128
+ * @property {() => (RecorderIdentity|null)} identity
129
+ * A copy of the latest snapshot identity, or null before the first one.
130
+ * @property {() => void} flush
131
+ * Mark the end time and, in chunk mode, emit the partial chunk.
132
+ * @property {(meta?: Object) => (Recording|null)} toRecording
133
+ * The retained recording, or null in chunk mode.
134
+ */
135
+
136
+ /**
137
+ * @typedef {Object} RecordingValidation
138
+ * @property {boolean} ok
139
+ * @property {string} [error]
140
+ * Lowercase kebab-case reason, present only when ok is false.
141
+ */
142
+
143
+ function isFiniteNumber(value) {
144
+ return typeof value === 'number' && isFinite(value);
145
+ }
146
+
147
+ function isRecordObject(value) {
148
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
149
+ }
150
+
151
+ /**
152
+ * The per-event structural rule, shared by validateRecording and the
153
+ * recorder itself so the recorder never records an event that validation
154
+ * would reject: a non-empty string type, a non-array object payload, and a
155
+ * non-empty string kind on host marks.
156
+ * @param {*} type
157
+ * @param {*} payload
158
+ * @returns {boolean}
159
+ */
160
+ function isEventBody(type, payload) {
161
+ if (typeof type !== 'string' || type === '') return false;
162
+ if (!isRecordObject(payload)) return false;
163
+ if (type === HOST_MARK_TYPE &&
164
+ (typeof payload.kind !== 'string' || payload.kind === '')) {
165
+ return false;
166
+ }
167
+ return true;
168
+ }
169
+
170
+ /** A snapshot the viewer can render: STREAM.SNAPSHOT with string html. */
171
+ function isRenderableSnapshot(type, payload) {
172
+ return type === STREAM.SNAPSHOT && isRecordObject(payload) &&
173
+ typeof payload.html === 'string';
174
+ }
175
+
176
+ function eventTime(event) {
177
+ return event && isFiniteNumber(event.t) ? event.t : null;
178
+ }
179
+
180
+ function defaultNow() {
181
+ return Date.now();
182
+ }
183
+
184
+ /**
185
+ * Build a recording object from events (and optional bounds and meta).
186
+ * Never validates: pair it with validateRecording when the input is not
187
+ * the recorder's own output.
188
+ *
189
+ * Bounds default to the first and last event times (0 and 0 with no
190
+ * events); explicit finite startedAt/endedAt are kept as given.
191
+ *
192
+ * @param {{events?: RecordingEvent[], meta?: Object, startedAt?: number, endedAt?: number}} [options]
193
+ * @returns {Recording}
194
+ */
195
+ export function createRecording(options) {
196
+ var cfg = options || {};
197
+ var events = Array.isArray(cfg.events) ? cfg.events.slice() : [];
198
+ var meta = isRecordObject(cfg.meta) ? Object.assign({}, cfg.meta) : {};
199
+ var firstT = events.length ? eventTime(events[0]) : null;
200
+ var lastT = events.length ? eventTime(events[events.length - 1]) : null;
201
+ var startedAt = isFiniteNumber(cfg.startedAt)
202
+ ? cfg.startedAt
203
+ : (firstT !== null ? firstT : 0);
204
+ var endedAt = isFiniteNumber(cfg.endedAt)
205
+ ? cfg.endedAt
206
+ : (lastT !== null ? lastT : startedAt);
207
+ return {
208
+ format: RECORDING_FORMAT,
209
+ version: RECORDING_VERSION,
210
+ startedAt: startedAt,
211
+ endedAt: endedAt,
212
+ meta: meta,
213
+ events: events
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Structural check of a recording. Never throws. Checks, in order: an
219
+ * object, the format, the version, finite bounds with startedAt not above
220
+ * endedAt, a non-array object meta, a non-empty events array, each event's
221
+ * shape, non-decreasing t, and at least one snapshot with string html.
222
+ * Reports the first fault only. It checks structure, not content: payloads
223
+ * still go through the viewer's sanitizers at playback.
224
+ *
225
+ * @param {*} rec
226
+ * @returns {RecordingValidation}
227
+ */
228
+ export function validateRecording(rec) {
229
+ try {
230
+ if (!isRecordObject(rec)) return { ok: false, error: 'recording-not-object' };
231
+ if (rec.format !== RECORDING_FORMAT) {
232
+ return { ok: false, error: 'recording-format-unsupported' };
233
+ }
234
+ if (rec.version !== RECORDING_VERSION) {
235
+ return { ok: false, error: 'recording-version-unsupported' };
236
+ }
237
+ if (!isFiniteNumber(rec.startedAt) || !isFiniteNumber(rec.endedAt) ||
238
+ rec.startedAt > rec.endedAt) {
239
+ return { ok: false, error: 'recording-bounds-invalid' };
240
+ }
241
+ if (!isRecordObject(rec.meta)) return { ok: false, error: 'recording-meta-invalid' };
242
+ var events = rec.events;
243
+ if (!Array.isArray(events) || events.length === 0) {
244
+ return { ok: false, error: 'recording-events-missing' };
245
+ }
246
+ var previousT = -Infinity;
247
+ var hasSnapshot = false;
248
+ for (var i = 0; i < events.length; i++) {
249
+ var event = events[i];
250
+ if (!isRecordObject(event) || !isFiniteNumber(event.t) ||
251
+ !isEventBody(event.type, event.payload)) {
252
+ return { ok: false, error: 'recording-event-invalid' };
253
+ }
254
+ if (event.t < previousT) return { ok: false, error: 'recording-time-decreasing' };
255
+ previousT = event.t;
256
+ if (isRenderableSnapshot(event.type, event.payload)) hasSnapshot = true;
257
+ }
258
+ if (!hasSnapshot) return { ok: false, error: 'recording-no-snapshot' };
259
+ return { ok: true };
260
+ } catch (err) {
261
+ // A hostile object (a throwing getter or proxy trap) is not a recording.
262
+ return { ok: false, error: 'recording-not-object' };
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Create a recorder: a capture transport that timestamps every message into
268
+ * a portable recording.
269
+ *
270
+ * Retained mode (no onChunk) keeps every event; toRecording(meta) returns
271
+ * the full recording. Chunk mode (onChunk given) retains nothing: every
272
+ * snapshot opens a new keyframe chunk, and a chunk is emitted when it
273
+ * reaches chunkMaxEvents, before an event that would make it span more than
274
+ * chunkMaxMs, or on flush(). onChunk runs synchronously; the recorder
275
+ * updates its own state first, so a throwing onChunk propagates to the
276
+ * caller without corrupting the recorder (capture contains transport
277
+ * throws).
278
+ *
279
+ * @param {RecorderOptions} [options]
280
+ * @returns {Recorder}
281
+ */
282
+ export function createRecorder(options) {
283
+ var cfg = options || {};
284
+
285
+ // Factory-time validation is the only place the recorder throws.
286
+ var now = cfg.now == null ? defaultNow : cfg.now;
287
+ if (typeof now !== 'function') throw new Error('recorder-now-invalid');
288
+ var onChunk = cfg.onChunk == null ? null : cfg.onChunk;
289
+ if (onChunk !== null && typeof onChunk !== 'function') {
290
+ throw new Error('recorder-onchunk-invalid');
291
+ }
292
+ var chunkMaxEvents = cfg.chunkMaxEvents == null
293
+ ? DEFAULT_CHUNK_MAX_EVENTS
294
+ : cfg.chunkMaxEvents;
295
+ if (!isFiniteNumber(chunkMaxEvents) || chunkMaxEvents < 1 ||
296
+ Math.floor(chunkMaxEvents) !== chunkMaxEvents) {
297
+ throw new Error('recorder-chunk-max-events-invalid');
298
+ }
299
+ var chunkMaxMs = cfg.chunkMaxMs == null ? DEFAULT_CHUNK_MAX_MS : cfg.chunkMaxMs;
300
+ if (!isFiniteNumber(chunkMaxMs) || chunkMaxMs <= 0) {
301
+ throw new Error('recorder-chunk-max-ms-invalid');
302
+ }
303
+ var recordReady = cfg.recordReady === true;
304
+
305
+ var retained = []; // retained mode: every event
306
+ var chunk = []; // chunk mode: the open chunk
307
+ var seq = 0; // chunk mode: the next chunk's seq
308
+ var lastT = null; // t of the newest event, or null before the first
309
+ var lastFlushAt = null; // time of the newest flush(), or null
310
+ var identity = null; // { streamSessionId, snapshotId } of the newest snapshot
311
+
312
+ /** A finite clock reading, or null (a throwing clock counts as non-finite). */
313
+ function readNow() {
314
+ var value;
315
+ try {
316
+ value = now();
317
+ } catch (err) {
318
+ return null;
319
+ }
320
+ return isFiniteNumber(value) ? value : null;
321
+ }
322
+
323
+ /** t = max(now(), previous t): a wall-clock step back never decreases t. */
324
+ function stamp() {
325
+ var value = readNow();
326
+ var t;
327
+ if (value === null) {
328
+ t = lastT === null ? 0 : lastT;
329
+ } else {
330
+ t = lastT === null ? value : Math.max(value, lastT);
331
+ }
332
+ lastT = t;
333
+ return t;
334
+ }
335
+
336
+ /** Detach the open chunk and advance seq. The caller hands it to onChunk. */
337
+ function takeChunk() {
338
+ var events = chunk;
339
+ chunk = [];
340
+ var out = {
341
+ seq: seq,
342
+ t0: events[0].t,
343
+ t1: events[events.length - 1].t,
344
+ keyframe: events[0].type === STREAM.SNAPSHOT,
345
+ events: events
346
+ };
347
+ seq += 1;
348
+ return out;
349
+ }
350
+
351
+ function record(type, payload) {
352
+ var event = { t: stamp(), type: type, payload: payload };
353
+ if (!onChunk) {
354
+ retained.push(event);
355
+ return;
356
+ }
357
+ // Place the event BEFORE calling onChunk so a throwing callback never
358
+ // loses it: every state update happens first, then the callbacks run.
359
+ var ready = [];
360
+ if (chunk.length > 0 &&
361
+ (type === STREAM.SNAPSHOT || event.t - chunk[0].t > chunkMaxMs)) {
362
+ ready.push(takeChunk());
363
+ }
364
+ chunk.push(event);
365
+ if (chunk.length >= chunkMaxEvents) ready.push(takeChunk());
366
+ for (var i = 0; i < ready.length; i++) onChunk(ready[i]);
367
+ }
368
+
369
+ /**
370
+ * Capture-facing send. STREAM.READY is dropped unless recordReady. A
371
+ * message whose type is not a non-empty string or whose payload is not an
372
+ * object is not recorded, so recorder output always passes the event
373
+ * shape check. A renderable snapshot updates the tracked identity.
374
+ * @param {string} type
375
+ * @param {Object} payload
376
+ */
377
+ function send(type, payload) {
378
+ if (type === STREAM.READY && !recordReady) return;
379
+ if (!isEventBody(type, payload)) return;
380
+ if (isRenderableSnapshot(type, payload)) {
381
+ identity = {
382
+ streamSessionId: payload.streamSessionId || '',
383
+ snapshotId: payload.snapshotId || 0
384
+ };
385
+ }
386
+ record(type, payload);
387
+ }
388
+
389
+ /**
390
+ * Record the end time (max of now() and the newest event t) and, in chunk
391
+ * mode, emit the open chunk when it holds any event. capture.stop() calls
392
+ * this through transport.flush. Hosts that want timed uploads call it on
393
+ * their own interval.
394
+ */
395
+ function flush() {
396
+ var value = readNow();
397
+ var at = value === null ? (lastT === null ? 0 : lastT) : value;
398
+ if (lastT !== null && at < lastT) at = lastT;
399
+ lastFlushAt = at;
400
+ if (onChunk && chunk.length > 0) onChunk(takeChunk());
401
+ }
402
+
403
+ /**
404
+ * Record an agent overlay against the current snapshot. Mirrors capture's
405
+ * overlay rule (E1): glow and progress default to null and the identity
406
+ * keys are assigned LAST, so an input can never spoof the stream identity.
407
+ * The input object is never mutated.
408
+ * @param {Object} payload
409
+ * @returns {boolean}
410
+ */
411
+ function overlay(payload) {
412
+ if (!identity) return false;
413
+ var body = Object.assign(
414
+ { glow: null, progress: null },
415
+ isRecordObject(payload) ? payload : {},
416
+ { streamSessionId: identity.streamSessionId, snapshotId: identity.snapshotId }
417
+ );
418
+ body.glow = body.glow || null;
419
+ body.progress = body.progress || null;
420
+ record(STREAM.OVERLAY, body);
421
+ return true;
422
+ }
423
+
424
+ /**
425
+ * Record a host timeline mark { kind, ...data }. kind is stamped last so
426
+ * data.kind cannot override it, and the payload is a JSON clone (functions
427
+ * and undefined values drop). Allowed before the first snapshot.
428
+ * @param {string} kind
429
+ * @param {Object} [data]
430
+ * @returns {boolean} false, recording nothing, for an empty kind or data
431
+ * that cannot be serialized (a cycle or a BigInt)
432
+ */
433
+ function mark(kind, data) {
434
+ if (typeof kind !== 'string' || kind === '') return false;
435
+ var payload;
436
+ try {
437
+ payload = JSON.parse(JSON.stringify(
438
+ Object.assign({}, isRecordObject(data) ? data : {}, { kind: kind })
439
+ ));
440
+ } catch (err) {
441
+ return false;
442
+ }
443
+ if (!isEventBody(HOST_MARK_TYPE, payload) || payload.kind !== kind) return false;
444
+ record(HOST_MARK_TYPE, payload);
445
+ return true;
446
+ }
447
+
448
+ function getIdentity() {
449
+ return identity
450
+ ? { streamSessionId: identity.streamSessionId, snapshotId: identity.snapshotId }
451
+ : null;
452
+ }
453
+
454
+ /**
455
+ * The retained recording: startedAt is the first event's t, endedAt the
456
+ * newest flush time (or now() when never flushed), never below the last
457
+ * event's t. Returns null in chunk mode, where hosts rebuild a recording
458
+ * with createRecording({ events: chunks.flatMap((c) => c.events) }).
459
+ * @param {Object} [meta]
460
+ * @returns {Recording|null}
461
+ */
462
+ function toRecording(meta) {
463
+ if (onChunk) return null;
464
+ var events = retained.slice();
465
+ var end = lastFlushAt;
466
+ if (end === null) {
467
+ var value = readNow();
468
+ end = value === null ? (lastT === null ? 0 : lastT) : value;
469
+ }
470
+ if (lastT !== null && end < lastT) end = lastT;
471
+ return createRecording({
472
+ events: events,
473
+ meta: meta,
474
+ startedAt: events.length ? events[0].t : end,
475
+ endedAt: end
476
+ });
477
+ }
478
+
479
+ return {
480
+ transport: { send: send, flush: flush },
481
+ mark: mark,
482
+ overlay: overlay,
483
+ identity: getIdentity,
484
+ flush: flush,
485
+ toRecording: toRecording
486
+ };
487
+ }
@@ -15,6 +15,7 @@ Module split (the seams jsdom forces — see Environment):
15
15
  ```
16
16
  snapshot.js buildSnapshotHtml(payload) -> string pure srcdoc builder
17
17
  diff.js applyMutations(doc, ops, counters, hooks) Document-parameterized applier
18
+ parser-safe.js restoreParserSafePlaceholders(root, options) parser-safe placeholder restore
18
19
  overlays.js createOverlays / mapRectToHost / OVERLAY_CSS
19
20
  index.js createViewer factory + barrel re-exports of all of the above
20
21
  ```
@@ -25,7 +26,8 @@ index.js createViewer factory + barrel re-exports of all of the above
25
26
  import { createViewer } from '@full-self-browsing/phantom-stream/renderer';
26
27
 
27
28
  const viewer = createViewer({ container, transport, logger });
28
- // -> { detach, destroy, registerOverlay, on, resolveNode, highlightNode, clearHighlight, requestSubtree }
29
+ // -> { detach, destroy, clearHighlight, getViewportMapping, highlightNode, on,
30
+ // registerOverlay, requestSubtree, resolveNode, handleSnapshot }
29
31
  ```
30
32
 
31
33
  Calling the factory auto-attaches a live mirror: the viewer root (stamped
@@ -105,12 +107,23 @@ streaming.
105
107
  safe after `detach()`.
106
108
  - `registerOverlay(kind, renderFn)` — register a custom overlay kind (the
107
109
  host-facing extension seam, below).
110
+ - `getViewportMapping()` — return cloned `scale`, `viewport`, and
111
+ `container` geometry so host-owned input overlays can map host points to
112
+ capture-page coordinates. It never exposes mirrored content.
108
113
  - `on(eventName, handler)` — subscribe to host-facing events. Supports
109
- `state` and `health`, immediately calls the handler with the current
110
- snapshot of that event, and returns an unsubscribe function. Unknown event
111
- names throw `Error('viewer-event-unsupported')` at subscription time.
114
+ `state`, `health`, and `loaded`, and returns an unsubscribe function.
115
+ `state` and `health` immediately call the handler with the current value
116
+ of that event; `loaded` never replays loads that happened before the
117
+ subscription. Unknown event names, or a handler that is not a function,
118
+ throw `Error('viewer-event-unsupported')` at subscription time.
112
119
  The viewer emits events only; visible badges, banners, logs, and status
113
120
  UI belong to the host application.
121
+ - `handleSnapshot(payload)` — the host-driven snapshot entry point. It
122
+ accepts a bare `SnapshotPayload` or a `{ type, payload }` envelope and
123
+ behaves exactly like the `STREAM.SNAPSHOT` dispatch target: the new
124
+ identity is adopted synchronously, and the mirror document loads later
125
+ (subscribe to `loaded` to learn when it is ready). Viewers created with
126
+ the `mount` alias need no transport and render through this call.
114
127
  - `resolveNode(nid)` — resolve a PhantomStream nid through the viewer's
115
128
  internal identity index. Returns a fresh geometry/identity object
116
129
  (`nid`, `exists`, `rect`, `streamSessionId`, `snapshotId`) or `null` for
@@ -122,7 +135,10 @@ streaming.
122
135
  - `clearHighlight()` — remove the local semantic highlight. Idempotent.
123
136
  - `requestSubtree(nid, options?)` — ask capture for one missing or truncated
124
137
  subtree. Returns a generated request id when the nid is current and no
125
- request for that nid is already in flight, otherwise `null`. Requests carry
138
+ request for that nid is already in flight, otherwise `null`. The reserved
139
+ `BODY_NID` always returns `null`: the body is a structural anchor, not a
140
+ recoverable subtree (hosts call capture `stop()` then `start()` for a full
141
+ refresh). Requests carry
126
142
  the active `streamSessionId`/`snapshotId`; stale, miss, and mismatched
127
143
  `STREAM.SUBTREE_RESPONSE` frames are ignored softly and clear only their
128
144
  matching latch.
@@ -135,6 +151,15 @@ the index from their own `nodeIds` sidecars, and remove ops delete the removed
135
151
  subtree before it leaves the mirror. A paired `WeakMap<Node, nid>` is kept
136
152
  only for internal cleanup; neither map is exposed to hosts.
137
153
 
154
+ When a snapshot carries `bodyNid` (the reserved `BODY_NID`, stamped by
155
+ captures since quick task 261127-u5c), the mirror `<body>` is indexed under
156
+ it after sidecar pairing, unless that nid is already paired, so body-level
157
+ add ops (`parentNid: BODY_NID`) and body attr ops resolve like any other
158
+ nid. Sidecar pairing stays authoritative for a non-conforming payload that
159
+ reuses a paired nid. Payloads without `bodyNid` index exactly as before; a
160
+ body-level op against them soft-fails as a stale miss and recovers through
161
+ the normal resync path.
162
+
138
163
  Diff application receives identity hooks from `createViewer`. `diff.js` does
139
164
  not own an identity selector fallback, and normal nid-addressed ops do not use
140
165
  per-op `querySelector` lookup. Overlay anchor resolution, `resolveNode`, and
@@ -191,6 +216,37 @@ Stale, gone, skipped, blocked, untracked, or mismatched responses do not mutate
191
216
  the mirror. The latch is bounded so one missing region cannot create request
192
217
  storms.
193
218
 
219
+ ### Parser-safe placeholders
220
+
221
+ Capture renames elements whose nesting HTML text cannot express (a button
222
+ inside a button, a link inside a link, a div inside a paragraph, a row without
223
+ a tbody) to `<ps-node data-ps-tag="original-tag">`, so the parse keeps the tree
224
+ and the positional `nodeIds` pairing. `restoreParserSafePlaceholders(root,
225
+ options)` in `parser-safe.js` turns them back into their tags right after EVERY
226
+ parse, before `sanitizeFragment` and identity pairing: the snapshot `load`
227
+ handler, `installOneShadowRoot`, the frame document index, subtree responses,
228
+ the shadow-root replacement in `diff.js`, and every ADD op. Restored elements
229
+ therefore always pass through the post-parse scrub and the asset gate.
230
+
231
+ Only button, a, form, nobr, p, h1-h6, li, dd, dt, option, optgroup, select,
232
+ textarea, xmp, plaintext, img, input, br, hr, wbr, area, col, source, track,
233
+ table, tbody, thead, tfoot, tr, td, th, caption and colgroup are restored.
234
+ script, iframe, object, embed, style, link, meta, base, html, head, body,
235
+ frameset and any other tag stay inert generic `<ps-node>` elements. In the two
236
+ live documents (the snapshot mirror and same-origin frame mirrors) a restored
237
+ img, input, source or track gets its `src`, `srcset` and `data-ps-currentsrc`
238
+ only through the viewer's asset gate, because the string-layer gate never scans
239
+ `<ps-node>` and a live `<img>` fetches as soon as its `src` is set. Template
240
+ parses are inert and are gated before `importNode`, as before.
241
+
242
+ An ADD op whose parent is an SVG element (other than `foreignObject`, `desc`
243
+ or `title`) parses inside an `<svg>` wrapper, and one under a MathML element
244
+ (other than `mi`, `mo`, `mn`, `ms`, `mtext` or `annotation-xml`) inside a
245
+ `<math>` wrapper, so `<clipPath>` or `<linearGradient>` keep the SVG namespace.
246
+ When the wrapper yields no element (an HTML breakout tag such as `<div>`), the
247
+ op parses again without it. The wrapper also fixes add ops in recordings made
248
+ before this change.
249
+
194
250
  ## Phase 9 CSSOM reconstruction
195
251
 
196
252
  When capture runs with `styleMode: 'cssom'`, snapshots and scoped sidecars may
@@ -210,6 +266,12 @@ selector fallback. The op contract is
210
266
  `action: 'upsert' | 'replace' | 'remove'`; upsert/replace carry a sanitized
211
267
  `source`, while remove only needs the `sourceId` and `scope`.
212
268
 
269
+ Installed nodes also carry `data-ps-style-order` (the source's `order`).
270
+ Capture sends only the sources that changed, so the renderer keeps cascade
271
+ order itself: a replace swaps the node in place, and a new source is inserted
272
+ before the first source in the same root with a greater order (or appended
273
+ when there is none).
274
+
213
275
  CSS text always routes through `scrubCssText` before insertion, matching the
214
276
  snapshot CSP and sandbox contract. If the scope cannot be resolved, or the
215
277
  viewer receives a style-source op before the matching document/shadow/frame is
@@ -255,6 +317,31 @@ Health snapshots are privacy-bounded telemetry. They include:
255
317
  Health snapshots never include mirrored `html`, text node contents, raw
256
318
  payload objects, page `url`, page `title`, or DOM nodes.
257
319
 
320
+ ### `loaded`
321
+
322
+ ```js
323
+ const offLoaded = viewer.on('loaded', (event) => {
324
+ // event is exactly { streamSessionId, snapshotId }: the identity of the
325
+ // snapshot whose mirror document just finished loading.
326
+ });
327
+ ```
328
+
329
+ `loaded` fires after each snapshot's mirror document finishes loading, once
330
+ per loaded document, after the viewer has started streaming that document
331
+ (the mirror is already un-hidden when handlers run). The bare `about:blank`
332
+ load before any snapshot never fires it. The payload is the viewer's active
333
+ identity at load time, `{ streamSessionId, snapshotId }`, and each handler
334
+ receives its own copy. It does **not** replay: a handler subscribed after a
335
+ load never hears about that load. Handler errors are contained to the
336
+ logger, and `destroy()` drops every subscription.
337
+
338
+ It exists for hosts that sequence work against the new document. A snapshot
339
+ adopts its identity synchronously, but its document loads later, and
340
+ mutations that arrive before the load are dropped (see Known remaining
341
+ behaviors). A host that drives snapshots itself waits for `loaded` before
342
+ sending that snapshot's mutations; the playback player does exactly this
343
+ on every seek.
344
+
258
345
  ## Overlay channel contract (VIEW-04)
259
346
 
260
347
  `STREAM.OVERLAY` payloads dispatch through one kind-keyed registry: **every
@@ -323,7 +410,7 @@ are pinned end-to-end by `tests/renderer-loopback.test.js`.
323
410
  ## Divergence ledger
324
411
 
325
412
  Phase 1 discipline: every intentional departure from the reference viewer is
326
- explicit, never accidental. Entries R1-R12; "drop" means FSB dashboard
413
+ explicit, never accidental. Entries R1-R13; "drop" means FSB dashboard
327
414
  chrome removed, "divergence" means changed behavior, "reconstruction" means
328
415
  parity values rebuilt from documentation because the source asset is not
329
416
  vendored.
@@ -386,6 +473,17 @@ vendored.
386
473
  un-hide). Relatedly, the viewer stays `streaming` across re-snapshots
387
474
  (reference parity): mutations carrying the new identity apply without
388
475
  waiting for a new load event.
476
+ - **R13 — The mirror `<body>` is indexed under the snapshot `bodyNid`.** The
477
+ reference viewer's mirror body never carried a nid, so body-level ops had
478
+ nothing to resolve against (and the reference capture never sent them).
479
+ The viewer now indexes the mirror body under the snapshot's reserved
480
+ `bodyNid` after sidecar pairing, never shadowing a paired nid, so direct
481
+ body children (toasts, modals, portals) and body attribute changes apply;
482
+ `requestSubtree(BODY_NID)` returns `null`. Snapshots without `bodyNid`
483
+ index exactly as before. Because body-level additions now stream, a
484
+ same-page host that mounts UI directly under `<body>` must exclude it with
485
+ the recursion guard predicate above (quick task 261127-u5c; capture README
486
+ E5; differential ledger D28).
389
487
 
390
488
  ## Phase 3 security behavior
391
489
 
@@ -416,7 +514,9 @@ The Phase 3 security pipeline is always on and documented in
416
514
  between the srcdoc write and the load event are dropped (the reference
417
515
  gates on streaming state). The miss accounting + `CONTROL.START` resync
418
516
  self-heals any resulting drift; do not write tests that assume zero loss
419
- before the first load.
517
+ before the first load. Hosts that drive snapshots themselves (through
518
+ `handleSnapshot` or a private transport) wait for the `loaded` event
519
+ before sending that snapshot's mutations, so nothing is lost.
420
520
 
421
521
  ## Environment
422
522
 
@@ -436,7 +536,10 @@ The Phase 3 security pipeline is always on and documented in
436
536
  `cd.open(); cd.write(iframe.srcdoc); cd.close();` — after which diff
437
537
  applies hit the written document because the viewer reads
438
538
  `contentDocument` fresh per message (see
439
- `tests/renderer-loopback.test.js`). Real browsers parse srcdoc natively;
539
+ `tests/renderer-loopback.test.js`). `cd.close()` already makes jsdom fire
540
+ one asynchronous load on the iframe. Dispatching another load by hand
541
+ makes the viewer re-pair its identity index against a mirror that may
542
+ already be mutated, so new tests rely on the close-fired load alone. Real browsers parse srcdoc natively;
440
543
  visual parity and real-browser srcdoc rendering are verified manually via
441
544
  the loopback demo.
442
545
  - Running the test suite requires Node >= 20.19 (jsdom 29 engines floor);