@full-self-browsing/phantom-stream 0.1.0 → 0.2.1

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 (46) hide show
  1. package/dist/types/adapters/extension.d.ts.map +1 -1
  2. package/dist/types/adapters/playwright.d.ts.map +1 -1
  3. package/dist/types/capture/index.d.ts +112 -0
  4. package/dist/types/capture/index.d.ts.map +1 -1
  5. package/dist/types/protocol/constants.d.ts +22 -0
  6. package/dist/types/protocol/constants.d.ts.map +1 -1
  7. package/dist/types/protocol/index.d.ts +1 -0
  8. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  9. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  10. package/dist/types/protocol/messages.d.ts +266 -2
  11. package/dist/types/protocol/messages.d.ts.map +1 -1
  12. package/dist/types/renderer/asset-policy.d.ts +72 -0
  13. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  14. package/dist/types/renderer/diff.d.ts.map +1 -1
  15. package/dist/types/renderer/index.d.ts +13 -0
  16. package/dist/types/renderer/index.d.ts.map +1 -1
  17. package/dist/types/renderer/media-player.d.ts +114 -0
  18. package/dist/types/renderer/media-player.d.ts.map +1 -0
  19. package/dist/types/renderer/overlays.d.ts +12 -0
  20. package/dist/types/renderer/overlays.d.ts.map +1 -1
  21. package/dist/types/renderer/sanitize.d.ts +22 -0
  22. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  23. package/dist/types/renderer/snapshot.d.ts +38 -0
  24. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  25. package/dist/types/transport/websocket.d.ts.map +1 -1
  26. package/docs/ARCHITECTURE.md +13 -4
  27. package/docs/SECURITY.md +233 -2
  28. package/examples/bookmarklet-demo/viewer.html +12 -3
  29. package/examples/extension-mv3/viewer.html +10 -3
  30. package/package.json +9 -1
  31. package/src/adapters/extension.js +202 -7
  32. package/src/adapters/playwright-inject.js +50 -0
  33. package/src/adapters/playwright.js +159 -0
  34. package/src/capture/index.js +1071 -11
  35. package/src/protocol/constants.js +24 -0
  36. package/src/protocol/index.js +1 -0
  37. package/src/protocol/media-reconcile.js +188 -0
  38. package/src/protocol/messages.js +145 -2
  39. package/src/renderer/asset-policy.js +172 -0
  40. package/src/renderer/diff.js +106 -2
  41. package/src/renderer/index.js +849 -9
  42. package/src/renderer/media-player.js +367 -0
  43. package/src/renderer/overlays.js +324 -0
  44. package/src/renderer/sanitize.js +25 -3
  45. package/src/renderer/snapshot.js +534 -3
  46. package/src/transport/websocket.js +36 -0
@@ -3,7 +3,7 @@
3
3
  // This module is intentionally framework-free so it can run in a service
4
4
  // worker bundle or be unit-tested with a fake Chrome API.
5
5
 
6
- import { CONTROL, STREAM } from '../protocol/messages.js';
6
+ import { CONTROL, STREAM, classifyManifest } from '../protocol/messages.js';
7
7
 
8
8
  export const PHANTOMSTREAM_WATCHDOG_ALARM = 'phantomstream-watchdog';
9
9
  export const PHANTOMSTREAM_SESSION_KEY = 'phantomstream:mv3-session';
@@ -35,7 +35,15 @@ function hasRemoveListener(event) {
35
35
  return event && typeof event.removeListener === 'function';
36
36
  }
37
37
 
