@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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +263 -0
  3. package/bin/phantom-stream.js +193 -0
  4. package/dist/types/adapters/bookmarklet.d.ts +22 -0
  5. package/dist/types/adapters/bookmarklet.d.ts.map +1 -0
  6. package/dist/types/adapters/browser-inject.d.ts +7 -0
  7. package/dist/types/adapters/browser-inject.d.ts.map +1 -0
  8. package/dist/types/adapters/extension.d.ts +43 -0
  9. package/dist/types/adapters/extension.d.ts.map +1 -0
  10. package/dist/types/adapters/playwright-inject.d.ts +2 -0
  11. package/dist/types/adapters/playwright-inject.d.ts.map +1 -0
  12. package/dist/types/adapters/playwright.d.ts +14 -0
  13. package/dist/types/adapters/playwright.d.ts.map +1 -0
  14. package/dist/types/capture/index.d.ts +241 -0
  15. package/dist/types/capture/index.d.ts.map +1 -0
  16. package/dist/types/index.d.ts +6 -0
  17. package/dist/types/index.d.ts.map +1 -0
  18. package/dist/types/protocol/constants.d.ts +35 -0
  19. package/dist/types/protocol/constants.d.ts.map +1 -0
  20. package/dist/types/protocol/envelope.d.ts +41 -0
  21. package/dist/types/protocol/envelope.d.ts.map +1 -0
  22. package/dist/types/protocol/index.d.ts +5 -0
  23. package/dist/types/protocol/index.d.ts.map +1 -0
  24. package/dist/types/protocol/messages.d.ts +520 -0
  25. package/dist/types/protocol/messages.d.ts.map +1 -0
  26. package/dist/types/protocol/remote-control.d.ts +70 -0
  27. package/dist/types/protocol/remote-control.d.ts.map +1 -0
  28. package/dist/types/relay/backends/ws.d.ts +39 -0
  29. package/dist/types/relay/backends/ws.d.ts.map +1 -0
  30. package/dist/types/relay/index.d.ts +4 -0
  31. package/dist/types/relay/index.d.ts.map +1 -0
  32. package/dist/types/relay/limits.d.ts +54 -0
  33. package/dist/types/relay/limits.d.ts.map +1 -0
  34. package/dist/types/relay/relay.d.ts +73 -0
  35. package/dist/types/relay/relay.d.ts.map +1 -0
  36. package/dist/types/renderer/diff.d.ts +62 -0
  37. package/dist/types/renderer/diff.d.ts.map +1 -0
  38. package/dist/types/renderer/index.d.ts +211 -0
  39. package/dist/types/renderer/index.d.ts.map +1 -0
  40. package/dist/types/renderer/overlays.d.ts +166 -0
  41. package/dist/types/renderer/overlays.d.ts.map +1 -0
  42. package/dist/types/renderer/sanitize.d.ts +73 -0
  43. package/dist/types/renderer/sanitize.d.ts.map +1 -0
  44. package/dist/types/renderer/snapshot.d.ts +41 -0
  45. package/dist/types/renderer/snapshot.d.ts.map +1 -0
  46. package/dist/types/transport/websocket.d.ts +44 -0
  47. package/dist/types/transport/websocket.d.ts.map +1 -0
  48. package/docs/ARCHITECTURE.md +273 -0
  49. package/docs/DESIGN-HISTORY.md +120 -0
  50. package/docs/QUICKSTARTS.md +289 -0
  51. package/docs/RELEASE.md +60 -0
  52. package/docs/SECURITY.md +156 -0
  53. package/docs/paper/OUTLINE.md +100 -0
  54. package/examples/bookmarklet-demo/demo.css +102 -0
  55. package/examples/bookmarklet-demo/server.js +297 -0
  56. package/examples/bookmarklet-demo/source.html +52 -0
  57. package/examples/bookmarklet-demo/viewer.html +48 -0
  58. package/examples/extension-mv3/demo.css +102 -0
  59. package/examples/extension-mv3/server.js +350 -0
  60. package/examples/extension-mv3/source.html +48 -0
  61. package/examples/extension-mv3/viewer.html +48 -0
  62. package/examples/loopback-mirror.html +369 -0
  63. package/examples/loopback-transport.js +65 -0
  64. package/examples/playwright-demo/demo.css +462 -0
  65. package/examples/playwright-demo/fixture.html +56 -0
  66. package/examples/playwright-demo/fixture.js +57 -0
  67. package/examples/playwright-demo/server.js +517 -0
  68. package/examples/playwright-demo/viewer.html +112 -0
  69. package/examples/playwright-demo/viewer.js +414 -0
  70. package/examples/serve.js +97 -0
  71. package/examples/two-tab-demo/demo.css +266 -0
  72. package/examples/two-tab-demo/server.js +233 -0
  73. package/examples/two-tab-demo/source.html +70 -0
  74. package/examples/two-tab-demo/source.js +213 -0
  75. package/examples/two-tab-demo/viewer.html +72 -0
  76. package/examples/two-tab-demo/viewer.js +121 -0
  77. package/package.json +107 -0
  78. package/src/adapters/bookmarklet.js +98 -0
  79. package/src/adapters/browser-inject.js +17 -0
  80. package/src/adapters/extension.js +322 -0
  81. package/src/adapters/playwright-inject.js +4401 -0
  82. package/src/adapters/playwright.js +540 -0
  83. package/src/capture/README.md +302 -0
  84. package/src/capture/index.js +4361 -0
  85. package/src/index.js +5 -0
  86. package/src/protocol/constants.js +49 -0
  87. package/src/protocol/envelope.js +75 -0
  88. package/src/protocol/index.js +4 -0
  89. package/src/protocol/messages.js +268 -0
  90. package/src/protocol/remote-control.js +300 -0
  91. package/src/relay/README.md +22 -0
  92. package/src/relay/backends/ws.js +186 -0
  93. package/src/relay/index.js +3 -0
  94. package/src/relay/limits.js +105 -0
  95. package/src/relay/relay.js +397 -0
  96. package/src/renderer/README.md +443 -0
  97. package/src/renderer/diff.js +389 -0
  98. package/src/renderer/index.js +1401 -0
  99. package/src/renderer/overlays.js +528 -0
  100. package/src/renderer/sanitize.js +366 -0
  101. package/src/renderer/snapshot.js +202 -0
  102. package/src/transport/websocket.js +553 -0
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './protocol/index.js';
2
+ export * from './capture/index.js';
3
+ export * from './renderer/index.js';
4
+ export * from './relay/index.js';
5
+ export * from './transport/websocket.js';
@@ -0,0 +1,49 @@
1
+ // Shared numeric constants of the PhantomStream pipeline.
2
+ // Extracted from FSB extension/content/dom-stream.js (Phase 211-02) and the
3
+ // relay's per-message enforcement (server ws handler).
4
+
5
+ /**
6
+ * Hard per-message size cap enforced by the relay (bytes).
7
+ * Capture-side snapshot truncation budgets derive from this value.
8
+ */
9
+ export const RELAY_PER_MESSAGE_LIMIT_BYTES = 1048576; // 1 MiB
10
+
11
+ /**
12
+ * Fraction of the relay cap a serialized snapshot may occupy. The remaining
13
+ * headroom absorbs envelope overhead and compression-resistant payloads
14
+ * where LZ does not reduce size.
15
+ */
16
+ export const SNAPSHOT_BUDGET_FRACTION = 0.8;
17
+
18
+ /** Snapshot truncation byte budget. */
19
+ export const SNAPSHOT_BUDGET_BYTES = Math.floor(
20
+ RELAY_PER_MESSAGE_LIMIT_BYTES * SNAPSHOT_BUDGET_FRACTION
21
+ );
22
+
23
+ /**
24
+ * During truncation, subtrees whose live top exceeds this many viewport
25
+ * heights are dropped first (content far below the fold).
26
+ */
27
+ export const TRUNCATION_VIEWPORT_MULTIPLIER = 3;
28
+
29
+ /** Scroll side-channel throttle: at most one event per this many ms. */
30
+ export const SCROLL_THROTTLE_MS = 200;
31
+
32
+ /** Overlay side-channel throttle: at most one broadcast per this many ms. */
33
+ export const OVERLAY_THROTTLE_MS = 500;
34
+
35
+ /**
36
+ * Capture-side watchdog: if mutations are pending and nothing has drained
37
+ * for this long, force a flush and count a stale rescue.
38
+ */
39
+ export const MUTATION_STALE_THRESHOLD_MS = 5000;
40
+
41
+ /** Capture-side watchdog tick cadence. */
42
+ export const WATCHDOG_TICK_MS = 500;
43
+
44
+ /** Readiness probe: poll interval and total budget. */
45
+ export const READY_PROBE_INTERVAL_MS = 200;
46
+ export const READY_PROBE_BUDGET_MS = 5000;
47
+
48
+ /** Inline <style> tags larger than this are skipped during snapshot capture. */
49
+ export const INLINE_STYLE_MAX_BYTES = 500000;
@@ -0,0 +1,75 @@
1
+ // PhantomStream compression envelope.
2
+ //
3
+ // Large payloads travel as a self-identifying envelope { _lz: true, d: <base64> }
4
+ // (LZ-string compressToBase64); small payloads travel as plain JSON. Receivers
5
+ // detect the envelope by shape, so compressed and plain senders interoperate
6
+ // (FSB Phase 122.3 backward-compatibility requirement).
7
+ //
8
+ // The LZ-string implementation is injected rather than imported so this module
9
+ // works in any runtime (extension content script, service worker, browser,
10
+ // Node) and stays dependency-free.
11
+
12
+ /**
13
+ * @typedef {Object} LZCodec
14
+ * @property {(s: string) => string} compressToBase64
15
+ * @property {(s: string) => string|null} decompressFromBase64
16
+ */
17
+
18
+ /**
19
+ * Encode a message object for the wire.
20
+ *
21
+ * @param {Object} msg The full message ({ type, payload, ... })
22
+ * @param {LZCodec} lz LZ-string (or compatible) codec
23
+ * @param {number} [thresholdBytes=0] Compress only when the JSON exceeds this size;
24
+ * 0 compresses everything
25
+ * @returns {string} JSON string ready to send
26
+ */
27
+ export function encodeEnvelope(msg, lz, thresholdBytes) {
28
+ var json = JSON.stringify(msg);
29
+ var threshold = thresholdBytes || 0;
30
+ if (!lz || typeof lz.compressToBase64 !== 'function' || json.length <= threshold) {
31
+ return json;
32
+ }
33
+ return JSON.stringify({ _lz: true, d: lz.compressToBase64(json) });
34
+ }
35
+
36
+ /**
37
+ * Decode a wire string into a message object. Detects the compressed
38
+ * envelope by shape; falls through to plain JSON otherwise.
39
+ *
40
+ * @param {string} raw
41
+ * @param {LZCodec} [lz]
42
+ * @returns {{ok: true, msg: Object} | {ok: false, error: string}}
43
+ */
44
+ export function decodeEnvelope(raw, lz) {
45
+ var outer;
46
+ try {
47
+ outer = JSON.parse(raw);
48
+ } catch (e) {
49
+ return { ok: false, error: 'json-parse-failed' };
50
+ }
51
+ if (!outer || outer._lz !== true || typeof outer.d !== 'string') {
52
+ return { ok: true, msg: outer };
53
+ }
54
+ if (!lz || typeof lz.decompressFromBase64 !== 'function') {
55
+ return { ok: false, error: 'decompress-unavailable' };
56
+ }
57
+ var inner = lz.decompressFromBase64(outer.d);
58
+ if (!inner) {
59
+ return { ok: false, error: 'decompress-failed' };
60
+ }
61
+ try {
62
+ return { ok: true, msg: JSON.parse(inner) };
63
+ } catch (e) {
64
+ return { ok: false, error: 'inner-json-parse-failed' };
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Is this decoded wire object a compressed envelope (vs. a plain message)?
70
+ * Useful for relay-side diagnostics that classify traffic without decoding.
71
+ * @param {Object} obj
72
+ */
73
+ export function isCompressedEnvelope(obj) {
74
+ return !!obj && obj._lz === true && typeof obj.d === 'string';
75
+ }
@@ -0,0 +1,4 @@
1
+ export * from './constants.js';
2
+ export * from './messages.js';
3
+ export * from './envelope.js';
4
+ export * from './remote-control.js';
@@ -0,0 +1,268 @@
1
+ // PhantomStream wire protocol: message types and payload shapes.
2
+ // Extracted from FSB's dom-stream pipeline (content script -> service worker ->
3
+ // relay -> viewer). Names keep the original `ext:` (capture host -> viewer) and
4
+ // `dash:` (viewer -> capture host) direction prefixes for FSB compatibility.
5
+
6
+ /** Viewer -> capture host: stream lifecycle control. */
7
+ export const CONTROL = {
8
+ START: 'dash:dom-stream-start',
9
+ STOP: 'dash:dom-stream-stop',
10
+ PAUSE: 'dash:dom-stream-pause',
11
+ RESUME: 'dash:dom-stream-resume',
12
+ /** Viewer request for a bounded fresh subtree payload. Payload: SubtreeRequestPayload */
13
+ SUBTREE_REQUEST: 'dash:ps-subtree-request',
14
+ };
15
+
16
+ /** Capture host -> viewer: stream data and side channels. */
17
+ export const STREAM = {
18
+ /** Full snapshot. Payload: see SnapshotPayload below. */
19
+ SNAPSHOT: 'ext:dom-snapshot',
20
+ /** Batched diff ops. Payload: { mutations: DiffOp[], streamSessionId, snapshotId } */
21
+ MUTATIONS: 'ext:dom-mutations',
22
+ /** Scroll position. Payload: { scrollX, scrollY, streamSessionId, snapshotId } */
23
+ SCROLL: 'ext:dom-scroll',
24
+ /** Automation overlay state. Payload: { glow, progress, streamSessionId, snapshotId } */
25
+ OVERLAY: 'ext:dom-overlay',
26
+ /** Native dialog mirroring. Payload: { dialog: DialogPayload } */
27
+ DIALOG: 'ext:dom-dialog',
28
+ /** Capture module loaded in a tab. Payload: { tabId } */
29
+ READY: 'ext:dom-ready',
30
+ /** Watchdog/viewer request for a fresh snapshot. Payload: { reason, ts } */
31
+ REQUEST_SNAPSHOT: 'ext:request-snapshot',
32
+ /** Stream health state. */
33
+ STATE: 'ext:stream-state',
34
+ /** Capture response to a bounded subtree request. Payload: SubtreeResponsePayload */
35
+ SUBTREE_RESPONSE: 'ext:ps-subtree-response',
36
+ };
37
+
38
+ /** Viewer -> adapter remote-control frames, plus adapter -> viewer state. */
39
+ export const REMOTE_CONTROL = {
40
+ REQUEST: 'dash:ps-control-request',
41
+ STOP: 'dash:ps-control-stop',
42
+ CLICK: 'dash:ps-control-click',
43
+ TEXT: 'dash:ps-control-text',
44
+ KEY: 'dash:ps-control-key',
45
+ SCROLL: 'dash:ps-control-scroll',
46
+ STATE: 'ext:ps-control-state',
47
+ };
48
+
49
+ /** Content-free remote-control authorization/replay states. */
50
+ const REMOTE_CONTROL_STATE_VALUES = {
51
+ LOCKED: 'locked',
52
+ REQUESTING: 'requesting',
53
+ ACTIVE: 'active',
54
+ DENIED: 'denied',
55
+ STOPPED: 'stopped',
56
+ };
57
+
58
+ export { REMOTE_CONTROL_STATE_VALUES as REMOTE_CONTROL_STATE };
59
+
60
+ /** Diff op codes carried in STREAM.MUTATIONS payloads. */
61
+ export const DIFF_OP = {
62
+ /** { op:'add', parentNid, html, beforeNid|null, nodeIds:string[] } — insert serialized subtree */
63
+ ADD: 'add',
64
+ /** { op:'rm', nid } — remove subtree */
65
+ REMOVE: 'rm',
66
+ /** { op:'attr', nid, attr, val } — attribute change */
67
+ ATTR: 'attr',
68
+ /** { op:'text', nid, text } — character data change, addressed via parent nid */
69
+ TEXT: 'text',
70
+ /** { op:'value', nid, value?, checked?, selectedValues? } — live form state change */
71
+ VALUE: 'value',
72
+ /** ShadowRootPayload plus op:'shadow-root' — replace/open an observed shadow root */
73
+ SHADOW_ROOT: 'shadow-root',
74
+ /** { op:'frame', frameNid, frame:FramePayload } — refresh an inert iframe mirror */
75
+ FRAME: 'frame',
76
+ /** StyleSourceDiffOp — upsert/replace/remove one scoped CSSOM source */
77
+ STYLE_SOURCE: 'style-source',
78
+ };
79
+
80
+ /**
81
+ * Legacy identity attribute name retained for compatibility with renderer
82
+ * and fixture code that still consumes nid-stamped mirror DOM. Capture-side
83
+ * framework identity now travels through SnapshotPayload.nodeIds and add-op
84
+ * nodeIds sidecars instead of mutating observed page elements.
85
+ */
86
+ export const NID_ATTR = 'data-fsb-nid';
87
+
88
+ /**
89
+ * @typedef {Object} StyleScope
90
+ * @property {'document'|'shadow'|'frame'} kind
91
+ * @property {string} [hostNid] Shadow host nid when kind is 'shadow'
92
+ * @property {string} [frameNid] Iframe nid when kind is 'frame'
93
+ */
94
+
95
+ /**
96
+ * @typedef {Object} StyleSource
97
+ * @property {string} sourceId
98
+ * @property {StyleScope} scope
99
+ * @property {'link'|'style'|'constructable'|'adopted'|'fallback'} ownerKind
100
+ * @property {number} order
101
+ * @property {string|null} [href]
102
+ * @property {string} [media]
103
+ * @property {boolean} [disabled]
104
+ * @property {string} [cssText]
105
+ * @property {{reason: string}|null} [fallback]
106
+ * @property {number} [approxBytes]
107
+ */
108
+
109
+ /**
110
+ * @typedef {Object} StyleStrategy
111
+ * @property {'computed'|'cssom'} mode
112
+ * @property {number} sourceCount
113
+ * @property {number} fallbackCount
114
+ * @property {number} computedFallbackCount
115
+ * @property {number} approxCssBytes
116
+ */
117
+
118
+ /**
119
+ * @typedef {Object} StyleSourceDiffOp
120
+ * @property {'style-source'} op
121
+ * @property {'upsert'|'replace'|'remove'} action
122
+ * @property {string} sourceId
123
+ * @property {StyleScope} scope
124
+ * @property {StyleSource} [source]
125
+ */
126
+
127
+ /**
128
+ * @typedef {Object} AddDiffOp
129
+ * @property {'add'} op
130
+ * @property {string} parentNid Parent node id in the current mirror
131
+ * @property {string} html Serialized subtree HTML, without framework identity attrs
132
+ * @property {string|null} beforeNid Insert before this sibling nid, or append when null
133
+ * @property {string[]} nodeIds Preorder ids for every serialized element in html
134
+ * @property {ShadowRootPayload[]} [shadowRoots] Open shadow root sidecars inside this added subtree
135
+ * @property {FramePayload[]} [frames] Same-origin/cross-origin frame sidecars inside this added subtree
136
+ */
137
+
138
+ /**
139
+ * @typedef {Object} ShadowRootPayload
140
+ * @property {string} hostNid Host element nid that owns this shadow root
141
+ * @property {'open'} mode Mirrored roots are open; closed roots are not introspected
142
+ * @property {string} html Serialized shadow root child HTML
143
+ * @property {string[]} nodeIds Preorder ids for shadow descendant elements
144
+ * @property {string} slotAssignment Content-free slot assignment hint/diagnostic
145
+ * @property {StyleSource[]} [styleSources] Scoped CSSOM sources for this shadow root
146
+ * @property {StyleStrategy} [styleStrategy] CSSOM strategy counters for this scope
147
+ */
148
+
149
+ /**
150
+ * @typedef {Object} FramePayload
151
+ * @property {string} frameNid Iframe element nid
152
+ * @property {string} kind Frame policy kind, e.g. 'same-origin' or 'cross-origin'
153
+ * @property {string} [html] Serialized frame body HTML for accessible frames
154
+ * @property {string[]} [nodeIds] Preorder ids for serialized frame elements
155
+ * @property {string[]} [stylesheets] Absolutified stylesheet URLs
156
+ * @property {string[]} [inlineStyles] Sanitized inline style blocks
157
+ * @property {StyleSource[]} [styleSources] Scoped CSSOM sources for this frame document
158
+ * @property {StyleStrategy} [styleStrategy] CSSOM strategy counters for this scope
159
+ * @property {Object} [htmlAttrs] Sanitized frame <html> attributes
160
+ * @property {Object} [bodyAttrs] Sanitized frame <body> attributes
161
+ * @property {string} [htmlStyle] Computed shell style for frame <html>
162
+ * @property {string} [bodyStyle] Computed shell style for frame <body>
163
+ * @property {string} [label] Content-free placeholder label
164
+ * @property {string} [src] Frame src URL when safe to disclose
165
+ * @property {string} [origin] Frame origin metadata when safe to disclose
166
+ */
167
+
168
+ /**
169
+ * @typedef {Object} ValueDiffOp
170
+ * @property {'value'} op
171
+ * @property {string} nid
172
+ * @property {string} [value] Textual value for input/textarea/select-like controls
173
+ * @property {boolean} [checked] Checked state for checkbox/radio controls
174
+ * @property {string[]} [selectedValues] Selected option values for multi-select controls
175
+ */
176
+
177
+ /**
178
+ * @typedef {Object} SubtreeRequestPayload
179
+ * @property {string} requestId
180
+ * @property {string} nid
181
+ * @property {string} streamSessionId
182
+ * @property {number} snapshotId
183
+ * @property {string} [reason]
184
+ */
185
+
186
+ /**
187
+ * @typedef {Object} SubtreeResponsePayload
188
+ * @property {string} requestId
189
+ * @property {string} nid
190
+ * @property {string} status 'ok' or a content-free miss status
191
+ * @property {string} [html] Serialized subtree HTML when status is 'ok'
192
+ * @property {string[]} [nodeIds] Preorder ids for serialized subtree elements
193
+ * @property {ShadowRootPayload[]} [shadowRoots] Open shadow roots inside the subtree
194
+ * @property {FramePayload[]} [frames] Frame sidecars inside the subtree
195
+ * @property {StyleSource[]} [styleSources] Scoped CSSOM sources inside the subtree
196
+ * @property {StyleStrategy} [styleStrategy] CSSOM strategy counters for subtree sources
197
+ * @property {string} streamSessionId
198
+ * @property {number} snapshotId
199
+ */
200
+
201
+ /**
202
+ * @typedef {Object} SnapshotPayload
203
+ * @property {string} html Serialized body innerHTML (style-inlined; framework identity-clean)
204
+ * @property {string[]} nodeIds Preorder ids for every serialized element in html
205
+ * @property {ShadowRootPayload[]} [shadowRoots] Open shadow roots keyed by host nid
206
+ * @property {FramePayload[]} [frames] Frame sidecars keyed by iframe nid
207
+ * @property {boolean} truncated True if the size budget forced subtree drops
208
+ * @property {number} missingDescendants Count of dropped subtrees
209
+ * @property {string[]} stylesheets Absolutified <link rel=stylesheet> URLs
210
+ * @property {string[]} inlineStyles Inline <style> text blocks from <head>
211
+ * @property {StyleSource[]} [styleSources] Scoped CSSOM sources for document/shadow/frame scopes
212
+ * @property {StyleStrategy} [styleStrategy] CSSOM strategy counters for document-level sources
213
+ * @property {Object} htmlAttrs Sanitized <html> attributes
214
+ * @property {Object} bodyAttrs Sanitized <body> attributes
215
+ * @property {string} htmlStyle Shell computed style for <html>
216
+ * @property {string} bodyStyle Shell computed style for <body>
217
+ * @property {number} scrollX
218
+ * @property {number} scrollY
219
+ * @property {number} viewportWidth
220
+ * @property {number} viewportHeight
221
+ * @property {number} pageWidth
222
+ * @property {number} pageHeight
223
+ * @property {string} url
224
+ * @property {string} title
225
+ * @property {string} streamSessionId Identity: minted per stream session
226
+ * @property {number} snapshotId Identity: minted per snapshot
227
+ */
228
+
229
+ /**
230
+ * @typedef {Object} DialogPayload
231
+ * @property {'alert'|'confirm'|'prompt'} type
232
+ * @property {'open'|'closed'} state
233
+ * @property {string} [message]
234
+ * @property {string} [defaultValue] prompt only
235
+ * @property {*} [result] on close: confirm boolean / prompt string|null
236
+ */
237
+
238
+ /**
239
+ * Mint a stream session id. Caller supplies entropy so the protocol layer
240
+ * stays pure (and replayable in tests).
241
+ * @param {number} nowMs e.g. Date.now()
242
+ * @param {string} rand short random suffix, e.g. Math.random().toString(36).slice(2, 8)
243
+ */
244
+ export function createStreamSessionId(nowMs, rand) {
245
+ return 'stream_' + nowMs.toString(36) + '_' + rand;
246
+ }
247
+
248
+ /**
249
+ * Staleness guard: should a viewer accept a message for the currently
250
+ * active stream identity? Messages with no identity are accepted
251
+ * (backward compatibility); messages with a mismatched identity are stale.
252
+ *
253
+ * @param {{streamSessionId?: string, snapshotId?: number}} msg
254
+ * @param {{streamSessionId?: string, snapshotId?: number}} active
255
+ * @returns {boolean}
256
+ */
257
+ export function isCurrentStream(msg, active) {
258
+ if (!msg) return false;
259
+ if (msg.streamSessionId && active.streamSessionId &&
260
+ msg.streamSessionId !== active.streamSessionId) {
261
+ return false;
262
+ }
263
+ if (msg.snapshotId && active.snapshotId &&
264
+ msg.snapshotId !== active.snapshotId) {
265
+ return false;
266
+ }
267
+ return true;
268
+ }