@full-self-browsing/phantom-stream 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 +263 -0
- package/bin/phantom-stream.js +193 -0
- package/dist/types/adapters/bookmarklet.d.ts +22 -0
- package/dist/types/adapters/bookmarklet.d.ts.map +1 -0
- package/dist/types/adapters/browser-inject.d.ts +7 -0
- package/dist/types/adapters/browser-inject.d.ts.map +1 -0
- package/dist/types/adapters/extension.d.ts +43 -0
- package/dist/types/adapters/extension.d.ts.map +1 -0
- package/dist/types/adapters/playwright-inject.d.ts +2 -0
- package/dist/types/adapters/playwright-inject.d.ts.map +1 -0
- package/dist/types/adapters/playwright.d.ts +14 -0
- package/dist/types/adapters/playwright.d.ts.map +1 -0
- package/dist/types/capture/index.d.ts +241 -0
- package/dist/types/capture/index.d.ts.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/protocol/constants.d.ts +35 -0
- package/dist/types/protocol/constants.d.ts.map +1 -0
- package/dist/types/protocol/envelope.d.ts +41 -0
- package/dist/types/protocol/envelope.d.ts.map +1 -0
- package/dist/types/protocol/index.d.ts +5 -0
- package/dist/types/protocol/index.d.ts.map +1 -0
- package/dist/types/protocol/messages.d.ts +520 -0
- package/dist/types/protocol/messages.d.ts.map +1 -0
- package/dist/types/protocol/remote-control.d.ts +70 -0
- package/dist/types/protocol/remote-control.d.ts.map +1 -0
- package/dist/types/relay/backends/ws.d.ts +39 -0
- package/dist/types/relay/backends/ws.d.ts.map +1 -0
- package/dist/types/relay/index.d.ts +4 -0
- package/dist/types/relay/index.d.ts.map +1 -0
- package/dist/types/relay/limits.d.ts +54 -0
- package/dist/types/relay/limits.d.ts.map +1 -0
- package/dist/types/relay/relay.d.ts +73 -0
- package/dist/types/relay/relay.d.ts.map +1 -0
- package/dist/types/renderer/diff.d.ts +62 -0
- package/dist/types/renderer/diff.d.ts.map +1 -0
- package/dist/types/renderer/index.d.ts +211 -0
- package/dist/types/renderer/index.d.ts.map +1 -0
- package/dist/types/renderer/overlays.d.ts +166 -0
- package/dist/types/renderer/overlays.d.ts.map +1 -0
- package/dist/types/renderer/sanitize.d.ts +73 -0
- package/dist/types/renderer/sanitize.d.ts.map +1 -0
- package/dist/types/renderer/snapshot.d.ts +41 -0
- package/dist/types/renderer/snapshot.d.ts.map +1 -0
- package/dist/types/transport/websocket.d.ts +44 -0
- package/dist/types/transport/websocket.d.ts.map +1 -0
- package/docs/ARCHITECTURE.md +273 -0
- package/docs/DESIGN-HISTORY.md +120 -0
- package/docs/QUICKSTARTS.md +289 -0
- package/docs/RELEASE.md +60 -0
- package/docs/SECURITY.md +156 -0
- package/docs/paper/OUTLINE.md +100 -0
- package/examples/bookmarklet-demo/demo.css +102 -0
- package/examples/bookmarklet-demo/server.js +297 -0
- package/examples/bookmarklet-demo/source.html +52 -0
- package/examples/bookmarklet-demo/viewer.html +48 -0
- package/examples/extension-mv3/demo.css +102 -0
- package/examples/extension-mv3/server.js +350 -0
- package/examples/extension-mv3/source.html +48 -0
- package/examples/extension-mv3/viewer.html +48 -0
- package/examples/loopback-mirror.html +369 -0
- package/examples/loopback-transport.js +65 -0
- package/examples/playwright-demo/demo.css +462 -0
- package/examples/playwright-demo/fixture.html +56 -0
- package/examples/playwright-demo/fixture.js +57 -0
- package/examples/playwright-demo/server.js +517 -0
- package/examples/playwright-demo/viewer.html +112 -0
- package/examples/playwright-demo/viewer.js +414 -0
- package/examples/serve.js +97 -0
- package/examples/two-tab-demo/demo.css +266 -0
- package/examples/two-tab-demo/server.js +233 -0
- package/examples/two-tab-demo/source.html +70 -0
- package/examples/two-tab-demo/source.js +213 -0
- package/examples/two-tab-demo/viewer.html +72 -0
- package/examples/two-tab-demo/viewer.js +121 -0
- package/package.json +107 -0
- package/src/adapters/bookmarklet.js +98 -0
- package/src/adapters/browser-inject.js +17 -0
- package/src/adapters/extension.js +322 -0
- package/src/adapters/playwright-inject.js +4401 -0
- package/src/adapters/playwright.js +540 -0
- package/src/capture/README.md +302 -0
- package/src/capture/index.js +4361 -0
- package/src/index.js +5 -0
- package/src/protocol/constants.js +49 -0
- package/src/protocol/envelope.js +75 -0
- package/src/protocol/index.js +4 -0
- package/src/protocol/messages.js +268 -0
- package/src/protocol/remote-control.js +300 -0
- package/src/relay/README.md +22 -0
- package/src/relay/backends/ws.js +186 -0
- package/src/relay/index.js +3 -0
- package/src/relay/limits.js +105 -0
- package/src/relay/relay.js +397 -0
- package/src/renderer/README.md +443 -0
- package/src/renderer/diff.js +389 -0
- package/src/renderer/index.js +1401 -0
- package/src/renderer/overlays.js +528 -0
- package/src/renderer/sanitize.js +366 -0
- package/src/renderer/snapshot.js +202 -0
- package/src/transport/websocket.js +553 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
# renderer
|
|
2
|
+
|
|
3
|
+
Viewer-side reconstruction: sandboxed-iframe snapshot render + nid-addressed
|
|
4
|
+
diff apply behind an injected `ViewerTransport` seam. Extraction of the FSB
|
|
5
|
+
reference viewer's stream plumbing (`reference/dashboard/dashboard.js`,
|
|
6
|
+
shipped as FSB milestone v0.9.9.1 — identity guard and resync at lines
|
|
7
|
+
185-278, snapshot/scale at 2723-2869, resize wiring at 3194-3207,
|
|
8
|
+
mutation/scroll/overlay/dialog handlers at 3209-3443), with the FSB
|
|
9
|
+
dashboard chrome dropped and every intentional departure recorded in the
|
|
10
|
+
divergence ledger below (Phase 2; the parity bar is behavioral equivalence
|
|
11
|
+
of the stream path, not the dashboard UI around it).
|
|
12
|
+
|
|
13
|
+
Module split (the seams jsdom forces — see Environment):
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
snapshot.js buildSnapshotHtml(payload) -> string pure srcdoc builder
|
|
17
|
+
diff.js applyMutations(doc, ops, counters, hooks) Document-parameterized applier
|
|
18
|
+
overlays.js createOverlays / mapRectToHost / OVERLAY_CSS
|
|
19
|
+
index.js createViewer factory + barrel re-exports of all of the above
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Factory
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
import { createViewer } from '@full-self-browsing/phantom-stream/renderer';
|
|
26
|
+
|
|
27
|
+
const viewer = createViewer({ container, transport, logger });
|
|
28
|
+
// -> { detach, destroy, registerOverlay, on, resolveNode, highlightNode, clearHighlight, requestSubtree }
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Calling the factory auto-attaches a live mirror: the viewer root (stamped
|
|
32
|
+
`data-phantomstream-ui="viewer"`), one injected `<style>` element carrying
|
|
33
|
+
`OVERLAY_CSS`, the sandboxed mirror iframe (hidden until the first snapshot
|
|
34
|
+
loads), and the host-document overlay layer. The first `STREAM.SNAPSHOT`
|
|
35
|
+
that arrives renders; everything after streams.
|
|
36
|
+
|
|
37
|
+
| Option | Required | Default | Purpose |
|
|
38
|
+
|--------|----------|---------|---------|
|
|
39
|
+
| `container` | yes | — | Host element the viewer root is appended into. The viewer always fills its container (layout is the host's job — ledger entry R1). The factory throws `Error('viewer-container-required')` otherwise. |
|
|
40
|
+
| `transport` | yes | — | `ViewerTransport` (below). The factory throws `Error('viewer-transport-required')` when `send` or `onMessage` is not a function. |
|
|
41
|
+
| `logger` | no | console-backed (`info`/`warn`/`error`) | Receives every contained error and health warning (`'[Renderer]'` prefix): diff-apply misses, transport send failures, unknown overlay kinds, nid-rect resolution failures. |
|
|
42
|
+
|
|
43
|
+
Factory-time validation is the **only** place this module throws
|
|
44
|
+
(`viewer-container-required`, `viewer-transport-required`,
|
|
45
|
+
`viewer-sandbox-invalid`); after creation every error routes to the injected
|
|
46
|
+
logger.
|
|
47
|
+
|
|
48
|
+
## Transport contract
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
/**
|
|
52
|
+
* @typedef {Object} ViewerTransport
|
|
53
|
+
* @property {(type: string, payload: Object) => void} send
|
|
54
|
+
* Viewer -> capture host (CONTROL.* messages). Fire-and-forget; errors
|
|
55
|
+
* are contained to the logger.
|
|
56
|
+
* @property {(handler: (type: string, payload: Object) => void) => (() => void)} onMessage
|
|
57
|
+
* Subscribe to capture-host -> viewer (STREAM.*) messages. Returns an
|
|
58
|
+
* unsubscribe function; detach() invokes it.
|
|
59
|
+
*/
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
This mirrors the capture `Transport`'s fire-and-forget `send` and adds the
|
|
63
|
+
receive side. Phase 4's WebSocket transport implements the same interface by
|
|
64
|
+
encoding/decoding envelopes — the viewer never changes. For a zero-
|
|
65
|
+
infrastructure same-page wiring, a loopback transport implements both ends
|
|
66
|
+
(this is the pattern `tests/renderer-loopback.test.js` and the
|
|
67
|
+
`examples/loopback-mirror.html` demo use):
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
function createLoopbackTransport() {
|
|
71
|
+
const toViewer = new Set(); // STREAM.* handlers (viewer subscribes)
|
|
72
|
+
const toHost = new Set(); // CONTROL.* handlers (host glue subscribes)
|
|
73
|
+
const fanOut = (handlers, type, payload) =>
|
|
74
|
+
queueMicrotask(() => handlers.forEach((h) => h(type, payload)));
|
|
75
|
+
return {
|
|
76
|
+
captureTransport: { send: (t, p) => fanOut(toViewer, t, p) },
|
|
77
|
+
viewerTransport: {
|
|
78
|
+
send: (t, p) => fanOut(toHost, t, p),
|
|
79
|
+
onMessage: (h) => { toViewer.add(h); return () => toViewer.delete(h); },
|
|
80
|
+
},
|
|
81
|
+
onControl: (h) => { toHost.add(h); return () => toHost.delete(h); },
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const transport = createLoopbackTransport();
|
|
86
|
+
const viewer = createViewer({ container, transport: transport.viewerTransport });
|
|
87
|
+
const capture = createCapture({ transport: transport.captureTransport, skipElement });
|
|
88
|
+
transport.onControl((type) => { if (type === CONTROL.START) capture.start(); });
|
|
89
|
+
capture.start();
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Wiring order matters: the loopback has no buffering, so the viewer must
|
|
93
|
+
exist (subscribed and skip-marked) **before** the first snapshot is sent.
|
|
94
|
+
The viewer's re-snapshot request is `CONTROL.START` (ledger entry R2) — the
|
|
95
|
+
host glue maps it to `capture.start()`, which restarts cleanly while
|
|
96
|
+
streaming.
|
|
97
|
+
|
|
98
|
+
## Handle contract
|
|
99
|
+
|
|
100
|
+
- `detach()` — unsubscribe from the transport, remove the resize listeners,
|
|
101
|
+
disconnect the ResizeObserver, and remove the viewer root from the
|
|
102
|
+
container. Idempotent.
|
|
103
|
+
- `destroy()` — `detach()` plus state/overlay reset (counters, identity,
|
|
104
|
+
resync latch, overlay registry dispatch of the null reset). Idempotent;
|
|
105
|
+
safe after `detach()`.
|
|
106
|
+
- `registerOverlay(kind, renderFn)` — register a custom overlay kind (the
|
|
107
|
+
host-facing extension seam, below).
|
|
108
|
+
- `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.
|
|
112
|
+
The viewer emits events only; visible badges, banners, logs, and status
|
|
113
|
+
UI belong to the host application.
|
|
114
|
+
- `resolveNode(nid)` — resolve a PhantomStream nid through the viewer's
|
|
115
|
+
internal identity index. Returns a fresh geometry/identity object
|
|
116
|
+
(`nid`, `exists`, `rect`, `streamSessionId`, `snapshotId`) or `null` for
|
|
117
|
+
missing, stale, or inactive ids. It does not expose mirrored HTML, text,
|
|
118
|
+
attributes, payloads, URLs, titles, or DOM nodes.
|
|
119
|
+
- `highlightNode(nid, options?)` — draw a local host-side highlight for a
|
|
120
|
+
resolved nid using the existing overlay layer. Optional labels are written
|
|
121
|
+
with `textContent`. Returns `false` for unresolved ids.
|
|
122
|
+
- `clearHighlight()` — remove the local semantic highlight. Idempotent.
|
|
123
|
+
- `requestSubtree(nid, options?)` — ask capture for one missing or truncated
|
|
124
|
+
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
|
|
126
|
+
the active `streamSessionId`/`snapshotId`; stale, miss, and mismatched
|
|
127
|
+
`STREAM.SUBTREE_RESPONSE` frames are ignored softly and clear only their
|
|
128
|
+
matching latch.
|
|
129
|
+
|
|
130
|
+
## Node identity index and semantic addressing
|
|
131
|
+
|
|
132
|
+
The renderer rebuilds a private `Map<nid, Node>` index from each accepted
|
|
133
|
+
snapshot's `nodeIds` sidecar after post-parse sanitization. Add ops extend
|
|
134
|
+
the index from their own `nodeIds` sidecars, and remove ops delete the removed
|
|
135
|
+
subtree before it leaves the mirror. A paired `WeakMap<Node, nid>` is kept
|
|
136
|
+
only for internal cleanup; neither map is exposed to hosts.
|
|
137
|
+
|
|
138
|
+
Diff application receives identity hooks from `createViewer`. `diff.js` does
|
|
139
|
+
not own an identity selector fallback, and normal nid-addressed ops do not use
|
|
140
|
+
per-op `querySelector` lookup. Overlay anchor resolution, `resolveNode`, and
|
|
141
|
+
`highlightNode` all route through the same index, so stale ids fail softly in
|
|
142
|
+
one place with content-free diagnostics.
|
|
143
|
+
|
|
144
|
+
The same index now spans Phase 8 scopes. Snapshot, add-op, and subtree payloads
|
|
145
|
+
can carry `shadowRoots[]` and `frames[]` sidecars; the renderer indexes those
|
|
146
|
+
descendants only after the mirror document, shadow fragment, or frame document
|
|
147
|
+
has been parsed and sanitized.
|
|
148
|
+
|
|
149
|
+
## Phase 8 reconstruction and recovery
|
|
150
|
+
|
|
151
|
+
### Shadow roots
|
|
152
|
+
|
|
153
|
+
`STREAM.SNAPSHOT`, add ops, and `DIFF_OP.SHADOW_ROOT` mutations can include
|
|
154
|
+
open shadow root sidecars keyed by `hostNid`. The renderer resolves the host
|
|
155
|
+
through the private identity index, calls `attachShadow({ mode: 'open' })`,
|
|
156
|
+
parses the sidecar HTML in a template, runs `sanitizeFragment`, appends the
|
|
157
|
+
fragment, and indexes the shadow `nodeIds`. Slotted light-DOM children are not
|
|
158
|
+
duplicated into the shadow payload; the browser's real slot distribution owns
|
|
159
|
+
projection.
|
|
160
|
+
|
|
161
|
+
Closed shadow roots are not reconstructed because capture cannot read them.
|
|
162
|
+
There is no selector fallback for shadow addressing.
|
|
163
|
+
|
|
164
|
+
### Iframes
|
|
165
|
+
|
|
166
|
+
Same-origin frame sidecars are rendered as inert nested `srcdoc` documents with
|
|
167
|
+
the same CSP discipline and a sandbox that does not include `allow-scripts`.
|
|
168
|
+
The renderer indexes frame-local `nodeIds` after the frame document loads.
|
|
169
|
+
Cross-origin iframe content is not mirrored; cross-origin entries render as
|
|
170
|
+
content-free labeled placeholders using safe src/origin metadata only.
|
|
171
|
+
|
|
172
|
+
### Value diffs
|
|
173
|
+
|
|
174
|
+
`DIFF_OP.VALUE` applies form-control property state without replacing the
|
|
175
|
+
node. The applier resolves `nid` through the identity index and updates
|
|
176
|
+
`value`, `checked`, and `selectedValues` as present. Missing nids follow the
|
|
177
|
+
same stale-miss accounting as other diff ops. Capture masks value payloads
|
|
178
|
+
before transport, so the renderer never receives raw password values when
|
|
179
|
+
masking applies.
|
|
180
|
+
|
|
181
|
+
### Subtree responses
|
|
182
|
+
|
|
183
|
+
`requestSubtree` sends `CONTROL.SUBTREE_REQUEST` for a specific current nid and
|
|
184
|
+
latches by nid until a matching response arrives. `STREAM.SUBTREE_RESPONSE`
|
|
185
|
+
with `status: 'ok'` replaces only the matching
|
|
186
|
+
`data-phantomstream-truncated="true"` marker after parsing and
|
|
187
|
+
`sanitizeFragment`; response `nodeIds`, `shadowRoots[]`, and `frames[]` are
|
|
188
|
+
then indexed through the same hooks used by snapshots and add ops.
|
|
189
|
+
|
|
190
|
+
Stale, gone, skipped, blocked, untracked, or mismatched responses do not mutate
|
|
191
|
+
the mirror. The latch is bounded so one missing region cannot create request
|
|
192
|
+
storms.
|
|
193
|
+
|
|
194
|
+
## Phase 9 CSSOM reconstruction
|
|
195
|
+
|
|
196
|
+
When capture runs with `styleMode: 'cssom'`, snapshots and scoped sidecars may
|
|
197
|
+
carry `styleSources[]` plus `styleStrategy` instead of generated computed
|
|
198
|
+
inline styles. The renderer installs those sources as sanitized `<style>` or
|
|
199
|
+
safe `<link rel="stylesheet">` nodes:
|
|
200
|
+
|
|
201
|
+
- document-scope sources install into the mirror document head;
|
|
202
|
+
- `{ kind: 'shadow', hostNid }` sources install inside the reconstructed open
|
|
203
|
+
shadow root for that host;
|
|
204
|
+
- `{ kind: 'frame', frameNid }` sources install inside the same-origin mirror
|
|
205
|
+
frame document for that iframe.
|
|
206
|
+
|
|
207
|
+
Each installed node is stamped with `data-ps-style-source-id`, so later
|
|
208
|
+
`DIFF_OP.STYLE_SOURCE` ops can replace or remove the exact source without
|
|
209
|
+
selector fallback. The op contract is
|
|
210
|
+
`action: 'upsert' | 'replace' | 'remove'`; upsert/replace carry a sanitized
|
|
211
|
+
`source`, while remove only needs the `sourceId` and `scope`.
|
|
212
|
+
|
|
213
|
+
CSS text always routes through `scrubCssText` before insertion, matching the
|
|
214
|
+
snapshot CSP and sandbox contract. If the scope cannot be resolved, or the
|
|
215
|
+
viewer receives a style-source op before the matching document/shadow/frame is
|
|
216
|
+
indexed, it increments stale-miss accounting and requests resync with
|
|
217
|
+
`stale-style-scope`.
|
|
218
|
+
|
|
219
|
+
## Event contract (VIEW-02)
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
const offState = viewer.on('state', (event) => {
|
|
223
|
+
// event.state is exactly one of:
|
|
224
|
+
// 'connecting' | 'live' | 'stale' | 'disconnected'
|
|
225
|
+
// event.reason is a lowercase diagnostic string; event.ts is Date.now().
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
const offHealth = viewer.on('health', (health) => {
|
|
229
|
+
// counters, timestamps, and transport diagnostics only
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
offState();
|
|
233
|
+
offHealth();
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Lifecycle starts at `connecting`, moves to `live` on the first accepted
|
|
237
|
+
snapshot/frame, moves to `stale` when resync is requested or transport
|
|
238
|
+
status reports `closed`/`reconnecting`/`error`, and moves to
|
|
239
|
+
`disconnected` after a closed transport remains stale past the short
|
|
240
|
+
disconnect window. `STREAM.STATE` payloads with those same state names map
|
|
241
|
+
into the same public event surface.
|
|
242
|
+
|
|
243
|
+
Health snapshots are privacy-bounded telemetry. They include:
|
|
244
|
+
|
|
245
|
+
- `state`, `ts`
|
|
246
|
+
- `lastFrameAt`, `lastSnapshotAt`, `lastMutationAt`
|
|
247
|
+
- `receivedByType`, `sentByType`
|
|
248
|
+
- `staleMisses`, `applyFailures`, `resyncPending`
|
|
249
|
+
- `sanitizer` counters: `strippedHandlers`, `blockedUrls`,
|
|
250
|
+
`droppedSubtrees`, `cssScrubs`
|
|
251
|
+
- `transport` diagnostics when available: `state`, `reason`, `readyState`,
|
|
252
|
+
`bufferedAmount`, `drops`, `errors`, `lastCloseAt`, `lastSendAt`,
|
|
253
|
+
`lastReceiveAt`, `closeCode`, `closeReason`, and transport type counters
|
|
254
|
+
|
|
255
|
+
Health snapshots never include mirrored `html`, text node contents, raw
|
|
256
|
+
payload objects, page `url`, page `title`, or DOM nodes.
|
|
257
|
+
|
|
258
|
+
## Overlay channel contract (VIEW-04)
|
|
259
|
+
|
|
260
|
+
`STREAM.OVERLAY` payloads dispatch through one kind-keyed registry: **every
|
|
261
|
+
own payload key except the reserved identity keys
|
|
262
|
+
(`streamSessionId`/`snapshotId`) is an overlay kind.** The built-ins (`glow`,
|
|
263
|
+
`progress`) are pre-registered through the exact same registry custom kinds
|
|
264
|
+
use — there is no special-cased dispatch path.
|
|
265
|
+
|
|
266
|
+
```js
|
|
267
|
+
viewer.registerOverlay('badge', (payload, anchorRect, layer) => {
|
|
268
|
+
// payload: the RAW wire value for this kind (null = hide/clear)
|
|
269
|
+
// anchorRect: {top, left, width, height} in host px, or null
|
|
270
|
+
// layer: the overlay layer element (write your DOM here)
|
|
271
|
+
});
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
- **Anchor-rect priority:** payload value carries a `nid` → the mirrored
|
|
275
|
+
element's bounding rect, mapped to host coordinates (a stale nid yields
|
|
276
|
+
`null`, no coordinate fallback) → otherwise numeric `x/y/w/h` →
|
|
277
|
+
`mapRectToHost` with the current scale state → otherwise `null`
|
|
278
|
+
(fixed-position overlays like the progress pill).
|
|
279
|
+
- **Null contract:** every renderFn (built-in or custom) receives `null` to
|
|
280
|
+
hide/clear; each new snapshot dispatches `(null, null, layer)` through
|
|
281
|
+
every registered kind (the reset contract).
|
|
282
|
+
- **Escaping:** the renderFn receives the **raw** payload value —
|
|
283
|
+
capture-side data is attacker-influenced, so custom renderFns own their
|
|
284
|
+
escaping (write text via `textContent` like the built-ins, never
|
|
285
|
+
`innerHTML`).
|
|
286
|
+
- **Unknown kinds** are logged (`[Renderer] unknown overlay kind ignored`)
|
|
287
|
+
and skipped — never thrown (forward-compatible).
|
|
288
|
+
- **Throwing renderFns** are contained: routed to the logger, the kind loop
|
|
289
|
+
continues.
|
|
290
|
+
|
|
291
|
+
On the capture side, every own enumerable key returned by the
|
|
292
|
+
`overlayProvider` is forwarded on the wire as an overlay kind (capture
|
|
293
|
+
README entry E1), so custom DOM-anchored overlays flow end-to-end:
|
|
294
|
+
provider → wire → `registerOverlay` renderFn. The dialog card
|
|
295
|
+
(`STREAM.DIALOG`) renders alert/confirm/prompt mirroring with the message
|
|
296
|
+
through `textContent`, never `innerHTML`.
|
|
297
|
+
|
|
298
|
+
## Recursion guard for same-page hosts
|
|
299
|
+
|
|
300
|
+
When the capture and the viewer share one page (the loopback demo, any
|
|
301
|
+
embedded-SDK host that mirrors its own tab), the viewer lives inside the
|
|
302
|
+
capture's body-scoped observer. Without exclusion, two feedback paths fire:
|
|
303
|
+
the snapshot embeds the mirror (`cloneNode` copies the iframe's `srcdoc`),
|
|
304
|
+
and every srcdoc write echoes back as a megabyte `attr` mutation —
|
|
305
|
+
amplification until the truncation budget chokes.
|
|
306
|
+
|
|
307
|
+
The viewer root therefore stamps `data-phantomstream-ui="viewer"`, and the
|
|
308
|
+
host passes the capture this predicate:
|
|
309
|
+
|
|
310
|
+
```js
|
|
311
|
+
skipElement: function (el) {
|
|
312
|
+
return !!(el.getAttribute && el.getAttribute('data-phantomstream-ui'));
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
**Predicates MUST be attribute- or id-based, never object identity and never
|
|
317
|
+
`document.contains`:** during serialization the predicate runs against
|
|
318
|
+
detached **clone** elements, during diffing against **live** elements — an
|
|
319
|
+
`el === viewerRoot` check matches only the live side and the clone leaks
|
|
320
|
+
into snapshots. Both guard paths (snapshot cleanliness, zero mutation echo)
|
|
321
|
+
are pinned end-to-end by `tests/renderer-loopback.test.js`.
|
|
322
|
+
|
|
323
|
+
## Divergence ledger
|
|
324
|
+
|
|
325
|
+
Phase 1 discipline: every intentional departure from the reference viewer is
|
|
326
|
+
explicit, never accidental. Entries R1-R12; "drop" means FSB dashboard
|
|
327
|
+
chrome removed, "divergence" means changed behavior, "reconstruction" means
|
|
328
|
+
parity values rebuilt from documentation because the source asset is not
|
|
329
|
+
vendored.
|
|
330
|
+
|
|
331
|
+
- **R1 — Layout modes dropped.** `inline`/`maximized`/`pip`/`fullscreen` are
|
|
332
|
+
FSB dashboard UI, not framework concerns (CONTEXT decision D-03). The
|
|
333
|
+
viewer always fills its container; layout belongs to the host. The
|
|
334
|
+
`layout.js` module sketched in earlier drafts is not extracted.
|
|
335
|
+
- **R2 — The resync message is `CONTROL.START`.** A message named
|
|
336
|
+
`dash:request-snapshot` does not exist anywhere in the protocol or the
|
|
337
|
+
reference; the reference's resync path sends `dash:dom-stream-start`
|
|
338
|
+
(= `CONTROL.START`), latched until the next snapshot. No new protocol
|
|
339
|
+
constant was minted.
|
|
340
|
+
- **R3 — `dash:request-status` dropped from the resync path.** The reference
|
|
341
|
+
paired its re-snapshot request with an FSB status refresh; the framework
|
|
342
|
+
viewer sends `CONTROL.START` alone.
|
|
343
|
+
- **R4 — tabId identity checks dropped.** Tab identity is an FSB extension
|
|
344
|
+
concern; staleness goes through the protocol's `isCurrentStream`
|
|
345
|
+
(streamSessionId/snapshotId) instead.
|
|
346
|
+
- **R5 — Transport-event ring buffers dropped.**
|
|
347
|
+
`recordDashboardTransportEvent`/`-Error` diagnostics are FSB dashboard
|
|
348
|
+
state; renderer diagnostics route to the injected logger with the
|
|
349
|
+
`'[Renderer]'` prefix (plus the miss/failure counters that feed resync).
|
|
350
|
+
- **R6 — FSB 9-state preview machine → minimal `waiting`/`streaming` gate.**
|
|
351
|
+
The reference's `previewState` sub-views (loading, disconnected, error,
|
|
352
|
+
...) are dashboard UI. The viewer gates mutation/scroll/overlay/dialog
|
|
353
|
+
application on `streaming` exactly like the reference did; Phase 4 adds
|
|
354
|
+
the host-facing `connecting`/`live`/`stale`/`disconnected` and health
|
|
355
|
+
event surface without adding viewer-owned chrome.
|
|
356
|
+
- **R7 — Font Awesome → inline SVG icons.** A zero-dependency framework
|
|
357
|
+
cannot ship an icon font; the dialog icons (warning-triangle,
|
|
358
|
+
question-circle, keyboard) are equivalent inline SVGs.
|
|
359
|
+
- **R8 — iframe title renamed.** `"PhantomStream live mirror"` replaces the
|
|
360
|
+
FSB dashboard's preview title.
|
|
361
|
+
- **R9 — Accessibility additions (additive).** `role="status"` +
|
|
362
|
+
`aria-live="polite"` on the dialog card; `aria-hidden="true"` on the
|
|
363
|
+
decorative glow/progress elements; glow reposition transitions wrapped in
|
|
364
|
+
`@media (prefers-reduced-motion: no-preference)`.
|
|
365
|
+
- **R10 — Glow and progress visuals are documented reconstructions.** The
|
|
366
|
+
glow's 2px `#f59e0b` border / 4px radius / `0 0 12px rgba(245,158,11,0.6)`
|
|
367
|
+
shadow and the progress pill's position/scrim are rebuilt from the
|
|
368
|
+
02-UI-SPEC parity contract — the reference stylesheet lines are not
|
|
369
|
+
vendored in this repo. The dialog card CSS, scale formula, scroll
|
|
370
|
+
smoothing, and overlay coordinate math are exact parity.
|
|
371
|
+
- **R11 — Dialog identity-nesting quirk ported as parity.** Capture nests
|
|
372
|
+
stream identity **inside** `payload.dialog`, so the viewer's top-level
|
|
373
|
+
`isCurrentStream` check finds no identity and always accepts dialogs —
|
|
374
|
+
exactly like the reference's `shouldAcceptPreviewMessage` no-identity
|
|
375
|
+
early return. Deliberate parity choice, commented in code; revisit when
|
|
376
|
+
Phase 4 introduces multi-stream transports.
|
|
377
|
+
- **R12 — Creation-time persistent load listener replaces per-snapshot
|
|
378
|
+
`iframe.onload` (forced divergence).** jsdom 29 (verified empirically)
|
|
379
|
+
only queues the iframe's initial about:blank load event when a load
|
|
380
|
+
listener already exists at insertion time, and never re-fires load on
|
|
381
|
+
srcdoc writes — the reference's per-snapshot `iframe.onload =` assignment
|
|
382
|
+
therefore never executes under test. One `addEventListener('load', ...)`
|
|
383
|
+
attached before insertion, guarded on the pending snapshot payload,
|
|
384
|
+
behaves identically in real browsers (fires on every srcdoc load with the
|
|
385
|
+
reference's onload body: scale, initial scrollTo, mark streaming,
|
|
386
|
+
un-hide). Relatedly, the viewer stays `streaming` across re-snapshots
|
|
387
|
+
(reference parity): mutations carrying the new identity apply without
|
|
388
|
+
waiting for a new load event.
|
|
389
|
+
|
|
390
|
+
## Phase 3 security behavior
|
|
391
|
+
|
|
392
|
+
The Phase 3 security pipeline is always on and documented in
|
|
393
|
+
`docs/SECURITY.md`:
|
|
394
|
+
|
|
395
|
+
- **Inline CSS is scrubbed and backed by CSP.** `payload.inlineStyles` route
|
|
396
|
+
through `scrubCssText` before srcdoc assembly, and the srcdoc head carries
|
|
397
|
+
the adopted Content-Security-Policy meta. `payload.html` intentionally
|
|
398
|
+
remains raw at the string layer because string-scrub-then-reparse is the
|
|
399
|
+
mutation-XSS anti-pattern; the capture chokepoint, post-parse
|
|
400
|
+
`sanitizeFragment` scrub, CSP, and sandbox form the defense chain.
|
|
401
|
+
- **`on*` attributes and dangerous URLs are scrubbed at both chokepoints.**
|
|
402
|
+
Capture strips or neutralizes before transport, and render applies
|
|
403
|
+
`sanitizeFragment` / `sanitizeAttrValue` before reconstructed content
|
|
404
|
+
reaches the mirror document.
|
|
405
|
+
- **Template-context add-op parsing is live.** The add op parses `m.html`
|
|
406
|
+
through `<template>`, then runs `sanitizeFragment` before `importNode`.
|
|
407
|
+
Context-dependent elements (`<tr>`, `<td>`, `<tbody>`, `<col>`, and
|
|
408
|
+
friends) no longer disappear through a div-context parser.
|
|
409
|
+
- **Embed contract is explicit.** The mirror iframe sandbox is exactly
|
|
410
|
+
`allow-same-origin`; hosts must never add `allow-scripts` or render wire
|
|
411
|
+
payloads outside `createViewer`.
|
|
412
|
+
|
|
413
|
+
## Known remaining behaviors
|
|
414
|
+
|
|
415
|
+
- **Pre-onload mutation drop (parity, self-healing).** Mutations arriving
|
|
416
|
+
between the srcdoc write and the load event are dropped (the reference
|
|
417
|
+
gates on streaming state). The miss accounting + `CONTROL.START` resync
|
|
418
|
+
self-heals any resulting drift; do not write tests that assume zero loss
|
|
419
|
+
before the first load.
|
|
420
|
+
|
|
421
|
+
## Environment
|
|
422
|
+
|
|
423
|
+
- **Sandbox contract:** the mirror iframe's sandbox is **exactly**
|
|
424
|
+
`allow-same-origin` — no `allow-scripts`, ever. The factory writes the
|
|
425
|
+
attribute, reads it back, and asserts the token list at creation
|
|
426
|
+
(`viewer-sandbox-invalid` otherwise), so a hostile or broken environment
|
|
427
|
+
fails loudly instead of weakening the sandbox silently. `allow-same-origin`
|
|
428
|
+
keeps `contentDocument` parent-accessible for diff applies and overlay
|
|
429
|
+
rect reads while the mirror cannot execute script. The full embed security
|
|
430
|
+
contract (CSP guidance, sanitization guarantees, and host must-nevers) is
|
|
431
|
+
documented in `docs/SECURITY.md`.
|
|
432
|
+
- **jsdom srcdoc limitation:** jsdom 29 never parses the `srcdoc` attribute
|
|
433
|
+
into `contentDocument` (the attribute round-trips; the document stays
|
|
434
|
+
empty). Tests must never assert mirror content through `contentDocument`
|
|
435
|
+
after only setting srcdoc. The e2e pattern is the manual write-glue —
|
|
436
|
+
`cd.open(); cd.write(iframe.srcdoc); cd.close();` — after which diff
|
|
437
|
+
applies hit the written document because the viewer reads
|
|
438
|
+
`contentDocument` fresh per message (see
|
|
439
|
+
`tests/renderer-loopback.test.js`). Real browsers parse srcdoc natively;
|
|
440
|
+
visual parity and real-browser srcdoc rendering are verified manually via
|
|
441
|
+
the loopback demo.
|
|
442
|
+
- Running the test suite requires Node >= 20.19 (jsdom 29 engines floor);
|
|
443
|
+
the library itself (`src/`) remains Node 18+-compatible.
|