@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.
@@ -50,13 +50,28 @@ function buildPlaywrightInjectSource(options) {
50
50
  );
51
51
  }
52
52
 
53
+ // Only JSON-safe, supported capture options reach the injected artifact:
54
+ // styleMode (first, when 'cssom'), then the quick task 261202-jwf budget
55
+ // options when each is a positive finite number. Anything else is dropped,
56
+ // so the defaults stay {}.
53
57
  function normalizeCaptureOptions(options) {
54
58
  var opts = options || {};
55
59
  var captureOptions = opts.captureOptions || {};
60
+ var normalized = {};
56
61
  if (captureOptions && captureOptions.styleMode === 'cssom') {
57
- return { styleMode: 'cssom' };
62
+ normalized.styleMode = 'cssom';
58
63
  }
59
- return {};
64
+ if (isPositiveFiniteNumber(captureOptions && captureOptions.messageLimitBytes)) {
65
+ normalized.messageLimitBytes = captureOptions.messageLimitBytes;
66
+ }
67
+ if (isPositiveFiniteNumber(captureOptions && captureOptions.snapshotBudgetBytes)) {
68
+ normalized.snapshotBudgetBytes = captureOptions.snapshotBudgetBytes;
69
+ }
70
+ return normalized;
71
+ }
72
+
73
+ function isPositiveFiniteNumber(value) {
74
+ return typeof value === 'number' && isFinite(value) && value > 0;
60
75
  }
61
76
 