38
- function validateChrome(chrome) {
38
+ function hasWebRequestOnCompleted(chrome) {
39
+ return !!(chrome && chrome.webRequest && hasAddListener(chrome.webRequest.onCompleted));
40
+ }
41
+
42
+ // The core MV3 surface is always hard-required. The powerful chrome.webRequest
43
+ // permission is required ONLY when manifest discovery is opted in, and even then
44
+ // its absence DEGRADES GRACEFULLY (no throw, no listener, emit nothing) rather
45
+ // than failing the adapter — the discovery returns a capability flag instead.
46
+ function validateChrome(chrome, discoverManifests) {
39
47
  if (!chrome || Object(chrome) !== chrome) throw new Error('extension-chrome-required');
40
48
  if (!chrome.runtime || !hasAddListener(chrome.runtime.onMessage)) {
41
49
  throw new Error('extension-runtime-required');
@@ -49,6 +57,9 @@ function validateChrome(chrome) {
49
57
  || typeof chrome.alarms.create !== 'function') {
50
58
  throw new Error('extension-alarms-required');
51
59
  }
60
+ // When opted in, report whether the discovery permission is available; never
61
+ // throw on its absence (graceful degradation is the contract).
62
+ return { manifestDiscoveryAvailable: discoverManifests ? hasWebRequestOnCompleted(chrome) : false };
52
63
  }
53
64
 
54
65
  function cleanString(value) {
@@ -137,7 +148,18 @@ function invokeTransportSend(transport, type, payload) {
137
148
  export function createExtensionAdapter(options) {
138
149
  var opts = options || {};
139
150
  var chrome = opts.chrome;
140
- validateChrome(chrome);
151
+
152
+ // Opt-in, off-by-default adaptive-manifest discovery (MADPT-02). chrome.webRequest
153
+ // is required ONLY when opted in, and its absence degrades gracefully.
154
+ var discoverManifests = opts.discoverManifests === true;
155
+ var validation = validateChrome(chrome, discoverManifests);
156
+ var manifestDiscoveryAvailable = !!(validation && validation.manifestDiscoveryAvailable);
157
+ var resolveActiveMediaNid = typeof opts.resolveActiveMediaNid === 'function'
158
+ ? opts.resolveActiveMediaNid
159
+ : function () { return null; };
160
+ // The hint is stamped with the same stream identity the adapter already
161
+ // forwards on the STREAM frames it relays, snooped from those payloads.
162
+ var currentIdentity = { streamSessionId: '', snapshotId: 0 };
141
163
 
142
164
  var transport = opts.transport || null;
143
165
  var alarmName = typeof opts.alarmName === 'string' && opts.alarmName
@@ -175,6 +197,10 @@ export function createExtensionAdapter(options) {
175
197
  async function writeSessionState(next) {
176
198
  sessionState = cloneSessionState(next);
177
199
  await chrome.storage.session.set({ [storageKey]: sessionState });
200
+ // Narrow the manifest observer to the streamed tab once its id is known (or
201
+ // re-scope if it changed). No-op when discovery is off or the scope already
202
+ // matches; the in-handler tabId check covers the window before this fires.
203
+ rearmManifestObserverForTab();
178
204
  return sessionState;
179
205
  }
180
206
 
@@ -246,6 +272,7 @@ export function createExtensionAdapter(options) {
246
272
  var bridge = normalizeBridgeMessage(message);
247
273
  if (!bridge || typeof bridge.type !== 'string') return undefined;
248
274
  if (STREAM_TYPES[bridge.type]) {
275
+ observeStreamIdentity(bridge.payload);
249
276
  invokeTransportSend(transport, bridge.type, bridge.payload || {});
250
277
  return { ok: true };
251
278
  }
@@ -256,14 +283,177 @@ export function createExtensionAdapter(options) {
256
283
  return undefined;
257
284
  }
258
285
 
259
- function handleTransportMessage(message) {
260
- var bridge = normalizeBridgeMessage(message);
261
- if (!bridge || !CONTROL_TYPES[bridge.type]) return;
262
- handleControl(bridge.type, bridge.payload || {}, null).catch(function handleControlFailure(error) {
286
+ function dispatchTransportControl(type, payload) {
287
+ if (typeof type !== 'string' || !CONTROL_TYPES[type]) return null;
288
+ return handleControl(type, payload || {}, null).catch(function handleControlFailure(error) {
263
289
  logWarn('transport-control-failed', error);
264
290
  });
265
291
  }
266
292
 
293
+ // The transport may dispatch as (type, payload) — the createWebSocketTransport
294
+ // onMessage contract — or hand us a single { type, payload } message object.
295
+ // Support both. Returns the in-flight control promise so callers can await the
296
+ // persist + forward; the transport itself discards the return value.
297
+ function handleTransportMessage(messageOrType, maybePayload) {
298
+ if (typeof messageOrType === 'string') {
299
+ return dispatchTransportControl(messageOrType, maybePayload);
300
+ }
301
+ var bridge = normalizeBridgeMessage(messageOrType);
302
+ if (!bridge) return null;
303
+ return dispatchTransportControl(bridge.type, bridge.payload || {});
304
+ }
305
+
306
+ // Snoop the stream identity off the side-channel STREAM payloads the adapter
307
+ // relays so an emitted hint carries the same identity. Missing fields are
308
+ // ignored (the viewer's isCurrentStream accepts an empty-identity hint until a
309
+ // real identity has been observed).
310
+ function observeStreamIdentity(payload) {
311
+ if (!payload || Object(payload) !== payload) return;
312
+ if (typeof payload.streamSessionId === 'string' && payload.streamSessionId) {
313
+ currentIdentity.streamSessionId = payload.streamSessionId;
314
+ }
315
+ if (typeof payload.snapshotId === 'number' && Number.isFinite(payload.snapshotId)) {
316
+ currentIdentity.snapshotId = payload.snapshotId;
317
+ }
318
+ }
319
+
320
+ // Read the content-type from the Chromium responseHeaders array (an array of
321
+ // { name, value }; the header name may be any casing).
322
+ function contentTypeOf(responseHeaders) {
323
+ if (!Array.isArray(responseHeaders)) return '';
324
+ for (var i = 0; i < responseHeaders.length; i += 1) {
325
+ var header = responseHeaders[i];
326
+ if (header && typeof header.name === 'string'
327
+ && header.name.toLowerCase() === 'content-type') {
328
+ return typeof header.value === 'string' ? header.value : '';
329
+ }
330
+ }
331
+ return '';
332
+ }
333
+
334
+ // Best-effort manifest observation. Classifies a completed response via the
335
+ // pure classifyManifest filter and, on a non-null kind, emits STREAM.MEDIA_HINT
336
+ // through the same transport.send path. Fully contained so a hostile details
337
+ // object can never wedge the observer.
338
+ function handleManifestCompleted(details) {
339
+ if (disposed || !discoverManifests) return;
340
+ try {
341
+ if (!details || typeof details.url !== 'string') return;
342
+ // Streamed-tab scope: drop a response from an UNRELATED tab so a manifest
343
+ // fetched elsewhere can never bind the streamed page's media element. The
344
+ // filter below also narrows at the API level once the tab id is known;
345
+ // this in-handler check is the robust guarantee (works even if the filter
346
+ // could not be scoped at arm time, or the browser ignored it). When the
347
+ // streamed tab id is unknown, or the details carry no tabId, accept
348
+ // (graceful: the prior <all_urls> behavior).
349
+ if (sessionState && sessionState.tabId != null
350
+ && typeof details.tabId === 'number'
351
+ && details.tabId !== sessionState.tabId) {
352
+ return;
353
+ }
354
+ var contentType = contentTypeOf(details.responseHeaders);
355
+ var kind = classifyManifest({ url: details.url, contentType: contentType });
356
+ if (!kind) return;
357
+ emitMediaHint(details.url, kind, contentType);
358
+ } catch (error) {
359
+ logWarn('manifest-observe-failed', error);
360
+ }
361
+ }
362
+
363
+ function emitMediaHint(manifestUrl, kind, contentType) {
364
+ if (!transport || typeof transport.send !== 'function') return;
365
+ var payload = {
366
+ scope: 'page',
367
+ manifestUrl: manifestUrl,
368
+ kind: kind,
369
+ streamSessionId: currentIdentity.streamSessionId,
370
+ snapshotId: currentIdentity.snapshotId
371
+ };
372
+ if (contentType) payload.contentType = contentType;
373
+ var nid = null;
374
+ try {
375
+ nid = resolveActiveMediaNid();
376
+ } catch (error) {
377
+ nid = null; // correlation is best-effort; failure -> page scope
378
+ }
379
+ if (typeof nid === 'string' && nid) {
380
+ payload.scope = 'element';
381
+ payload.nid = nid;
382
+ }
383
+ try {
384
+ transport.send(STREAM.MEDIA_HINT, payload);
385
+ } catch (error) {
386
+ logWarn('media-hint-send-failed', error);
387
+ }
388
+ }
389
+
390
+ var manifestListener = function manifestListener(details) {
391
+ return handleManifestCompleted(details);
392
+ };
393
+
394
+ // Whether the manifest listener is currently registered, and the tab id its
395
+ // filter was scoped to (null = the broad <all_urls> filter). Tracked so the
396
+ // observer can re-register a narrower per-tab filter once the streamed tab id
397
+ // becomes known (it is absent at install time -- armManifestObserver runs
398
+ // before readSessionState rehydrates sessionState).
399
+ var manifestObserverArmed = false;
400
+ var manifestObserverTabId = null;
401
+
402
+ function manifestFilter() {
403
+ var tabId = (sessionState && sessionState.tabId != null) ? sessionState.tabId : null;
404
+ // Restrict to the streamed tab at the API level when known; the in-handler
405
+ // check is the belt-and-suspenders guarantee regardless. Omit tabId (broad
406
+ // filter) until the streamed tab id is observed.
407
+ return tabId != null
408
+ ? { urls: ['<all_urls>'], tabId: tabId }
409
+ : { urls: ['<all_urls>'] };
410
+ }
411
+
412
+ function armManifestObserver() {
413
+ if (!discoverManifests) return;
414
+ if (!manifestDiscoveryAvailable) {
415
+ // Opted in but the permission/API is absent: graceful no-op (no listener,
416
+ // no hint, no throw). The progressive path is unaffected.
417
+ logWarn('manifest-discovery-unavailable');
418
+ return;
419
+ }
420
+ if (manifestObserverArmed) return;
421
+ try {
422
+ chrome.webRequest.onCompleted.addListener(
423
+ manifestListener,
424
+ manifestFilter(),
425
+ ['responseHeaders']
426
+ );
427
+ manifestObserverArmed = true;
428
+ manifestObserverTabId = (sessionState && sessionState.tabId != null) ? sessionState.tabId : null;
429
+ } catch (error) {
430
+ logWarn('manifest-observer-arm-failed', error);
431
+ }
432
+ }
433
+
434
+ // Re-register the observer with a tab-scoped filter when the streamed tab id
435
+ // first becomes known (or changes). A no-op when discovery is off/unavailable,
436
+ // when no listener is armed, or when the scope is already correct.
437
+ function rearmManifestObserverForTab() {
438
+ if (!discoverManifests || !manifestDiscoveryAvailable) return;
439
+ if (!manifestObserverArmed) return;
440
+ var tabId = (sessionState && sessionState.tabId != null) ? sessionState.tabId : null;
441
+ if (tabId === manifestObserverTabId) return;
442
+ disarmManifestObserver();
443
+ armManifestObserver();
444
+ }
445
+
446
+ function disarmManifestObserver() {
447
+ if (!manifestDiscoveryAvailable) return;
448
+ try {
449
+ if (chrome.webRequest && hasRemoveListener(chrome.webRequest.onCompleted)) {
450
+ chrome.webRequest.onCompleted.removeListener(manifestListener);
451
+ }
452
+ } catch (error) { /* best-effort cleanup */ }
453
+ manifestObserverArmed = false;
454
+ manifestObserverTabId = null;
455
+ }
456
+
267
457
  var runtimeListener = function runtimeListener(message, sender) {
268
458
  return handleRuntimeMessage(message, sender);
269
459
  };
@@ -278,10 +468,14 @@ export function createExtensionAdapter(options) {
278
468
  installed = true;
279
469
  chrome.runtime.onMessage.addListener(runtimeListener);
280
470
  chrome.alarms.onAlarm.addListener(alarmListener);
471
+ armManifestObserver();
281
472
  if (transport && typeof transport.onMessage === 'function') {
282
473
  unsubscribeTransport = transport.onMessage(handleTransportMessage);
283
474
  }
284
475
  var restored = await readSessionState();
476
+ // armManifestObserver ran before sessionState was rehydrated; if the
477
+ // restored session names the streamed tab, re-scope the filter to it now.
478
+ rearmManifestObserverForTab();
285
479
  if (restored && restored.streamingActive) armWatchdog();
286
480
  return handle;
287
481
  },
@@ -293,6 +487,7 @@ export function createExtensionAdapter(options) {
293
487
  if (hasRemoveListener(chrome.alarms.onAlarm)) {
294
488
  chrome.alarms.onAlarm.removeListener(alarmListener);
295
489
  }
490
+ disarmManifestObserver();
296
491
  if (typeof unsubscribeTransport === 'function') {
297
492
  unsubscribeTransport();
298
493
  }
@@ -1723,6 +1723,36 @@ function createCapture(config) {
1723
1723
  return values;
1724
1724
  }
1725
1725
 
1726
+ // Positional identity for the selected options; mirrors src/capture/index.js
1727
+ // so masked option-value collisions stay unambiguous on the renderer.
1728
+ function selectedOptionIndexes(select) {
1729
+ var indexes = [];
1730
+ var options = select && select.options ? select.options : [];
1731
+ for (var i = 0; i < options.length; i++) {
1732
+ if (options[i].selected) indexes.push(i);
1733
+ }
1734
+ return indexes;
1735
+ }
1736
+
1737
+ // Positional selectedIndexes only line up with the mirror when EVERY option
1738
+ // survives the wire. If skipElement/blockSelector drops an <option> (or an
1739
+ // <optgroup>), the mirror's options list is shorter, so live-collection
1740
+ // indexes would address the wrong option. Detect that and fall back to value
1741
+ // matching instead.
1742
+ function selectHasFilteredOptions(select) {
1743
+ var nodes = select && select.querySelectorAll
1744
+ ? select.querySelectorAll('option, optgroup')
1745
+ : [];
1746
+ for (var i = 0; i < nodes.length; i++) {
1747
+ if (skipElementWithAncestors(nodes[i])
1748
+ || blockedWithAncestors(nodes[i])
1749
+ || wireDroppedWithAncestors(nodes[i])) {
1750
+ return true;
1751
+ }
1752
+ }
1753
+ return false;
1754
+ }
1755
+
1726
1756
  function sanitizeInputValue(value, owner) {
1727
1757
  return sanitizeForWire('input', {
1728
1758
  value: value == null ? '' : String(value),
@@ -1759,6 +1789,12 @@ function createCapture(config) {
1759
1789
  for (var s = 0; s < selected.length; s++) {
1760
1790
  diff.selectedValues.push(sanitizeInputValue(selected[s], control));
1761
1791
  }
1792
+ // Authoritative selection identity (renderer prefers this over the
1793
+ // maskable selectedValues), omitted when an option is filtered from the
1794
+ // wire so live indexes cannot mis-address the shorter mirror options.
1795
+ if (!selectHasFilteredOptions(control)) {
1796
+ diff.selectedIndexes = selectedOptionIndexes(control);
1797
+ }
1762
1798
  return diff;
1763
1799
  }
1764
1800
 
@@ -2521,6 +2557,13 @@ function createCapture(config) {
2521
2557
  bodyAttrs: Object.assign({}, payload && payload.bodyAttrs ? payload.bodyAttrs : {})
2522
2558
  });
2523
2559
 
2560
+ // CSSOM mode carries full stylesheet text in styleSources; copy the array
2561
+ // so the budget passes below can prune it without mutating the caller's
2562
+ // sources. Only present in cssom mode -- computed mode omits the field.
2563
+ if (Array.isArray(next.styleSources)) {
2564
+ next.styleSources = next.styleSources.slice();
2565
+ }
2566
+
2524
2567
  while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
2525
2568
  next.inlineStyles.pop();
2526
2569
  markSnapshotPayloadTruncated(next);
@@ -2529,6 +2572,12 @@ function createCapture(config) {
2529
2572
  next.stylesheets.pop();
2530
2573
  markSnapshotPayloadTruncated(next);
2531
2574
  }
2575
+ // A single large CSSOM source can dominate the payload; shed sources before
2576
+ // dropping DOM structure so an oversized stylesheet cannot blow the cap.
2577
+ while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Array.isArray(next.styleSources) && next.styleSources.length) {
2578
+ next.styleSources.pop();
2579
+ markSnapshotPayloadTruncated(next);
2580
+ }
2532
2581
 
2533
2582
  if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
2534
2583
  next.htmlStyle = '';
@@ -2577,6 +2626,7 @@ function createCapture(config) {
2577
2626
  next.frames = [];
2578
2627
  next.inlineStyles = [];
2579
2628
  next.stylesheets = [];
2629
+ if (Array.isArray(next.styleSources)) next.styleSources = [];
2580
2630
  next.htmlAttrs = {};
2581
2631
  next.bodyAttrs = {};
2582
2632
  next.htmlStyle = '';
@@ -13,6 +13,7 @@ import {
13
13
  REMOTE_CONTROL,
14
14
  REMOTE_CONTROL_STATE,
15
15
  STREAM,
16
+ classifyManifest,
16
17
  createRemoteControlStateEvent,
17
18
  isRemoteControlType,
18
19
  validateRemoteControlMessage,
@@ -87,6 +88,19 @@ export function createPlaywrightAdapter(options) {
87
88
  error: function () {}
88
89
  };
89
90
 
91
+ // Opt-in, off-by-default adaptive-manifest discovery (MADPT-02). When false/
92
+ // absent: register NO response listener and emit NO hints (graceful absence —
93
+ // the progressive path is untouched). The correlation hook is best-effort: it
94
+ // returns the nid of a single active opaque media element, or null/undefined
95
+ // for the always-safe page-scope default.
96
+ var discoverManifests = cfg.discoverManifests === true;
97
+ var resolveActiveMediaNid = typeof cfg.resolveActiveMediaNid === 'function'
98
+ ? cfg.resolveActiveMediaNid
99
+ : function () { return null; };
100
+ // The hint is stamped with the same stream identity the adapter already
101
+ // forwards on STREAM messages, snooped from the bridge payloads it relays.
102
+ var currentIdentity = { streamSessionId: '', snapshotId: 0 };
103
+
90
104
  var installed = false;
91
105
  var disposed = false;
92
106
  var cdpSession = cfg.cdpSession || null;
@@ -198,6 +212,7 @@ export function createPlaywrightAdapter(options) {
198
212
  return { ok: false, error: 'bridge-type-invalid' };
199
213
  }
200
214
  try {
215
+ observeStreamIdentity(msg.payload);
201
216
  transport.send(msg.type, msg.payload || {});
202
217
  emit('bridge', { type: msg.type });
203
218
  return { ok: true };
@@ -207,6 +222,138 @@ export function createPlaywrightAdapter(options) {
207
222
  }
208
223
  }
209
224
 
225
+ // Snoop the stream identity off the side-channel payloads the adapter relays,
226
+ // so an emitted media hint carries the same identity as the messages around
227
+ // it. Missing fields are ignored (the viewer's isCurrentStream accepts a hint
228
+ // with empty identity until a real stream identity has been observed).
229
+ function observeStreamIdentity(payload) {
230
+ if (!payload || Object(payload) !== payload) return;
231
+ if (typeof payload.streamSessionId === 'string' && payload.streamSessionId) {
232
+ currentIdentity.streamSessionId = payload.streamSessionId;
233
+ }
234
+ if (typeof payload.snapshotId === 'number' && Number.isFinite(payload.snapshotId)) {
235
+ currentIdentity.snapshotId = payload.snapshotId;
236
+ }
237
+ }
238
+
239
+ // Resolve the initiating frame of a Playwright Response, tolerant of API
240
+ // shape. Modern Playwright exposes response.frame() directly; older builds
241
+ // and the minimal test mock expose it via response.request().frame(). Returns
242
+ // null when no frame info is available so the caller degrades to "accept"
243
+ // (parity with isMainFrame(null) === true).
244
+ function responseFrame(response) {
245
+ try {
246
+ if (response && typeof response.frame === 'function') {
247
+ return response.frame() || null;
248
+ }
249
+ } catch (e) { /* fall through to the request() path */ }
250
+ try {
251
+ if (response && typeof response.request === 'function') {
252
+ var req = response.request();
253
+ if (req && typeof req.frame === 'function') return req.frame() || null;
254
+ }
255
+ } catch (e) { /* frame info unavailable */ }
256
+ return null;
257
+ }
258
+
259
+ // Best-effort manifest observation. Reads the response url + content-type,
260
+ // classifies via the pure classifyManifest filter, and on a non-null kind
261
+ // emits STREAM.MEDIA_HINT through the same transport.send path the bridge
262
+ // uses. Fully contained: a hostile/odd response can never wedge the observer.
263
+ function handleManifestResponse(response) {
264
+ if (disposed || !discoverManifests) return;
265
+ try {
266
+ if (!response || typeof response.url !== 'function') return;
267
+ // Main-frame-only, parity with bindingCallback's isMainFrame check: a
268
+ // cross-origin sub-frame must not steer the top page's player. When frame
269
+ // info is unavailable, isMainFrame(null) === true (degrade to accept).
270
+ var frame = responseFrame(response);
271
+ if (frame && !isMainFrame(frame)) return;
272
+ var url = response.url();
273
+ var contentType = '';
274
+ if (typeof response.headers === 'function') {
275
+ var headers = response.headers() || {};
276
+ // Playwright lowercases header names; be tolerant of either casing.
277
+ contentType = headers['content-type'] || headers['Content-Type'] || '';
278
+ }
279
+ var kind = classifyManifest({ url: url, contentType: contentType });
280
+ if (!kind) return;
281
+ emitMediaHint(url, kind, contentType);
282
+ } catch (err) {
283
+ safeLog('warn', '[PlaywrightAdapter] manifest observe failed', { reason: 'manifest-observe-failed' });
284
+ }
285
+ }
286
+
287
+ // The main frame's CDP frameId, learned opportunistically from
288
+ // Page.frameNavigated (the top-level frame has no parentId). Until known, the
289
+ // CDP manifest path degrades to "accept" (parity with the Playwright path when
290
+ // frame info is unavailable). Once known, a responseReceived carrying a
291
+ // different frameId is a sub-frame fetch and is ignored.
292
+ var mainCdpFrameId = null;
293
+
294
+ function observeCDPFrameNavigated(event) {
295
+ try {
296
+ var frame = event && event.frame;
297
+ if (!frame || typeof frame.id !== 'string') return;
298
+ // The top-level frame is the one without a parentId.
299
+ if (!frame.parentId) mainCdpFrameId = frame.id;
300
+ } catch (e) { /* contained -- frame tracking is best-effort */ }
301
+ }
302
+
303
+ // CDP Network.responseReceived secondary path: { frameId, response: { url,
304
+ // headers, mimeType, frameId? } }. Same opt-in, same classifier, same
305
+ // emission as the page hook, with the analogous main-frame scope: drop a
306
+ // response whose CDP frameId is a known non-main frame.
307
+ function handleCDPResponseReceived(event) {
308
+ if (disposed || !discoverManifests) return;
309
+ try {
310
+ var resp = event && event.response;
311
+ if (!resp || typeof resp.url !== 'string') return;
312
+ // Main-frame-only when both ids are known. The frameId rides the event
313
+ // (and sometimes the response); accept when either is unknown.
314
+ if (mainCdpFrameId) {
315
+ var frameId = (event && typeof event.frameId === 'string') ? event.frameId
316
+ : (typeof resp.frameId === 'string' ? resp.frameId : null);
317
+ if (frameId && frameId !== mainCdpFrameId) return;
318
+ }
319
+ var headers = resp.headers || {};
320
+ var contentType = headers['content-type'] || headers['Content-Type']
321
+ || (typeof resp.mimeType === 'string' ? resp.mimeType : '');
322
+ var kind = classifyManifest({ url: resp.url, contentType: contentType });
323
+ if (!kind) return;
324
+ emitMediaHint(resp.url, kind, contentType);
325
+ } catch (err) {
326
+ safeLog('warn', '[PlaywrightAdapter] cdp manifest observe failed', { reason: 'manifest-observe-failed' });
327
+ }
328
+ }
329
+
330
+ function emitMediaHint(manifestUrl, kind, contentType) {
331
+ var payload = {
332
+ scope: 'page',
333
+ manifestUrl: manifestUrl,
334
+ kind: kind,
335
+ streamSessionId: currentIdentity.streamSessionId,
336
+ snapshotId: currentIdentity.snapshotId
337
+ };
338
+ if (contentType) payload.contentType = contentType;
339
+ var nid = null;
340
+ try {
341
+ nid = resolveActiveMediaNid();
342
+ } catch (err) {
343
+ nid = null; // correlation is best-effort; failure -> page scope
344
+ }
345
+ if (typeof nid === 'string' && nid) {
346
+ payload.scope = 'element';
347
+ payload.nid = nid;
348
+ }
349
+ try {
350
+ transport.send(STREAM.MEDIA_HINT, payload);
351
+ emit('mediahint', { kind: kind, scope: payload.scope });
352
+ } catch (err) {
353
+ safeLog('error', '[PlaywrightAdapter] media hint send failed', { reason: 'media-hint-send-failed' });
354
+ }
355
+ }
356
+
210
357
  async function ensureCDPSession() {
211
358
  if (cdpSession) return cdpSession;
212
359
  if (typeof cfg.cdpSessionFactory !== 'function') return null;
@@ -305,6 +452,18 @@ export function createPlaywrightAdapter(options) {
305
452
  addPageListener('domcontentloaded', function () { handleNavigation(null); });
306
453
  addPageListener('load', function () { handleNavigation(null); });
307
454
 
455
+ // Opt-in manifest observation: only when discovery is enabled do we attach
456
+ // the 'response' listener (off by default -> no listener, graceful absence).
457
+ if (discoverManifests) {
458
+ addPageListener('response', handleManifestResponse);
459
+ if (session && typeof session.on === 'function') {
460
+ // CDP secondary path (same opt-in, same filter + emission). Track the
461
+ // main frame's CDP id so the response path can scope to it.
462
+ session.on('Page.frameNavigated', observeCDPFrameNavigated);
463
+ session.on('Network.responseReceived', handleCDPResponseReceived);
464
+ }
465
+ }
466
+
308
467
  if (transport && typeof transport.onMessage === 'function') {
309
468
  unsubscribeTransport = transport.onMessage(function (type, payload) {
310
469
  if (type === CONTROL.START) {