@full-self-browsing/phantom-stream 0.1.0 → 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.
Files changed (64) hide show
  1. package/README.md +48 -2
  2. package/dist/types/adapters/extension.d.ts.map +1 -1
  3. package/dist/types/adapters/playwright.d.ts.map +1 -1
  4. package/dist/types/capture/index.d.ts +150 -0
  5. package/dist/types/capture/index.d.ts.map +1 -1
  6. package/dist/types/index.d.ts +2 -0
  7. package/dist/types/player/index.d.ts +136 -0
  8. package/dist/types/player/index.d.ts.map +1 -0
  9. package/dist/types/protocol/constants.d.ts +22 -0
  10. package/dist/types/protocol/constants.d.ts.map +1 -1
  11. package/dist/types/protocol/index.d.ts +1 -0
  12. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  13. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  14. package/dist/types/protocol/messages.d.ts +326 -4
  15. package/dist/types/protocol/messages.d.ts.map +1 -1
  16. package/dist/types/recorder/index.d.ts +207 -0
  17. package/dist/types/recorder/index.d.ts.map +1 -0
  18. package/dist/types/renderer/asset-policy.d.ts +72 -0
  19. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  20. package/dist/types/renderer/diff.d.ts.map +1 -1
  21. package/dist/types/renderer/index.d.ts +61 -8
  22. package/dist/types/renderer/index.d.ts.map +1 -1
  23. package/dist/types/renderer/media-player.d.ts +114 -0
  24. package/dist/types/renderer/media-player.d.ts.map +1 -0
  25. package/dist/types/renderer/overlays.d.ts +12 -0
  26. package/dist/types/renderer/overlays.d.ts.map +1 -1
  27. package/dist/types/renderer/parser-safe.d.ts +26 -0
  28. package/dist/types/renderer/parser-safe.d.ts.map +1 -0
  29. package/dist/types/renderer/sanitize.d.ts +22 -0
  30. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  31. package/dist/types/renderer/snapshot.d.ts +38 -0
  32. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  33. package/dist/types/transport/websocket.d.ts.map +1 -1
  34. package/docs/ARCHITECTURE.md +83 -4
  35. package/docs/QUICKSTARTS.md +64 -0
  36. package/docs/SECURITY.md +279 -2
  37. package/docs/paper/OUTLINE.md +24 -91
  38. package/examples/bookmarklet-demo/viewer.html +12 -3
  39. package/examples/extension-mv3/viewer.html +10 -3
  40. package/package.json +25 -1
  41. package/src/adapters/extension.js +202 -7
  42. package/src/adapters/playwright-inject.js +645 -28
  43. package/src/adapters/playwright.js +176 -2
  44. package/src/capture/README.md +96 -1
  45. package/src/capture/index.js +1672 -40
  46. package/src/index.js +2 -0
  47. package/src/player/README.md +175 -0
  48. package/src/player/index.js +627 -0
  49. package/src/protocol/constants.js +24 -0
  50. package/src/protocol/index.js +1 -0
  51. package/src/protocol/media-reconcile.js +188 -0
  52. package/src/protocol/messages.js +195 -4
  53. package/src/recorder/README.md +225 -0
  54. package/src/recorder/index.js +487 -0
  55. package/src/renderer/README.md +111 -8
  56. package/src/renderer/asset-policy.js +172 -0
  57. package/src/renderer/diff.js +158 -15
  58. package/src/renderer/index.js +978 -21
  59. package/src/renderer/media-player.js +367 -0
  60. package/src/renderer/overlays.js +324 -0
  61. package/src/renderer/parser-safe.js +111 -0
  62. package/src/renderer/sanitize.js +25 -3
  63. package/src/renderer/snapshot.js +534 -3
  64. package/src/transport/websocket.js +36 -0
@@ -34,11 +34,142 @@
34
34
  // || inline defaulting, function expressions, named exports, explicit .js
35
35
  // import extensions, factory-time validation as the ONLY throwing site.
36
36
 
37
- import { buildSnapshotHtml, buildFramePlaceholderHtml } from './snapshot.js';
37
+ import { buildSnapshotHtml, buildFramePlaceholderHtml, gateSnapshotAssets } from './snapshot.js';
38
38
  import { applyMutations } from './diff.js';
39
- import { sanitizeFragment, scrubCssText } from './sanitize.js';
39
+ import { sanitizeFragment, scrubCssText, parseSrcsetCandidates } from './sanitize.js';
40
+ import { restoreParserSafePlaceholders } from './parser-safe.js';
40
41
  import { createOverlays, mapRectToHost, OVERLAY_CSS } from './overlays.js';