62
77
  /**
@@ -39,6 +39,8 @@ const capture = createCapture({
39
39
  | `maskTextFn` / `maskInputFn` | no | asterisk mask | Custom masking functions. They are fail-closed: thrown errors are logged and the default mask is used. |
40
40
  | `styleMode` | no | `'computed'` | <code>'computed' &#124; 'cssom'</code> — default mode preserves the legacy curated computed-style snapshot path. CSSOM mode omits generated computed inline styles and transports scoped `styleSources[]` plus `styleStrategy` instead. |
41
41
  | `fetchStylesheet` | no | `null` | Optional synchronous hook used only by CSSOM mode when a stylesheet cannot expose readable `cssRules` and cannot be safely re-linked. Called as `fetchStylesheet({ href, scope, ownerKind })`; PhantomStream never performs hidden network fetches. |
42
+ | `messageLimitBytes` | no | `RELAY_PER_MESSAGE_LIMIT_BYTES` (1 MiB) | The largest wire message this capture emits, in UTF-8 bytes of the JSON payload. It governs the snapshot hard reset, single mutation diffs, mutation chunking, and subtree responses. Positive finite numbers only; any other value is ignored. Relay users keep the default, because the relay drops messages over 1 MiB. Local recorders that never send through a relay, such as FSB, pass a larger value (FSB uses 8 MiB). The Playwright adapter forwards it through `captureOptions`. |
43
+ | `snapshotBudgetBytes` | no | `floor(messageLimitBytes * 0.8)` | The budget the snapshot truncation passes and sidecar pruning aim for, in UTF-8 wire bytes, clamped to at most `messageLimitBytes`. Positive finite numbers only; any other value is ignored. Relay users keep the default. Local recorders pass a larger value so large pages keep every stylesheet (FSB uses 4 MiB). The Playwright adapter forwards it through `captureOptions`. |
42
44
 
43
45
  A readiness ping (`STREAM.READY`) is emitted once, at factory creation
44
46
  (divergence-ledger entry D3 — the reference pinged at script-load time).
@@ -100,6 +102,22 @@ const nid = capture.getNodeId(element);
100
102
  non-elements, and disconnected elements. It is the capture-side bridge for
101
103
  semantic addressing; it exposes identity only, never mirrored content.
102
104
 
105
+ The main document `<body>` itself never enters the `nodeIds` sidecar (the
106
+ serializer starts below it), so capture addresses it with the reserved
107
+ `BODY_NID` from the protocol module. Every main snapshot carries `bodyNid`
108
+ set to `BODY_NID`, a non-numeric value outside the nid counter, so `nodeIds`
109
+ numbering is unchanged. Elements appended or inserted directly under
110
+ `<body>` (toasts, modals, portals) stream as add ops with
111
+ `parentNid: BODY_NID`, with `beforeNid` resolved exactly as for any other
112
+ parent, and `<body>` attribute changes stream as attr ops on `BODY_NID`
113
+ except `style`: the snapshot's computed shell `bodyStyle` owns the mirror
114
+ body's style. Bare text directly under `<body>` still drops, because a text
115
+ op applies as `textContent =` and would flatten the whole mirror body.
116
+ `BODY_NID` is a structural anchor, not an addressable element:
117
+ `getNodeId(document.body)` stays `null`, and a subtree request for it is
118
+ answered content-free as `untracked`. Same-origin frame documents are
119
+ unchanged and keep their counter `htmlNid`/`bodyNid`.
120
+
103
121
  ## Phase 8 fidelity surfaces
104
122
 
105
123
  Open shadow roots, same-origin iframes, live form values, late-added computed
@@ -179,6 +197,51 @@ add-op serialization policy: sanitized HTML, masking, URL absolutification,
179
197
  curated styles, `nodeIds`, `shadowRoots[]`, and `frames[]`. Miss responses are
180
198
  content-free and clear the request path without exposing page data.
181
199
 
200
+ ### Parser-safe serialization
201
+
202
+ A DOM built by scripts can hold nesting that HTML text cannot express. Parsing
203
+ the serialized markup again rewrites it: a `<button>` inside a `<button>` closes
204
+ the outer one, an `<a>` inside an `<a>` is split, a `<div>` closes an open
205
+ `<p>`, and a bare `<tr>` gets an implied `<tbody>`. On x.com this moved the
206
+ sidebar column out of `<main>`, and every change of element count misaligned the
207
+ positional `nodeIds` pairing, so later ops hit the wrong nodes.
208
+
209
+ Capture therefore renames such elements in each detached wire clone to
210
+ `<ps-node data-ps-tag="original-tag">` placeholders (`PARSER_SAFE_TAG` and
211
+ `PARSER_SAFE_TAG_ATTR` in `src/protocol/messages.js`). A placeholder takes the
212
+ element's attributes, children, position and node id, so element order and
213
+ count stay the same and the sidecar stays aligned. The viewer restores the
214
+ original tags right after its parse. The rule families, applied to
215
+ HTML-namespace elements only (renaming too much is harmless):
216
+
217
+ - `button`, `a`, `form` or `nobr` inside an ancestor with the same tag;
218
+ - every `p` that contains a block element which would close it;
219
+ - a heading directly inside a heading;
220
+ - an `li` (or `dd`/`dt`) that reaches another `li` (or `dd`/`dt`) before a
221
+ special element other than `address`, `div` or `p`;
222
+ - `option`/`optgroup` inside an `option`, `optgroup` inside an `optgroup`, and
223
+ a `select` holding anything other than `option`, `optgroup`, `hr`, `script`
224
+ or `template`;
225
+ - `textarea`, `xmp` or `plaintext` with element children, and a void element
226
+ (`img`, `input`, `br`, `hr`, `wbr`, `area`, `col`, `source`, `track`) with
227
+ child nodes;
228
+ - a table the parser would restructure (renamed with all its table parts,
229
+ stopping at nested tables), and stray table parts whose parent cannot hold
230
+ them; the root of an add op or subtree response is exempt from the stray rule,
231
+ because the viewer's `<template>` parse accepts table parts there;
232
+ - `html`, `head`, `body` or `frameset` inside the clone.
233
+
234
+ `neutralizeParserHostileNesting` runs at all five serialization sites: the
235
+ `serializeDOM` body clone, shadow-root payloads, same-origin frame bodies,
236
+ add-op clones, and subtree responses (which reuse the add-op path). It runs
237
+ after each site's last `sanitizeForWire` call, so masking and the URL and
238
+ handler strips always see the original tags; it is a structural rename, never a
239
+ scrub. Capture also removes `data-ps-tag` from page-owned `<ps-node>` elements,
240
+ so a page cannot ask the viewer to create a tag. Viewers older than 0.3.0 show
241
+ the placeholders as generic elements: structure and node pairing stay intact,
242
+ only the original tag is lost. The inject bundle mirrors the pass, pinned by
243
+ `tests/inject-value-parity.test.js`.
244
+
182
245
  ## Phase 9 CSSOM style mode
183
246
 
184
247
  `styleMode: 'computed' | 'cssom'` controls how visual style fidelity is
@@ -210,9 +273,25 @@ Stylesheet fallback reasons are explicit and wire-visible:
210
273
 
211
274
  Live stylesheet changes stream as `DIFF_OP.STYLE_SOURCE` ops with
212
275
  `action: 'upsert' | 'replace' | 'remove'`. The payload is scoped the same way
213
- as snapshots. `CSSStyleSheet.insertRule` / `deleteRule` / `replaceSync` are
276
+ as snapshots. Only sources that changed are sent: capture keeps a per-session
277
+ fingerprint of each source the viewer holds (owner kind, order, href, media,
278
+ disabled, plus the length and a 32-bit FNV-1a hash of the sanitized CSS text),
279
+ seeded from every emitted snapshot after budget pruning. A source whose
280
+ fingerprint matches is skipped, and a `remove` goes out only for a source the
281
+ viewer holds. `CSSStyleSheet.insertRule` / `deleteRule` / `replaceSync` are
214
282
  patched while streaming in CSSOM mode; if a hook cannot be installed, capture
215
283
  logs `cssom-hook-unavailable` and sends a fresh snapshot rather than guessing.
284
+ The patched methods cannot see rules the page adds from another JavaScript
285
+ world, such as page `insertRule` calls when capture runs in an extension's
286
+ isolated world. Each flush therefore compares a cheap per-scope signature
287
+ (sheet identity, `cssRules.length`, disabled, media and href for each
288
+ stylesheet) and re-collects a scope only when the signature changed. A full
289
+ re-collect runs at most every 2000 ms (`STYLE_FULL_RECONCILE_MS`) to catch
290
+ edits that keep the rule count; the fingerprints dedupe it, so it sends nothing
291
+ unless something changed. When a snapshot had to drop style sources to fit its
292
+ budget, the dropped sources go out as style-source ops in the next flush. A
293
+ style owner added after the snapshot reconciles the scope it lives in; capture
294
+ sends a fresh snapshot only when no known scope matches.
216
295
  If a known style owner cannot be reconciled, the op carries
217
296
  `cssom-style-source-stale` so the renderer can request recovery. Renderer-side
218
297
  scope misses surface as `stale-style-scope`.
@@ -294,6 +373,22 @@ divergence, so it lives here rather than in the differential ledger):
294
373
  snapshots and add ops. The observed page is no longer mutated for
295
374
  framework identity, page-owned `data-fsb-nid` remains page data, and
296
375
  `getNodeId(element) -> string|null` is the public live-element lookup.
376
+ - **E5 (quick task 261127-u5c, fidelity fix)** — body-level mutations: the
377
+ reference resolves add-op parents and attr targets through dataset nid
378
+ reads, and `<body>` never carries one, so elements appended directly to
379
+ the body (toasts, modals, portals) and attribute changes on the body were
380
+ dropped with no op, no stale miss, and no resync. Capture now addresses
381
+ the main body as the reserved `BODY_NID` (see "Node identity and semantic
382
+ addressing" above): direct body children emit add ops with
383
+ `parentNid: BODY_NID` (beforeNid resolution unchanged), and body attribute
384
+ changes emit attr ops on `BODY_NID` except `style`. Bare body text keeps
385
+ the drop, and frames are unchanged. Host UI placed directly under the body
386
+ now streams too, so same-page hosts exclude it with `skipElement`, exactly
387
+ as the viewer root already requires. Ledgered as **D28** in
388
+ `tests/differential/divergence-ledger.js`: `D28-body-level-mutations`
389
+ (mismatch, pinned by the `body-level-mutations` oracle scenario) and
390
+ `D28-body-nid-snapshot-key` (documented mapping for the new snapshot key),
391
+ and covered end-to-end in `tests/renderer-loopback.test.js`.
297
392
 
298
393
  ## Environment
299
394