41
- import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
42
+ import { classifyAssetOrigin } from './asset-policy.js';
43
+ import { createMediaPlayer } from './media-player.js';
44
+ import { STREAM, CONTROL, BODY_NID, isCurrentStream } from '../protocol/messages.js';
45
+ import { reconcileMediaDrift, DEFAULT_MEDIA_RECONCILE_CONFIG } from '../protocol/media-reconcile.js';
46
+
47
+ // ---- Phase 12 (MSEC-01/MSEC-02): the renderer pre-write fetch gate ----
48
+ //
49
+ // v2.0 changes the viewer's verb from render-inert to FETCH. gateAssetUrl is
50
+ // the single orchestrator every write site consults BEFORE an asset URL
51
+ // reaches the mirror DOM, so the viewer's browser never issues a GET for a
52
+ // blocked origin (snapshot: pre-srcdoc string layer; diff ADD/subtree:
53
+ // pre-importNode on inert template content; diff ATTR: pre-setAttribute).
54
+ //
55
+ // Pure and fail-closed (mirrors compileMaskSelector's fail-closed-and-loud
56
+ // precedent): it takes the per-viewer posture in ctx so it is unit-testable
57
+ // in isolation and reused unchanged across all four sites. Precedence:
58
+ // 1. mediaMode 'off' -> block ALL asset fetch (no surface).
59
+ // 2. allowAssetOrigins host match -> ALLOW (explicit host widen of the
60
+ // conservative default; the only way a
61
+ // private/non-https host is reachable).
62
+ // 3. classifyAssetOrigin(url) -> classifier deny is authoritative
63
+ // (https-only + private-range deny)
64
+ // unless (2) widened it.
65
+ // 4. assetOriginPolicy(url, ctx) -> host hook, fail-closed: a throw OR any
66
+ // non-true return BLOCKS (never opens).
67
+ // 5. mediaMode 'poster' | 'reference' -> in 'poster' mode the playable-media
68
+ // kinds ('media' = <video src>, 'source'
69
+ // = <source src>) are BLOCKED so no media
70
+ // GET issues (Phase 13 CR-01: the poster
71
+ // image is the only fetch poster mode
72
+ // permits); poster images and <img>
73
+ // pass under 'poster'. 'reference' permits
74
+ // all by-reference assets.
75
+ var VALID_MEDIA_MODES = { off: true, poster: true, reference: true };
76
+
77
+ /** Extract a lowercased hostname from a URL string, or '' on parse failure. */
78
+ function assetUrlHost(url) {
79
+ try {
80
+ return new URL(String(url)).hostname.toLowerCase();
81
+ } catch (e) {
82
+ return '';
83
+ }
84
+ }
85
+
86
+ /**
87
+ * True when any candidate in a srcset value is blocked by the supplied gate.
88
+ * Reuses the shared per-candidate parser so the fragment gate covers srcset
89
+ * with the same vocabulary as the snapshot/diff gates (review WR-03/WR-04).
90
+ * Unparseable input fails closed (treated as blocked).
91
+ * @param {string} srcset
92
+ * @param {(url: string, kind: string) => { allow: boolean }} gateAsset
93
+ * @returns {boolean}
94
+ */
95
+ function srcsetHasBlockedCandidate(srcset, gateAsset) {
96
+ if (!srcset) return false;
97
+ try {
98
+ var candidates = parseSrcsetCandidates(srcset);
99
+ for (var i = 0; i < candidates.length; i++) {
100
+ var url = candidates[i].url;
101
+ if (!url) continue;
102
+ var verdict = gateAsset(url, 'image');
103
+ if (!verdict || !verdict.allow) return true;
104
+ }
105
+ return false;
106
+ } catch (e) {
107
+ return true; // unparseable srcset: fail closed
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The renderer's pre-write asset fetch gate (MSEC-01/MSEC-02). Pure: decides
113
+ * allow/deny for a single asset URL under the posture carried in ctx. Every
114
+ * branch that is not an explicit allow fails closed.
115
+ *
116
+ * @param {string} url Absolute asset URL about to be written into the mirror.
117
+ * @param {Object} [ctx] Posture: { mediaMode, allowAssetOrigins, assetOriginPolicy, kind }.
118
+ * @returns {{ allow: boolean, reason: string }}
119
+ */
120
+ export function gateAssetUrl(url, ctx) {
121
+ var c = ctx || {};
122
+ var mode = VALID_MEDIA_MODES[c.mediaMode] ? c.mediaMode : 'reference';
123
+
124
+ // (1) mediaMode 'off': no viewer fetch surface at all.
125
+ if (mode === 'off') return { allow: false, reason: 'media-off' };
126
+
127
+ // (2) allowAssetOrigins widen: an explicitly allowlisted host is reachable
128
+ // even if the conservative classifier would otherwise deny it.
129
+ var host = assetUrlHost(url);
130
+ var allowlist = Array.isArray(c.allowAssetOrigins) ? c.allowAssetOrigins : null;
131
+ var widened = false;
132
+ if (allowlist && host) {
133
+ for (var i = 0; i < allowlist.length; i++) {
134
+ if (String(allowlist[i]).toLowerCase() === host) { widened = true; break; }
135
+ }
136
+ }
137
+
138
+ // (3) classifier: authoritative deny unless (2) widened the host.
139
+ if (!widened) {
140
+ var verdict = classifyAssetOrigin(url);
141
+ if (!verdict.allowed) return { allow: false, reason: verdict.reason };
142
+ }
143
+
144
+ // (4) host hook, fail-closed: throw OR non-true -> block.
145
+ if (typeof c.assetOriginPolicy === 'function') {
146
+ var ok;
147
+ try {
148
+ ok = c.assetOriginPolicy(url, c);
149
+ } catch (e) {
150
+ return { allow: false, reason: 'hook-threw' };
151
+ }
152
+ if (ok !== true) return { allow: false, reason: 'hook-denied' };
153
+ }
154
+
155
+ // (5) posture: in 'poster' mode the ONLY fetch poster mode permits is the
156
+ // poster image itself -- no playable media source may issue a GET (CR-01 /
157
+ // 13-RESEARCH Open Q3). A playable source fetches the full media bytes, which
158
+ // is exactly the GET poster mode exists to suppress; this MUST be enforced at
159
+ // the STRING layer (the authoritative pre-srcdoc gate -- the parser prefetches
160
+ // <video src>/<source src> DURING parse, before any post-parse scrub can run).
161
+ // kinds 'media' (<video src>) and 'source' (<source src>) are the playable-
162
+ // source kinds; 'poster' and 'image' stay allowed (the poster image is the
163
+ // one thing poster mode renders). 'reference' mode permits all by-reference
164
+ // assets and is unaffected. Fail-closed posture, mirroring the gate's other
165
+ // explicit denies.
166
+ if (mode === 'poster' && (c.kind === 'media' || c.kind === 'source')) {
167
+ return { allow: false, reason: 'poster-mode-media' };
168
+ }
169
+
170
+ // 'poster' permits poster images; 'reference' permits all by-reference assets.
171
+ return { allow: true, reason: 'ok' };
172
+ }
42
173
 
43
174
  /**
44
175
  * The host-injected viewer transport. Mirrors the capture Transport's
@@ -100,13 +231,33 @@ import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
100
231
  * Hide the local node highlight. Idempotent.
101
232
  * @property {(nid: string|number, options?: {reason?: string}) => string|null} requestSubtree
102
233
  * Request a bounded fresh subtree for an indexed truncated marker. Returns
103
- * the generated requestId, or null when the nid is invalid, missing, or
104
- * already in flight.
234
+ * the generated requestId, or null when the nid is invalid, missing,
235
+ * already in flight, or the reserved BODY_NID (the body is a structural
236
+ * anchor, not a recoverable subtree).
105
237
  * @property {(kind: string, renderFn: (payload: *, anchorRect: ?Object, layer: Element) => void) => void} registerOverlay
106
238
  * Register a custom overlay kind (delegates to the overlays registry --
107
239
  * the host-facing extension seam from D-10).
108
- * @property {(eventName: 'state'|'health', handler: (event: Object) => void) => (() => void)} on
109
- * Subscribe to host-facing lifecycle and health events. Returns unsubscribe.
240
+ * @property {(eventName: 'state'|'health'|'loaded', handler: (event: Object) => void) => (() => void)} on
241
+ * Subscribe to host-facing lifecycle, health, and loaded events. Returns
242
+ * unsubscribe. 'state' and 'health' call the handler immediately with the
243
+ * current value; 'loaded' never replays loads that happened before the
244
+ * subscription (see ViewerLoadedEvent).
245
+ * @property {(payload: Object) => void} handleSnapshot
246
+ * Host-driven snapshot entry point. Accepts a bare SnapshotPayload or a
247
+ * { type, payload } envelope and behaves exactly like the STREAM.SNAPSHOT
248
+ * dispatch target (identity adopted synchronously, mirror document loaded
249
+ * later; subscribe to 'loaded' to learn when it is ready).
250
+ */
251
+
252
+ /**
253
+ * Payload of the viewer 'loaded' event: the stream identity active when a
254
+ * snapshot's mirror document finished loading. Fired after the viewer has
255
+ * flipped to streaming, once per loaded snapshot document, never for the
256
+ * bare about:blank load, and never replayed to late subscribers.
257
+ *
258
+ * @typedef {Object} ViewerLoadedEvent
259
+ * @property {string} streamSessionId
260
+ * @property {number} snapshotId
110
261
  */
111
262
 
112
263
  /**
@@ -152,13 +303,33 @@ export function computeScale(pageW, pageH, containerW, containerH) {
152
303
  export function createViewer(options) {
153
304
  var cfg = options || {};
154
305
 
155
- var container = cfg.container;
306
+ // Container resolution: `mount` is accepted as an alias for `container`
307
+ // (the host-driven asset-gate path and embedders that think in "mount
308
+ // points" use it). When the resolved container carries no ownerDocument,
309
+ // cfg.document is the construction-document fallback (see `doc` below).
310
+ var hostDriven = !cfg.container && !!cfg.mount; // mount alias == host-driven API
311
+ var container = cfg.container || cfg.mount;
156
312
  if (!container || typeof container.appendChild !== 'function') {
157
313
  throw new Error('viewer-container-required');
158
314
  }
315
+ // Transport requirement depends on the API style. The wire-driven API
316
+ // (cfg.container) REQUIRES a complete transport -- the original contract,
317
+ // and a partial { send } / { onMessage } still throws. The host-driven API
318
+ // (cfg.mount) makes transport OPTIONAL: such viewers drive handleSnapshot
319
+ // directly (Phase 12 asset path) and need no socket, so a no-op transport
320
+ // keeps the dispatch wiring intact without one. A provided transport is
321
+ // always validated regardless of style.
159
322
  var transport = cfg.transport;
160
- if (!transport || typeof transport.send !== 'function'
161
- || typeof transport.onMessage !== 'function') {
323
+ if (transport) {
324
+ if (typeof transport.send !== 'function' || typeof transport.onMessage !== 'function') {
325
+ throw new Error('viewer-transport-required');
326
+ }
327
+ } else if (hostDriven) {
328
+ transport = {
329
+ send: function () {},
330
+ onMessage: function () { return function () {}; }
331
+ };
332
+ } else {
162
333
  throw new Error('viewer-transport-required');
163
334
  }
164
335
  var logger = cfg.logger || {
@@ -170,9 +341,202 @@ export function createViewer(options) {
170
341
  ? Math.max(0, cfg.disconnectDelayMs)
171
342
  : 750;
172
343
 
344
+ // Phase 12 asset-fetch posture (MSEC-01/MSEC-02). Validate mediaMode at
345
+ // factory time -- the ONLY sanctioned throw site (capture precedent); an
346
+ // invalid value is a host misconfiguration, not a per-message error.
347
+ var mediaMode = cfg.mediaMode == null ? 'reference' : String(cfg.mediaMode);
348
+ if (!VALID_MEDIA_MODES[mediaMode]) {
349
+ throw new Error('viewer-mediamode-invalid');
350
+ }
351
+ var assetOriginPolicy = typeof cfg.assetOriginPolicy === 'function'
352
+ ? cfg.assetOriginPolicy
353
+ : null;
354
+ var allowAssetOrigins = Array.isArray(cfg.allowAssetOrigins)
355
+ ? cfg.allowAssetOrigins.slice()
356
+ : null;
357
+ // Phase 13 (MEDIA-05): onMediaBlocked is a CONFIG callback (the
358
+ // assetOriginPolicy-hook family), NOT an on('state'|'health') subscription
359
+ // (which throws on other names). Invoked with the element nid when a
360
+ // programmatic play() rejects with NotAllowedError; its errors are contained
361
+ // to the logger (never rethrown). mediaReconcileConfig overrides merge over
362
+ // DEFAULT_MEDIA_RECONCILE_CONFIG (the reconciler tolerances stay tunable).
363
+ var onMediaBlocked = typeof cfg.onMediaBlocked === 'function' ? cfg.onMediaBlocked : null;
364
+ var mediaReconcileConfig = (cfg.mediaReconcileConfig && typeof cfg.mediaReconcileConfig === 'object')
365
+ ? cfg.mediaReconcileConfig
366
+ : DEFAULT_MEDIA_RECONCILE_CONFIG;
367
+ // Phase 14 (MADPT-01/03): the adaptive-player config-callback family (the
368
+ // onMediaBlocked/assetOriginPolicy family, NOT the throwing on() allowlist).
369
+ // playerFactory is the host-provided HLS/DASH/Shaka player seam; absent, the
370
+ // optional lazy hls.js path (or degrade-to-poster) handles HLS. onMediaUnavailable
371
+ // is the degrade-reason callback (no-manifest|no-player|mse-opaque|drm); a non-
372
+ // function is ignored (graceful absence). Both are contained -- a throwing host
373
+ // callback can never wedge the mirror.
374
+ var playerFactory = typeof cfg.playerFactory === 'function' ? cfg.playerFactory : null;
375
+ var onMediaUnavailable = typeof cfg.onMediaUnavailable === 'function' ? cfg.onMediaUnavailable : null;
376
+ // Per-viewer gate closure: every write site (snapshot string layer, diff
377
+ // ADD/ATTR, subtree) calls this so the posture is applied uniformly and
378
+ // fail-closed. kind defaults to 'image' (P12 image scope).
379
+ function gateAsset(url, kind) {
380
+ return gateAssetUrl(url, {
381
+ mediaMode: mediaMode,
382
+ allowAssetOrigins: allowAssetOrigins,
383
+ assetOriginPolicy: assetOriginPolicy,
384
+ kind: kind || 'image'
385
+ });
386
+ }
387
+
388
+ // URL gate for parser-safe restores in LIVE documents (quick task
389
+ // 261202-jwf). The snapshot string-layer gate never scans <ps-node>, and a
390
+ // restored <img> in the live mirror would fetch as soon as its src is set,
391
+ // before the post-parse gate runs. restoreParserSafePlaceholders therefore
392
+ // asks this filter for src / srcset / data-ps-currentsrc on restored img,
393
+ // input, source and track, and never sets a blocked value (null = drop).
394
+ function restoreUrlFilter(tag, attr, value) {
395
+ if (attr === 'srcset') return srcsetHasBlockedCandidate(value, gateAsset) ? null : value;
396
+ var kind = tag === 'source' ? 'source' : (tag === 'track' ? 'media' : 'image');
397
+ return gateAsset(value, kind).allow ? value : null;
398
+ }
399
+
400
+ /**
401
+ * Build the renderer-owned dimensioned blocked-origin placeholder ELEMENT
402
+ * (the DOM-fragment twin of snapshot.js's string placeholder; renderer-owned
403
+ * per the project's duplicate-don't-couple style). Preserves the source
404
+ * element's dimensions (rr_width/rr_height or width/height) so layout stays
405
+ * stable; replacing an <img> 1:1 with this <div> keeps the positional nid
406
+ * index consistent (the renderer pairs elements by the nodeIds sidecar
407
+ * positionally, not by any live identity attribute -- Phase 7). No fetchable
408
+ * attribute is set.
409
+ * @param {Document} ownerDoc
410
+ * @param {Element} el The blocked <img>.
411
+ * @returns {Element}
412
+ */
413
+ function buildAssetPlaceholderEl(ownerDoc, el) {
414
+ var ph = ownerDoc.createElement('div');
415
+ ph.setAttribute('data-ps-asset-unavailable', 'blocked-origin');
416
+ var w = (el.getAttribute && (el.getAttribute('rr_width') || el.getAttribute('width'))) || '';
417
+ var h = (el.getAttribute && (el.getAttribute('rr_height') || el.getAttribute('height'))) || '';
418
+ if (w) ph.setAttribute('rr_width', w);
419
+ if (h) ph.setAttribute('rr_height', h);
420
+ return ph;
421
+ }
422
+
423
+ /**
424
+ * Pre-write asset gate over a PARSED, inert DOM subtree (defense-in-depth
425
+ * for the post-parse mirror body and the authoritative gate for diff ADD /
426
+ * subtree-response template content, which is inert and fires no fetch). For
427
+ * each <img>: apply the ASST-03 currentSrc pin (effective src =
428
+ * data-ps-currentsrc, neutralize srcset/sizes), then gateAsset the effective
429
+ * src; blocked -> replace the <img> with the dimensioned placeholder. Safe
430
+ * on any Document-owned root; contained per-element so one bad node never
431
+ * aborts the pass.
432
+ * @param {Node} rootNode A parsed fragment/body (template.content or mirror body).
433
+ */
434
+ function gateFragmentAssets(rootNode) {
435
+ if (!rootNode || typeof rootNode.querySelectorAll !== 'function') return;
436
+ var ownerDoc = rootNode.ownerDocument || (rootNode.nodeType === 9 ? rootNode : null);
437
+ if (!ownerDoc) return;
438
+ var imgs = rootNode.querySelectorAll('img');
439
+ for (var i = 0; i < imgs.length; i++) {
440
+ var el = imgs[i];
441
+ try {
442
+ var pinned = el.getAttribute('data-ps-currentsrc');
443
+ var effective = el.getAttribute('src');
444
+ if (pinned) {
445
+ effective = pinned;
446
+ el.setAttribute('src', pinned);
447
+ el.removeAttribute('srcset');
448
+ el.removeAttribute('sizes');
449
+ el.removeAttribute('data-ps-currentsrc');
450
+ }
451
+ if (effective && !gateAsset(effective, 'image').allow) {
452
+ var ph = buildAssetPlaceholderEl(ownerDoc, el);
453
+ if (el.parentNode) el.parentNode.replaceChild(ph, el);
454
+ continue;
455
+ }
456
+ // srcset gate (review WR-04): an <img srcset> with NO src (and no
457
+ // currentsrc pin, which removes srcset above) is otherwise imported
458
+ // with its blocked candidate intact, where the browser can fetch it.
459
+ // Gate every candidate; if any is blocked, replace with the
460
+ // placeholder when there is no allowed src, else strip srcset so only
461
+ // the allowed src can fetch.
462
+ var srcset = el.getAttribute('srcset');
463
+ if (srcset && srcsetHasBlockedCandidate(srcset, gateAsset)) {
464
+ if (!effective) {
465
+ var phSrcset = buildAssetPlaceholderEl(ownerDoc, el);
466
+ if (el.parentNode) el.parentNode.replaceChild(phSrcset, el);
467
+ } else {
468
+ el.removeAttribute('srcset');
469
+ }
470
+ }
471
+ } catch (e) {
472
+ logger.warn('[Renderer] asset gate pass failed for an element', {
473
+ error: e && e.message ? e.message : String(e)
474
+ });
475
+ }
476
+ }
477
+ gateFragmentMedia(rootNode, ownerDoc);
478
+ }
479
+
480
+ /**
481
+ * Post-parse media-asset gate (Phase 13 defense-in-depth + poster-mode
482
+ * source neutralization). The STRING-layer gateSnapshotAssets is the
483
+ * authoritative pre-parse control (the parser fetches during parse); this
484
+ * pass covers the diff ADD/subtree inert-fragment path and re-asserts the
485
+ * posture on the parsed body. For each <video>/<audio>:
486
+ * - gate src + poster; a blocked URL is removed (no fetchable attribute).
487
+ * - mediaMode 'poster': strip src and every child <source src> so NO media
488
+ * GET issues while the gated poster is kept (13-RESEARCH Open Q3).
489
+ * For each standalone <source>: gate src; blocked or poster-mode -> removed.
490
+ * @param {Node} rootNode
491
+ * @param {Document} ownerDoc
492
+ */
493
+ function gateFragmentMedia(rootNode, ownerDoc) {
494
+ var posterOnly = (mediaMode === 'poster');
495
+ var media = rootNode.querySelectorAll('video, audio');
496
+ for (var i = 0; i < media.length; i++) {
497
+ var el = media[i];
498
+ try {
499
+ var src = el.getAttribute('src');
500
+ if (src && (posterOnly || !gateAsset(src, 'media').allow)) {
501
+ el.removeAttribute('src');
502
+ }
503
+ var poster = el.getAttribute('poster');
504
+ if (poster && !gateAsset(poster, 'poster').allow) {
505
+ el.removeAttribute('poster');
506
+ }
507
+ // Child <source> elements bind the playable source; in poster mode or
508
+ // when blocked, neutralize their src so the element selects nothing.
509
+ var childSources = el.querySelectorAll('source');
510
+ for (var j = 0; j < childSources.length; j++) {
511
+ var cs = childSources[j];
512
+ var csSrc = cs.getAttribute('src');
513
+ if (csSrc && (posterOnly || !gateAsset(csSrc, 'media').allow)) {
514
+ cs.removeAttribute('src');
515
+ }
516
+ }
517
+ } catch (e) {
518
+ logger.warn('[Renderer] media gate pass failed for an element', {
519
+ error: e && e.message ? e.message : String(e)
520
+ });
521
+ }
522
+ }
523
+ // Standalone <source> (not under a video/audio we already walked, e.g. a
524
+ // detached fragment) -- gate defensively.
525
+ var looseSources = rootNode.querySelectorAll('source');
526
+ for (var k = 0; k < looseSources.length; k++) {
527
+ var ls = looseSources[k];
528
+ try {
529
+ var lsSrc = ls.getAttribute('src');
530
+ if (lsSrc && (posterOnly || !gateAsset(lsSrc, 'media').allow)) {
531
+ ls.removeAttribute('src');
532
+ }
533
+ } catch (e2) { /* contained: one bad node never aborts the pass */ }
534
+ }
535
+ }
536
+
173
537
  // All DOM construction happens in the container's own document so the
174
538
  // viewer works in any window (host page, jsdom test, future multi-doc).
175
- var doc = container.ownerDocument;
539
+ var doc = container.ownerDocument || cfg.document;
176
540
  var win = doc.defaultView;
177
541
 
178
542
  // --- Viewer root: fills the container, clips the scaled mirror, and
@@ -227,12 +591,25 @@ export function createViewer(options) {
227
591
  try {
228
592
  var scrubDoc = iframe.contentDocument;
229
593
  if (scrubDoc && scrubDoc.body) {
594
+ // Parser-safe restore (quick task 261202-jwf): right after the parse,
595
+ // before the scrub and identity pairing, with the live-document URL gate.
596
+ restoreParserSafePlaceholders(scrubDoc.body, { filterUrl: restoreUrlFilter });
230
597
  sanitizeFragment(scrubDoc.body, sanitizeCounters, logger);
598
+ // DEFENSE-IN-DEPTH (MSEC-01): the authoritative snapshot gate already
599
+ // ran at the string layer (handleSnapshot) so the parser never saw a
600
+ // blocked URL; this post-parse pass re-gates the parsed mirror body to
601
+ // catch any asset a future write path introduces and to keep the pin
602
+ // consistent on the live mirror DOM.
603
+ gateFragmentAssets(scrubDoc.body);
231
604
  if (lastSnapshotPayload) {
232
- resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || []);
605
+ resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || [], lastSnapshotPayload.bodyNid);
233
606
  installStyleSources(scrubDoc, lastSnapshotPayload.styleSources || [], { kind: 'document' });
234
607
  installShadowRoots(scrubDoc, lastSnapshotPayload.shadowRoots || []);
235
608
  installFrames(scrubDoc, lastSnapshotPayload.frames || []);
609
+ // Phase 13 (MEDIA-02, Pitfall 7): apply the snapshot media[] baseline
610
+ // once now that nids are paired -- the INITIAL desired state -- then
611
+ // defer to the reconciler. No-op in poster/off mode (no playback).
612
+ applyMediaBaseline(lastSnapshotPayload.media);
236
613
  }
237
614
  }
238
615
  } catch (e) {
@@ -261,6 +638,14 @@ export function createViewer(options) {
261
638
  } catch (e) { /* ignore: scroll restore is best-effort */ }
262
639
  viewerState = 'streaming';
263
640
  iframe.style.display = '';
641
+ // The 'loaded' event exists because handleSnapshot adopts the new
642
+ // identity synchronously while the mirror document loads later, and
643
+ // mutations sent before this load are dropped (or miss against the
644
+ // cleared identity index). Hosts that drive snapshots themselves (the
645
+ // player) wait for this event before sending that snapshot's
646
+ // mutations. It is the LAST statement so the viewer is already
647
+ // streaming and un-hidden when handlers run.
648
+ notifyLoaded();
264
649
  });
265
650
  root.appendChild(iframe);
266
651
 
@@ -270,6 +655,45 @@ export function createViewer(options) {
270
655
  var overlays = createOverlays({ document: doc, logger: logger });
271
656
  root.appendChild(overlays.layer);
272
657
 
658
+ // --- Phase 14 (MADPT-01/03): the parent-realm adaptive media player. Runs
659
+ // ENTIRELY in this (host/parent) realm; the mirror iframe stays exactly
660
+ // sandbox="allow-same-origin" (no allow-scripts). attach() binds an HLS/DASH
661
+ // manifest to the inert in-iframe <video> (native-HLS-first -> playerFactory
662
+ // -> optional lazy hls.js -> degrade-to-poster); the single degrade(nid,reason)
663
+ // sink shows the media-unavailable overlay + invokes onMediaUnavailable. The
664
+ // onMediaUnavailable host callback is wrapped in the same containment as
665
+ // onMediaBlocked (safeInvokeMediaHook) so a throwing host hook can never wedge
666
+ // the mirror; a throwing playerFactory is contained by the player's degrade
667
+ // sink. Plan 03 routes STREAM.MEDIA_HINT to attach() and calls destroyAll() on
668
+ // a re-snapshot (Pattern 2 -- teardown on new identity). gateAsset reuses the
669
+ // Phase 12 fail-closed gate so a manifest/segment URL is re-gated at the viewer
670
+ // (defense in depth -- a hint is attacker-influenced). win is the PARENT realm
671
+ // (the MSE feature-detect surface), NOT iframe.contentWindow. ---
672
+ var mediaPlayer = createMediaPlayer({
673
+ doc: doc,
674
+ win: win,
675
+ gateAsset: gateAsset,
676
+ logger: logger,
677
+ playerFactory: playerFactory,
678
+ onMediaUnavailable: function (nid, reason) {
679
+ safeInvokeMediaHook(function (n) {
680
+ if (onMediaUnavailable) onMediaUnavailable(n, reason);
681
+ }, nid);
682
+ },
683
+ showOverlay: function (kind, payload, ctx) { return overlays.show(kind, payload, ctx); },
684
+ resolveNidRect: resolveNidRect,
685
+ ensurePlaying: ensurePlaying
686
+ });
687
+ // Page-scope adaptive hints awaiting an MSE-opaque element to play (most-
688
+ // recent-wins per kind). An element-scope hint binds immediately; a page-scope
689
+ // hint sits here until handleMedia sees a source-less element start, then is
690
+ // consumed (14-RESEARCH "manifest->element correlation": never block on perfect
691
+ // correlation). Cleared on every new stream identity in handleSnapshot.
692
+ var pendingHints = new Map();
693
+ // nids that have already consumed/bound an adaptive hint this generation, so a
694
+ // page hint is attached at most once per element (idempotent consumption).
695
+ var hintBoundNids = new Set();
696
+
273
697
  // Auto-attach (D-01): creation yields a live, ready-to-stream mirror.
274
698
  container.appendChild(root);
275
699
 
@@ -283,6 +707,7 @@ export function createViewer(options) {
283
707
  };
284
708
  var stateListeners = new Set();
285
709
  var healthListeners = new Set();
710
+ var loadedListeners = new Set(); // 'loaded' subscribers; never replayed
286
711
  var disconnectTimer = null;
287
712
  var active = { streamSessionId: '', snapshotId: 0 };
288
713
  var lastScroll = { x: 0, y: 0 };
@@ -310,6 +735,11 @@ export function createViewer(options) {
310
735
  var destroyed = false;
311
736
  var nidToNode = new Map();
312
737
  var nodeToNid = new WeakMap();
738
+ // Phase 13 (Pitfall 7): nids whose snapshot media[] baseline has been applied
739
+ // once. The baseline is the INITIAL desired state; after first bind control
740
+ // passes to the reconciler (subsequent STREAM.MEDIA), so the baseline never
741
+ // re-fights live drift on a re-snapshot. Reset per snapshot identity.
742
+ var mediaFirstBind = new Set();
313
743
  var frameLoadHandlers = new WeakMap();
314
744
  var nodeHighlightEl = null;
315
745
  var pendingSubtreeRequests = new Map();
@@ -407,6 +837,26 @@ export function createViewer(options) {
407
837
  });
408
838
  }
409
839
 
840
+ /**
841
+ * Tell 'loaded' subscribers that the current snapshot's mirror document
842
+ * finished loading. Each handler gets its own fresh payload copy; a
843
+ * throwing handler is contained to the logger and never starves the
844
+ * others. Iterates a copy so a handler may unsubscribe itself.
845
+ */
846
+ function notifyLoaded() {
847
+ var event = {
848
+ streamSessionId: active.streamSessionId || '',
849
+ snapshotId: active.snapshotId || 0
850
+ };
851
+ Array.from(loadedListeners).forEach(function (handler) {
852
+ try {
853
+ handler({ streamSessionId: event.streamSessionId, snapshotId: event.snapshotId });
854
+ } catch (err) {
855
+ logger.error('[Renderer] event handler failed', 'loaded', err);
856
+ }
857
+ });
858
+ }
859
+
410
860
  function notifyHealth() {
411
861
  var event = healthSnapshot();
412
862
  healthListeners.forEach(function (handler) {
@@ -452,9 +902,18 @@ export function createViewer(options) {
452
902
  }
453
903
 
454
904
  function on(eventName, handler) {
455
- if ((eventName !== 'state' && eventName !== 'health') || typeof handler !== 'function') {
905
+ if ((eventName !== 'state' && eventName !== 'health' && eventName !== 'loaded') ||
906
+ typeof handler !== 'function') {
456
907
  throw new Error('viewer-event-unsupported');
457
908
  }
909
+ if (eventName === 'loaded') {
910
+ // No immediate call: 'loaded' reports future document loads only and
911
+ // never replays loads that happened before the subscription.
912
+ loadedListeners.add(handler);
913
+ return function unsubscribeViewerEvent() {
914
+ loadedListeners.delete(handler);
915
+ };
916
+ }
458
917
  var listeners = eventName === 'state' ? stateListeners : healthListeners;
459
918
  listeners.add(handler);
460
919
  try {
@@ -526,6 +985,10 @@ export function createViewer(options) {
526
985
  if (nid === undefined || nid === null) return null;
527
986
  var key = String(nid);
528
987
  if (!key) return null;
988
+ // The body is a structural anchor, not a recoverable subtree (capture
989
+ // answers a body request content-free 'untracked'); hosts that need a
990
+ // full refresh call stop() then start() on the capture.
991
+ if (key === BODY_NID) return null;
529
992
  var target = resolveIndexedNode(key);
530
993
  if (!target) return null;
531
994
  if (pendingSubtreeRequests.has(key)) return null;
@@ -656,7 +1119,7 @@ export function createViewer(options) {
656
1119
  }
657
1120
  }
658
1121
 
659
- function resetIdentityIndex(targetDoc, nodeIds) {
1122
+ function resetIdentityIndex(targetDoc, nodeIds, bodyNid) {
660
1123
  clearIdentityIndex();
661
1124
  if (!targetDoc || !targetDoc.body) return;
662
1125
  pairIdentityElements(
@@ -664,6 +1127,16 @@ export function createViewer(options) {
664
1127
  nodeIds,
665
1128
  'snapshot'
666
1129
  );
1130
+ // Reserved main-body identity (quick task 261127-u5c): body-level add ops
1131
+ // use it as their parent and body attr ops as their target. Captures older
1132
+ // than that fix send no bodyNid and index exactly as before. Sidecar
1133
+ // pairing stays authoritative: a non-conforming payload whose bodyNid
1134
+ // reuses an already paired nid never re-points that nid at the body.
1135
+ if (bodyNid !== undefined && bodyNid !== null && bodyNid !== ''
1136
+ && !nidToNode.has(String(bodyNid))) {
1137
+ nidToNode.set(String(bodyNid), targetDoc.body);
1138
+ nodeToNid.set(targetDoc.body, String(bodyNid));
1139
+ }
667
1140
  }
668
1141
 
669
1142
  function resolveIndexedNode(nid) {
@@ -719,11 +1192,25 @@ export function createViewer(options) {
719
1192
  }
720
1193
  }
721
1194
 
1195
+ // First DIRECT child of rootNode that is an installed style source with a
1196
+ // numeric data-ps-style-order greater than order, or null (append). Children
1197
+ // without a parsable order, such as string-level snapshot tags before the
1198
+ // load-time re-install, are skipped.
1199
+ function nextStyleSourceByOrder(rootNode, order) {
1200
+ for (var child = rootNode.firstElementChild; child; child = child.nextElementSibling) {
1201
+ if (!child.hasAttribute('data-ps-style-source-id')) continue;
1202
+ var raw = child.getAttribute('data-ps-style-order');
1203
+ if (raw === null || raw === '') continue;
1204
+ var childOrder = Number(raw);
1205
+ if (isFinite(childOrder) && childOrder > order) return child;
1206
+ }
1207
+ return null;
1208
+ }
1209
+
722
1210
  function installOneStyleSource(targetDoc, rootNode, source) {
723
1211
  var s = source || {};
724
1212
  if (!targetDoc || !rootNode || !s.sourceId) return false;
725
1213
  var existing = findStyleSourceElement(rootNode, s.sourceId);
726
- if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
727
1214
  var el = null;
728
1215
  if (s.href && !hasDangerousStylesheetUrl(s.href)) {
729
1216
  el = targetDoc.createElement('link');
@@ -733,10 +1220,26 @@ export function createViewer(options) {
733
1220
  el = targetDoc.createElement('style');
734
1221
  setScopedStyleText(el, s.cssText || '');
735
1222
  }
1223
+ var order = typeof s.order === 'number' ? s.order : 0;
736
1224
  el.setAttribute('data-ps-style-source-id', String(s.sourceId));
1225
+ el.setAttribute('data-ps-style-order', String(order));
737
1226
  if (s.media) el.setAttribute('media', String(s.media));
738
1227
  if (s.disabled) el.setAttribute('data-ps-style-disabled', 'true');
739
- rootNode.appendChild(el);
1228
+ // Cascade order (quick task 261202-jwf, D 1.5). Capture sends only the
1229
+ // sources that changed, so a replaced source keeps its position and a new
1230
+ // source goes before the first source in this root with a greater order.
1231
+ if (existing && existing.parentNode) {
1232
+ existing.parentNode.insertBefore(el, existing);
1233
+ existing.parentNode.removeChild(existing);
1234
+ } else {
1235
+ rootNode.insertBefore(el, nextStyleSourceByOrder(rootNode, order));
1236
+ }
1237
+ // A disabled source must not apply in the mirror -- the diagnostic
1238
+ // attribute above is not enough. Disable the sheet itself, set after
1239
+ // insertion so the StyleSheet object exists to be disabled.
1240
+ if (s.disabled) {
1241
+ try { el.disabled = true; } catch (err) { /* CSSOM disabled unsupported */ }
1242
+ }
740
1243
  return true;
741
1244
  }
742
1245
 
@@ -809,8 +1312,7 @@ export function createViewer(options) {
809
1312
  });
810
1313
  return false;
811
1314
  }
812
- var existing = findStyleSourceElement(resolved.root, sourceId);
813
- if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
1315
+ // installOneStyleSource replaces an existing node in place (cascade order).
814
1316
  return installOneStyleSource(resolved.doc, resolved.root, source || {});
815
1317
  }
816
1318
 
@@ -861,6 +1363,7 @@ export function createViewer(options) {
861
1363
 
862
1364
  var tpl = targetDoc.createElement('template');
863
1365
  tpl.innerHTML = p.html || '';
1366
+ restoreParserSafePlaceholders(tpl.content);
864
1367
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
865
1368
  shadowRoot.appendChild(targetDoc.importNode(tpl.content, true));
866
1369
  installStyleSources(targetDoc, p.styleSources || [], { kind: 'shadow', hostNid: p.hostNid });
@@ -895,6 +1398,9 @@ export function createViewer(options) {
895
1398
  var frameDoc = frameEl && frameEl.contentDocument;
896
1399
  if (!frameDoc || !frameDoc.documentElement || !frameDoc.body) return false;
897
1400
  removeIndexedSubtree(frameDoc.documentElement);
1401
+ // Parser-safe restore before the scrub and pairing. This also runs from
1402
+ // the frame load handler; repeating it is harmless.
1403
+ restoreParserSafePlaceholders(frameDoc.body, { filterUrl: restoreUrlFilter });
898
1404
  sanitizeFragment(frameDoc.body, sanitizeCounters, logger);
899
1405
  if (p.htmlNid) {
900
1406
  nidToNode.set(String(p.htmlNid), frameDoc.documentElement);
@@ -1087,6 +1593,13 @@ export function createViewer(options) {
1087
1593
  */
1088
1594
  function handleSnapshot(payload) {
1089
1595
  var p = payload || {};
1596
+ // Accept either a bare SnapshotPayload (the dispatch() path passes
1597
+ // payload directly) or a full { type, payload } message envelope (the
1598
+ // host-driven handleSnapshot entry point on the returned handle). Unwrap
1599
+ // the envelope so both call shapes resolve the same payload.
1600
+ if (typeof p.html !== 'string' && p.payload && typeof p.payload === 'object') {
1601
+ p = p.payload;
1602
+ }
1090
1603
  if (typeof p.html !== 'string') {
1091
1604
  logger.error('[Renderer] snapshot missing html');
1092
1605
  return;
@@ -1104,7 +1617,31 @@ export function createViewer(options) {
1104
1617
  lastScroll.y = p.scrollY || 0;
1105
1618
  lastSnapshotPayload = p;
1106
1619
  clearIdentityIndex();
1107
- iframe.srcdoc = buildSnapshotHtml(p);
1620
+ mediaFirstBind.clear(); // new identity: re-bind media baseline on next load
1621
+ // Phase 14 (Pattern 2 -- teardown on new identity / Pitfall 2 -- object-URL
1622
+ // leak): a new stream identity tears down EVERY live adaptive player before
1623
+ // the new mirror document replaces the prior child elements, revoking parent-
1624
+ // realm object URLs and freeing buffers so a re-snapshot never orphans a
1625
+ // player bound to a now-dead element. It also invalidates any stored page hint
1626
+ // and the per-element bound set (a prior page's manifest must never bind a new
1627
+ // page's element).
1628
+ mediaPlayer.destroyAll();
1629
+ pendingHints.clear();
1630
+ hintBoundNids.clear();
1631
+ // PRE-WRITE FETCH GATE (MSEC-01, THE timing rule -- 12-RESEARCH Pitfall 1):
1632
+ // rewrite blocked <img> assets to the dimensioned blocked-origin
1633
+ // placeholder and apply the ASST-03 currentSrc pin at the STRING layer,
1634
+ // BEFORE buildSnapshotHtml assembles the srcdoc, so a real browser's
1635
+ // parser never sees a blocked URL and never issues the GET. Operates on a
1636
+ // shallow payload copy (the wire payload object stays intact for the
1637
+ // post-parse scrub's nodeIds/styleSources re-read). This rewrites typed
1638
+ // values we are emitting -- NOT a scrub-then-reparse of sanitized HTML
1639
+ // (snapshot.js header lines 14-19 invariant preserved). The post-parse
1640
+ // DOM gate below is defense-in-depth for diffs/robustness.
1641
+ var gatedPayload = Object.assign({}, p, {
1642
+ html: gateSnapshotAssets(p.html, gateAsset)
1643
+ });
1644
+ iframe.srcdoc = buildSnapshotHtml(gatedPayload);
1108
1645
  markLive('snapshot');
1109
1646
  }
1110
1647
 
@@ -1137,7 +1674,12 @@ export function createViewer(options) {
1137
1674
  installFrames(cd, frames || []);
1138
1675
  },
1139
1676
  applyStyleSource: applyStyleSource,
1140
- removeStyleSource: removeStyleSource
1677
+ removeStyleSource: removeStyleSource,
1678
+ // Phase 12 (MSEC-01) pre-write asset gate hooks for the diff applier:
1679
+ // ADD template content is gated as an inert fragment; ATTR src/poster
1680
+ // is gated per-URL before setAttribute.
1681
+ gateFragmentAssets: gateFragmentAssets,
1682
+ gateAssetUrl: gateAsset
1141
1683
  }
1142
1684
  });
1143
1685
  if (!resyncPending) markLive('mutations');
@@ -1163,7 +1705,11 @@ export function createViewer(options) {
1163
1705
 
1164
1706
  var tpl = targetDoc.createElement('template');
1165
1707
  tpl.innerHTML = p.html || '';
1708
+ restoreParserSafePlaceholders(tpl.content);
1166
1709
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
1710
+ // PRE-WRITE FETCH GATE (MSEC-01): template content is inert (no fetch), so
1711
+ // gating here -- before importNode -- is pre-write and safe.
1712
+ gateFragmentAssets(tpl.content);
1167
1713
  var newNode = tpl.content.firstElementChild;
1168
1714
  if (!newNode) {
1169
1715
  logger.warn('[Renderer] subtree response dropped: html parsed to no element', {
@@ -1233,6 +1779,405 @@ export function createViewer(options) {
1233
1779
  markLive('dialog');
1234
1780
  }
1235
1781
 
1782
+ // --- Phase 13 media driver (MEDIA-01/05): the in-iframe <video>/<audio> is
1783
+ // inert (no allow-scripts); the PARENT realm is the only tier that can drive
1784
+ // it cross-realm. handleMedia resolves the nid, runs the pure reconciler, and
1785
+ // applies the action by calling methods on the in-iframe element. The element
1786
+ // is NEVER scripted; affordances live in the parent-realm overlay layer. ---
1787
+
1788
+ /** Invoke a host hook in containment -> logger, never rethrow (T-13-12). */
1789
+ function safeInvokeMediaHook(fn, nid) {
1790
+ if (typeof fn !== 'function') return;
1791
+ try {
1792
+ fn(nid);
1793
+ } catch (err) {
1794
+ logger.error('[Renderer] onMediaBlocked hook failed', err);
1795
+ }
1796
+ }
1797
+
1798
+ /**
1799
+ * Show the blocked-play affordance over the element rect and arm its onActivate
1800
+ * to re-issue play() (user-gesture-backed, so autoplay policy permits it). On
1801
+ * a successful re-play the affordance hides. Never wedges the mirror.
1802
+ * @param {Element} el
1803
+ * @param {number|string} nid
1804
+ */
1805
+ function showBlockedPlayAffordance(el, nid) {
1806
+ overlays.show('media-blocked', {
1807
+ nid: nid,
1808
+ onActivate: function () {
1809
+ try {
1810
+ var p = el.play();
1811
+ if (p !== undefined && typeof p.then === 'function') {
1812
+ p.then(function () { overlays.show('media-blocked', null); })
1813
+ .catch(function () { /* still blocked: keep the affordance up */ });
1814
+ } else {
1815
+ overlays.show('media-blocked', null);
1816
+ }
1817
+ } catch (e) { /* contained: a re-play failure keeps the affordance */ }
1818
+ }
1819
+ }, { anchorRect: resolveNidRect(nid) });
1820
+ }
1821
+
1822
+ /**
1823
+ * Ensure the element is playing under autoplay policy. Sets muted=true before
1824
+ * the first programmatic play (muted autoplay is always allowed), then guards
1825
+ * play()'s return: jsdom (and very old browsers) return undefined, so the
1826
+ * `if (p !== undefined && typeof p.catch === 'function')` guard avoids a
1827
+ * TypeError; a NotAllowedError rejection shows the blocked-play affordance and
1828
+ * invokes onMediaBlocked(nid). Any other rejection falls through to the
1829
+ * Phase 12 load-error path (no affordance). (13-RESEARCH Example 4.)
1830
+ * @param {Element} el
1831
+ * @param {number|string} nid
1832
+ */
1833
+ function ensurePlaying(el, nid) {
1834
+ if (!el.paused) return;
1835
+ try { el.muted = true; } catch (e) { /* muted-autoplay default best-effort */ }
1836
+ var p;
1837
+ try {
1838
+ p = el.play();
1839
+ } catch (e) {
1840
+ return; // a synchronous play() throw is contained (never wedges)
1841
+ }
1842
+ if (p !== undefined && typeof p.catch === 'function') {
1843
+ p.catch(function (err) {
1844
+ if (err && err.name === 'NotAllowedError') {
1845
+ showBlockedPlayAffordance(el, nid);
1846
+ safeInvokeMediaHook(onMediaBlocked, nid);
1847
+ }
1848
+ // Any other rejection: defer to the Phase 12 load-error placeholder.
1849
+ });
1850
+ }
1851
+ }
1852
+
1853
+ /**
1854
+ * Apply one reconciler action to the in-iframe element from the parent realm.
1855
+ * Driver guards (13-RESEARCH Example 4 + Pitfalls 4/6): hold while
1856
+ * element.seeking; only seek when readyState >= HAVE_METADATA (1); rejoin-edge
1857
+ * reads seekable.end only when seekable.length > 0 (else holds). All element
1858
+ * mutations are try/caught so one failure never wedges the mirror.
1859
+ * @param {Element} el
1860
+ * @param {{action: string, toTime?: number, rate?: number, revertRate?: number}} action
1861
+ * @param {number|string} nid
1862
+ */
1863
+ function applyMediaAction(el, action, nid) {
1864
+ if (!action || typeof action.action !== 'string') return;
1865
+ // Pitfall 6 driver guard: never apply a new seek while a seek is in flight.
1866
+ if (el.seeking) {
1867
+ // Still allow pause to flow even mid-seek; a new seek is the only thing held.
1868
+ if (action.action === 'pause') { try { el.pause(); } catch (e) {} }
1869
+ return;
1870
+ }
1871
+ switch (action.action) {
1872
+ case 'pause':
1873
+ try { el.pause(); } catch (e) { /* contained */ }
1874
+ break;
1875
+ case 'seek':
1876
+ case 'rejoin-edge': {
1877
+ var target;
1878
+ if (action.action === 'rejoin-edge') {
1879
+ // Live rejoin: seekable.end only when the range is non-empty (Pitfall 4).
1880
+ target = (el.seekable && el.seekable.length > 0)
1881
+ ? el.seekable.end(el.seekable.length - 1)
1882
+ : null;
1883
+ } else {
1884
+ target = action.toTime;
1885
+ }
1886
+ if (target != null && el.readyState >= 1 /* HAVE_METADATA */) {
1887
+ try { el.currentTime = target; } catch (e) { /* contained */ }
1888
+ }
1889
+ ensurePlaying(el, nid);
1890
+ break;
1891
+ }
1892
+ case 'nudge':
1893
+ try { el.playbackRate = action.rate; } catch (e) { /* contained */ }
1894
+ ensurePlaying(el, nid);
1895
+ break;
1896
+ case 'hold':
1897
+ // Restore the true rate if a nudge was active and drifted the rate.
1898
+ if (action.revertRate != null && el.playbackRate !== action.revertRate) {
1899
+ try { el.playbackRate = action.revertRate; } catch (e) { /* contained */ }
1900
+ }
1901
+ ensurePlaying(el, nid);
1902
+ break;
1903
+ default:
1904
+ break;
1905
+ }
1906
+ }
1907
+
1908
+ /**
1909
+ * STREAM.MEDIA handler (MEDIA-01/05, MWIRE-01): the side-channel twin of
1910
+ * handleScroll/handleOverlay. Streaming + identity gate, then resolve the nid,
1911
+ * run the pure reconciler over the element's observed state, and drive the
1912
+ * in-iframe element cross-realm. After ensurePlaying, evaluate the unmute
1913
+ * trigger. In mediaMode 'poster'/'off' no source is bound and no driver runs
1914
+ * (the Task 1 string/fragment gate already neutralized the source) and no
1915
+ * affordance is surfaced. A viewer without this case (the dispatch default)
1916
+ * silently ignores the message (backward-compat).
1917
+ * @param {Object} payload
1918
+ */
1919
+ function handleMedia(payload) {
1920
+ if (viewerState !== 'streaming') return;
1921
+ if (!isCurrentStream(payload, active)) return;
1922
+ // poster/off: the source is neutralized at the gate; never drive playback or
1923
+ // surface a playback affordance (13-UI-SPEC State C: poster is a still frame).
1924
+ if (mediaMode !== 'reference') {
1925
+ // State C wire (13-UI-REVIEW Fix 1 -- the dead-code BLOCKER): in POSTER mode
1926
+ // a media element whose gated `poster` did NOT survive renders as an
1927
+ // unexplained blank, so drive the registered-but-never-shown media-poster
1928
+ // caption: show it IFF the element has no surviving poster, else hide it
1929
+ // (the poster image is the explanation). 'off' mode renders nothing.
1930
+ if (mediaMode === 'poster') {
1931
+ var posterNid = payload && payload.nid;
1932
+ var posterEl = resolveIndexedNode(posterNid);
1933
+ var hasPoster = !!(posterEl && posterEl.getAttribute && posterEl.getAttribute('poster'));
1934
+ if (posterEl && !hasPoster) {
1935
+ overlays.show('media-poster', { nid: posterNid }, { anchorRect: resolveNidRect(posterNid) });
1936
+ } else {
1937
+ overlays.show('media-poster', null);
1938
+ }
1939
+ }
1940
+ markLive('media');
1941
+ return;
1942
+ }
1943
+ var nid = payload && payload.nid;
1944
+ var el = resolveIndexedNode(nid);
1945
+ if (!el || typeof el.play !== 'function') return;
1946
+
1947
+ // Phase 14 (MADPT-02 page correlation): an MSE-opaque element (no resolvable
1948
+ // source) that starts is the consumer for the most-recent stored page hint.
1949
+ // Consume at most once per element per generation, then let the player +
1950
+ // reconciler own it (the source-less element otherwise plays nothing).
1951
+ maybeConsumePageHint(el, nid);
1952
+
1953
+ var localState = {
1954
+ currentTime: el.currentTime,
1955
+ paused: !!el.paused,
1956
+ playbackRate: el.playbackRate,
1957
+ seeking: !!el.seeking,
1958
+ readyState: el.readyState
1959
+ };
1960
+ var action = reconcileMediaDrift(localState, payload, Date.now(), mediaReconcileConfig);
1961
+ applyMediaAction(el, action, nid);
1962
+ evaluateUnmuteTrigger(el, payload, nid);
1963
+ markLive('media');
1964
+ }
1965
+
1966
+ /**
1967
+ * Is this media element MSE-opaque / source-less -- i.e. it resolves to no
1968
+ * playable source the viewer can reference (no `src` attribute survived the
1969
+ * gate, no current child <source src>, and an empty currentSrc)? Such an
1970
+ * element is the candidate consumer for a page-scope adaptive hint (an
1971
+ * adaptive manifest never appears as a plain element src). All reads are
1972
+ * guarded so a hostile/odd element never wedges the media path.
1973
+ * @param {Element} el
1974
+ * @returns {boolean}
1975
+ */
1976
+ function mediaElementHasNoSource(el) {
1977
+ try {
1978
+ if (el.getAttribute && el.getAttribute('src')) return false;
1979
+ if (el.currentSrc) return false;
1980
+ if (typeof el.querySelector === 'function') {
1981
+ var sourced = el.querySelector('source[src]');
1982
+ if (sourced) return false;
1983
+ }
1984
+ return true;
1985
+ } catch (e) {
1986
+ return false; // unknowable -> do not consume (conservative)
1987
+ }
1988
+ }
1989
+
1990
+ /**
1991
+ * Consume the most-recent stored page hint for an MSE-opaque element on play
1992
+ * (14-RESEARCH page-level correlation). Idempotent per nid per generation: an
1993
+ * element binds at most one page hint, and only when it is source-less. The
1994
+ * stored hint is removed once bound so a single page hint maps to a single
1995
+ * consumer. No-op when the element already has a source or no hint is pending.
1996
+ * @param {Element} el
1997
+ * @param {number|string} nid
1998
+ */
1999
+ function maybeConsumePageHint(el, nid) {
2000
+ if (pendingHints.size === 0) return;
2001
+ var key = String(nid);
2002
+ if (hintBoundNids.has(key)) return;
2003
+ if (!mediaElementHasNoSource(el)) return;
2004
+ // Most-recent-wins per kind: prefer 'hls' (the optional lazy path needs no
2005
+ // host player), else 'dash' (host playerFactory only). Either is correct;
2006
+ // pick the most-recently stored across kinds.
2007
+ var chosen = null;
2008
+ pendingHints.forEach(function (hint) {
2009
+ if (!chosen || hint.storedAt >= chosen.storedAt) chosen = hint;
2010
+ });
2011
+ if (!chosen) return;
2012
+ pendingHints.delete(chosen.kind);
2013
+ hintBoundNids.add(key);
2014
+ bindAdaptiveHint(el, key, chosen.manifestUrl, chosen.kind, chosen.contentType);
2015
+ }
2016
+
2017
+ /**
2018
+ * Bind an adaptive manifest to an in-iframe element through the parent-realm
2019
+ * player. The manifestUrl was already re-gated by handleMediaHint before it
2020
+ * reached pendingHints (page scope) or before an element-scope bind; the
2021
+ * player re-gates a third time internally (defense in depth). attach() is
2022
+ * fire-and-forget (the native/factory/dash branches are synchronous; the lazy-
2023
+ * hls branch returns a promise the player self-contains) and never throws.
2024
+ * @param {Element} el
2025
+ * @param {number|string} nid
2026
+ * @param {string} manifestUrl
2027
+ * @param {'hls'|'dash'} kind
2028
+ * @param {?string} contentType
2029
+ */
2030
+ function bindAdaptiveHint(el, nid, manifestUrl, kind, contentType) {
2031
+ try {
2032
+ mediaPlayer.attach(el, manifestUrl, { nid: String(nid), kind: kind, contentType: contentType });
2033
+ } catch (e) {
2034
+ // attach() is contained internally, but guard the call site too so a
2035
+ // correlation bug never wedges the media dispatch.
2036
+ logger.warn('[Renderer] adaptive hint bind failed', { nid: String(nid) });
2037
+ }
2038
+ }
2039
+
2040
+ /**
2041
+ * STREAM.MEDIA_HINT handler (MADPT-02 consumption): the adapter-originated
2042
+ * adaptive-manifest discovery op (a structural twin of STREAM.MEDIA; old
2043
+ * viewers ignore it via the dispatch default). Flow (14-RESEARCH hint-
2044
+ * consumption spec):
2045
+ * 1. streaming + identity gate (isCurrentStream) -- drop a stale/late hint
2046
+ * from a prior page so it can never bind the wrong media (T-14-11).
2047
+ * 2. poster/off mode binds no adaptive player at all (no player surface).
2048
+ * 3. RE-GATE manifestUrl through gateAsset(url,'media') BEFORE any use -- the
2049
+ * hint is attacker-influenced; a blocked origin degrades to poster and is
2050
+ * NEVER fetched (T-14-10 / V12 SSRF defense in depth).
2051
+ * 4. element scope (payload.nid set, element resolves & is MSE-opaque) ->
2052
+ * bind immediately via the player; page scope -> store most-recent-wins
2053
+ * per kind for an opaque element to consume on play.
2054
+ * @param {Object} payload MediaHintPayload
2055
+ */
2056
+ function handleMediaHint(payload) {
2057
+ if (viewerState !== 'streaming') return;
2058
+ if (!isCurrentStream(payload, active)) return;
2059
+ // WR-03: an empty-identity hint bypasses isCurrentStream (the backward-compat
2060
+ // clause accepts any message with no identity). Before the first identity-
2061
+ // bearing snapshot establishes a generation (active.streamSessionId === ''),
2062
+ // such a hint could out-race the snapshot that defines its generation and be
2063
+ // consumed by an element it was never meant for. Do NOT accept a hint until a
2064
+ // current stream identity exists: drop an empty-identity hint that arrives in
2065
+ // the pre-snapshot window. Once a generation exists, isCurrentStream governs.
2066
+ if ((!payload || !payload.streamSessionId) && !active.streamSessionId) return;
2067
+ // Poster/off mode: no adaptive player surface (the source is neutralized at
2068
+ // the gate and poster is a still frame -- 13-UI-SPEC State C). Drop hints.
2069
+ if (mediaMode !== 'reference') { markLive('media'); return; }
2070
+ var p = payload || {};
2071
+ var manifestUrl = p.manifestUrl;
2072
+ if (!manifestUrl || typeof manifestUrl !== 'string') { markLive('media'); return; }
2073
+ var nid = (p.nid != null) ? p.nid : null;
2074
+ // RE-GATE at the viewer (defense in depth): a blocked manifest origin must
2075
+ // never be fetched -> degrade to poster instead.
2076
+ if (!gateAsset(manifestUrl, 'media').allow) {
2077
+ mediaPlayer.degrade(nid != null ? String(nid) : null, 'no-manifest');
2078
+ markLive('media');
2079
+ return;
2080
+ }
2081
+ var kind = (p.kind === 'hls' || p.kind === 'dash') ? p.kind : null;
2082
+ var scope = (p.scope === 'element') ? 'element' : (p.scope === 'page' ? 'page' : (nid != null ? 'element' : 'page'));
2083
+ if (scope === 'element' && nid != null) {
2084
+ var el = resolveIndexedNode(nid);
2085
+ // Element-scope: bind immediately when the element resolves and is MSE-
2086
+ // opaque (no resolvable source). A correlated element that already has a
2087
+ // playable source is left to the Phase 13 progressive path.
2088
+ if (el && typeof el.play === 'function' && mediaElementHasNoSource(el)) {
2089
+ hintBoundNids.add(String(nid));
2090
+ bindAdaptiveHint(el, nid, manifestUrl, kind, p.contentType);
2091
+ } else {
2092
+ // WR-05: the named element cannot take the adaptive stream -- either the
2093
+ // nid does not resolve (stale / wrong generation) or it resolves but is
2094
+ // not MSE-opaque (a resolved-but-sourced element stays with the
2095
+ // progressive path). Surface ONE concise diagnostic so a dropped hint is
2096
+ // observable instead of indistinguishable from "successfully handled".
2097
+ // Never throws (logger is advisory); the never-break contract holds.
2098
+ logger.warn('[Renderer] element-scope media hint dropped (unresolved or non-opaque nid)', {
2099
+ nid: String(nid),
2100
+ reason: el ? 'not-opaque' : 'unresolved'
2101
+ });
2102
+ }
2103
+ markLive('media');
2104
+ return;
2105
+ }
2106
+ // Page scope (nid omitted): store most-recent-wins per kind; consumed when an
2107
+ // MSE-opaque element next plays (handleMedia -> maybeConsumePageHint).
2108
+ pendingHints.set(kind || 'hls', {
2109
+ manifestUrl: manifestUrl,
2110
+ kind: kind || 'hls',
2111
+ contentType: p.contentType,
2112
+ storedAt: Date.now()
2113
+ });
2114
+ markLive('media');
2115
+ }
2116
+
2117
+ /**
2118
+ * Unmute trigger (MEDIA-05, 13-UI-SPEC State B): after the muted-default play,
2119
+ * when the in-iframe element is muted but the source reports unmuted
2120
+ * (payload.muted === false) in mediaMode 'reference', SHOW the media-unmute
2121
+ * affordance; activating it sets muted=false + restores volume and hides the
2122
+ * affordance. When the source is still muted (or no muted field), hide/skip
2123
+ * the affordance (the null-payload contract).
2124
+ * @param {Element} el
2125
+ * @param {Object} payload
2126
+ * @param {number|string} nid
2127
+ */
2128
+ function evaluateUnmuteTrigger(el, payload, nid) {
2129
+ var sourceUnmuted = payload && payload.muted === false;
2130
+ if (el.muted === true && sourceUnmuted) {
2131
+ var vol = (payload && typeof payload.volume === 'number') ? payload.volume : null;
2132
+ overlays.show('media-unmute', {
2133
+ nid: nid,
2134
+ onActivate: function () {
2135
+ try { el.muted = false; } catch (e) { /* contained */ }
2136
+ if (vol != null) { try { el.volume = vol; } catch (e2) { /* contained */ } }
2137
+ overlays.show('media-unmute', null); // hide after activation
2138
+ }
2139
+ }, { anchorRect: resolveNidRect(nid) });
2140
+ } else {
2141
+ // Source muted / field absent / element already unmuted -> hide.
2142
+ overlays.show('media-unmute', null);
2143
+ }
2144
+ }
2145
+
2146
+ /**
2147
+ * Apply the snapshot media[] baseline (Plan 02) once per element, on first
2148
+ * bind only (Pitfall 7: the baseline is the INITIAL desired state; after this,
2149
+ * live STREAM.MEDIA hands control to the reconciler so a re-snapshot never
2150
+ * jumps playback back). Each entry is nid-addressed; the seek is readyState-
2151
+ * gated (>= HAVE_METADATA) and contained. No-op in poster/off mode (the source
2152
+ * is neutralized; nothing plays). All element mutations are best-effort.
2153
+ * @param {Array<Object>} baseline payload.media (absent on media-free pages)
2154
+ */
2155
+ function applyMediaBaseline(baseline) {
2156
+ if (mediaMode !== 'reference') return;
2157
+ if (!Array.isArray(baseline) || baseline.length === 0) return;
2158
+ for (var i = 0; i < baseline.length; i++) {
2159
+ var entry = baseline[i];
2160
+ if (!entry || entry.nid == null) continue;
2161
+ var key = String(entry.nid);
2162
+ if (mediaFirstBind.has(key)) continue; // already bound -> reconciler owns it
2163
+ var el = resolveIndexedNode(key);
2164
+ if (!el || typeof el.play !== 'function') continue;
2165
+ mediaFirstBind.add(key);
2166
+ try {
2167
+ // Initial currentTime only when ready (live entries carry no duration).
2168
+ if (typeof entry.currentTime === 'number' && el.readyState >= 1) {
2169
+ el.currentTime = entry.currentTime;
2170
+ }
2171
+ if (typeof entry.playbackRate === 'number') el.playbackRate = entry.playbackRate;
2172
+ if (entry.paused === false) {
2173
+ ensurePlaying(el, key);
2174
+ }
2175
+ } catch (e) {
2176
+ logger.warn('[Renderer] media baseline apply failed', { nid: key });
2177
+ }
2178
+ }
2179
+ }
2180
+
1236
2181
  /**
1237
2182
  * Transport message dispatch. The whole handler is containment-wrapped:
1238
2183
  * one malformed message routes to the logger and never kills the
@@ -1265,6 +2210,12 @@ export function createViewer(options) {
1265
2210
  case STREAM.DIALOG:
1266
2211
  handleDialog(payload);
1267
2212
  break;
2213
+ case STREAM.MEDIA:
2214
+ handleMedia(payload);
2215
+ break;
2216
+ case STREAM.MEDIA_HINT:
2217
+ handleMediaHint(payload);
2218
+ break;
1268
2219
  case STREAM.STATE:
1269
2220
  handleStreamState(payload);
1270
2221
  break;
@@ -1365,6 +2316,7 @@ export function createViewer(options) {
1365
2316
  lastTransportStatus = {};
1366
2317
  stateListeners.clear();
1367
2318
  healthListeners.clear();
2319
+ loadedListeners.clear();
1368
2320
  viewerState = 'waiting';
1369
2321
  }
1370
2322
 
@@ -1390,7 +2342,12 @@ export function createViewer(options) {
1390
2342
  on: on,
1391
2343
  registerOverlay: registerOverlay,
1392
2344
  requestSubtree: requestSubtree,
1393
- resolveNode: resolveNode
2345
+ resolveNode: resolveNode,
2346
+ // Host-driven snapshot entry point (Phase 12): viewers wired without a
2347
+ // wire transport (the asset-fetch-gate path) render a snapshot by calling
2348
+ // this directly. Identical to the dispatch() STREAM.SNAPSHOT target and
2349
+ // accepts either a bare payload or a { type, payload } envelope.
2350
+ handleSnapshot: handleSnapshot
1394
2351
  };
1395
2352
  }
1396
2353