@browserbox/hyper-frame 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,7 @@
31
31
  * | `media-permissions` | no | `"default"` | Set to `"none"` to deny embedded mic/camera/display-capture use |
32
32
  * | `session-unload-warning` | no | `"default"` | Set to `"none"` to suppress BrowserBox's own "leave remote browser?" beforeunload warning |
33
33
  * | `beforeunload-behavior` | no | `"default"` | Set to `"leave"` to auto-depart or `"remain"` to auto-remain when a remote page triggers a beforeunload dialog |
34
+ * | `first-load-cleanse` | no | — | If present, automatically close all tabs on the first load of a session. If a URL is provided as the value, that URL is opened after cleansing. |
34
35
  *
35
36
  * ## Events * | Event | Detail | Description |
36
37
  * |-------|--------|-------------|
@@ -352,13 +353,24 @@ function createTabsNamespace(instance) {
352
353
  const url = typeof input.url === 'string' ? input.url : '';
353
354
  const shouldActivate = input.active !== false;
354
355
  const previousActiveTab = shouldActivate ? null : await instance._getActiveTabInfo();
355
- const beforeCount = await instance.callApi('getTabCount');
356
+ const before = new Set((await this.list()).map(tab => tab.id));
356
357
  await instance.callApi('createTab', url);
357
- await instance.callApi('waitForTabCount', beforeCount + 1, {
358
- timeoutMs: instance.requestTimeoutMs,
359
- });
360
- const tabs = await this.list();
361
- const createdTab = tabs[tabs.length - 1] || null;
358
+ // The created tab is the one whose id was not there before. Waiting for an exact
359
+ // tab count ran into the request timeout whenever another tab opened or closed
360
+ // in the meantime (two overlapping create calls were enough).
361
+ const deadline = Date.now() + instance.requestTimeoutMs;
362
+ let createdTab = null;
363
+ while (createdTab === null) {
364
+ const added = (await this.list()).filter(tab => !before.has(tab.id));
365
+ createdTab = added[added.length - 1] || null;
366
+ if (createdTab !== null) break;
367
+ if (Date.now() >= deadline) {
368
+ throw createBrowserBoxError(
369
+ `tabs.create: no new tab appeared within ${instance.requestTimeoutMs}ms of createTab.`,
370
+ { retriable: true });
371
+ }
372
+ await new Promise(resolve => setTimeout(resolve, 150));
373
+ }
362
374
  if (!shouldActivate && previousActiveTab?.id) {
363
375
  await instance.callApi('switchToTabById', previousActiveTab.id);
364
376
  }
@@ -584,9 +596,11 @@ function createSessionFacade(instance) {
584
596
 
585
597
  Object.defineProperties(session, {
586
598
  id: readOnlyProperty(() => instance.routingMid || null),
587
- usable: readOnlyProperty(() => instance._usable),
588
- transport: readOnlyProperty(() => instance._transportMode),
589
- ready: readOnlyProperty(() => instance._isReady),
599
+ state: readOnlyProperty(() => (instance._ready ? 'ready' : (instance._final ? 'failed' : 'connecting'))),
600
+ reason: readOnlyProperty(() => (instance._ready ? 'api-ready' : instance._notReadyReason())),
601
+ usable: readOnlyProperty(() => instance._ready),
602
+ transport: readOnlyProperty(() => 'modern'),
603
+ ready: readOnlyProperty(() => instance._ready),
590
604
  tabs: readOnlyProperty(() => instance.tabs),
591
605
  page: readOnlyProperty(() => instance.page),
592
606
  capture: readOnlyProperty(() => instance.capture),
@@ -712,6 +726,7 @@ const METHOD_CAPABILITY_MAP = {
712
726
  uiVisible: ['page.read'],
713
727
  allowUserToggleUI: ['page.read'],
714
728
  getTransportDiagnostics: ['events.read'],
729
+ getSessionDiagnostics: ['events.read'],
715
730
  getCurrentModal: ['modals.read'],
716
731
  respondToModal: ['modals.respond'],
717
732
  dismissModal: ['modals.respond'],
@@ -740,7 +755,7 @@ const EVENT_ALIAS_MAP = {
740
755
  'modal-closed': ['modal.closed'],
741
756
  };
742
757
 
743
- function debugBrowserBoxWebview(...args) {
758
+ function debugHyperFrame(...args) {
744
759
  if (globalThis.BROWSERBOX_WEBVIEW_DEBUG === true) {
745
760
  console.log(...args);
746
761
  }
@@ -1044,6 +1059,7 @@ class HyperFrame extends HTMLElement {
1044
1059
  'media-permissions',
1045
1060
  'session-unload-warning',
1046
1061
  'beforeunload-behavior',
1062
+ 'first-load-cleanse',
1047
1063
  ];
1048
1064
  }
1049
1065
 
@@ -1185,11 +1201,13 @@ class HyperFrame extends HTMLElement {
1185
1201
  this._requestSeq = 0;
1186
1202
  this._pending = new Map();
1187
1203
  this._apiMethods = [];
1188
- this._isReady = false;
1189
- this._usable = false;
1190
- this._readyPromise = Promise.resolve(true);
1204
+ this._attached = false;
1205
+ this._stopReason = '';
1206
+ this._viewerWord = 'none';
1207
+ this._viewerReason = '';
1208
+ this._wasReady = false;
1209
+ this._readyWaiters = new Set();
1191
1210
  this._initPingTimer = null;
1192
- this._transportMode = 'unknown';
1193
1211
  this._legacyTabsCache = [];
1194
1212
 
1195
1213
  // Iframe connection retry state
@@ -1197,7 +1215,6 @@ class HyperFrame extends HTMLElement {
1197
1215
  this._iframeRetryMax = 5;
1198
1216
  this._iframeRetryPingThreshold = 30; // pings (1s each) before retry — covers ~90s cold starts
1199
1217
  this._initPingCount = 0;
1200
- this._reconnectStopped = false;
1201
1218
  this._silentRecoveryUsed = false;
1202
1219
  this._silentRecoveryParam = 'bbx_embed_retry';
1203
1220
 
@@ -1245,7 +1262,6 @@ class HyperFrame extends HTMLElement {
1245
1262
  this._boundVisibilityChange = () => this._handleResumeTrigger('document-visibility');
1246
1263
  this._boundPageShow = () => this._handleResumeTrigger('page-show');
1247
1264
  this._boundWindowFocus = () => this._handleResumeTrigger('window-focus');
1248
- this._resetReadyPromise();
1249
1265
  this.tabs = createTabsNamespace(this);
1250
1266
  this.page = createPageNamespace(this);
1251
1267
  this.capture = createCaptureNamespace(this);
@@ -1255,6 +1271,9 @@ class HyperFrame extends HTMLElement {
1255
1271
  }
1256
1272
 
1257
1273
  connectedCallback() {
1274
+ this._attached = true;
1275
+ this._viewerWord = 'none';
1276
+ this._viewerReason = '';
1258
1277
  window.addEventListener('message', this._boundMessage);
1259
1278
  window.addEventListener('resize', this._boundResize);
1260
1279
  window.addEventListener('pageshow', this._boundPageShow);
@@ -1267,6 +1286,7 @@ class HyperFrame extends HTMLElement {
1267
1286
  }
1268
1287
  this._startVisibilityPolling();
1269
1288
  this.updateIframe();
1289
+ this._sync();
1270
1290
  }
1271
1291
 
1272
1292
  disconnectedCallback() {
@@ -1292,14 +1312,10 @@ class HyperFrame extends HTMLElement {
1292
1312
  this._deferredVisibilityRecheckTimer = null;
1293
1313
  }
1294
1314
  this._stopVisibilityPolling();
1295
- this._stopInitPing();
1296
- this._stopMidSync();
1297
- this._rejectPending(createBrowserBoxError('hyper-frame disconnected.', {
1298
- code: ERROR_CODES.TRANSPORT,
1299
- retriable: true,
1300
- status: 503,
1301
- }));
1302
- this._setUsable(false, 'disconnected');
1315
+ this._attached = false;
1316
+ this._viewerWord = 'none';
1317
+ this._viewerReason = '';
1318
+ this._sync();
1303
1319
  this._emitBrowserBoxEvent('disconnected', {});
1304
1320
  }
1305
1321
 
@@ -1308,22 +1324,16 @@ class HyperFrame extends HTMLElement {
1308
1324
  return;
1309
1325
  }
1310
1326
  if (name === 'login-link') {
1311
- this._isReady = false;
1312
1327
  this._apiMethods = [];
1313
- this._transportMode = 'unknown';
1314
1328
  this._legacyTabsCache = [];
1315
1329
  this._iframeRetryCount = 0;
1316
1330
  this._initPingCount = 0;
1317
- this._reconnectStopped = false;
1318
1331
  this._silentRecoveryUsed = false;
1319
1332
  this._lastSuccessfulBootstrapAt = 0;
1320
- this._resetReadyPromise();
1321
- this._invalidateFrameBootstrap('login-link-changed');
1322
- this._rejectPending(createBrowserBoxError('hyper-frame source changed.', {
1323
- code: ERROR_CODES.TRANSPORT,
1324
- retriable: true,
1325
- status: 503,
1326
- }));
1333
+ this._stopReason = '';
1334
+ this._viewerWord = 'none';
1335
+ this._viewerReason = '';
1336
+ this._sync();
1327
1337
  this._emitBrowserBoxEvent('disconnected', {
1328
1338
  reason: 'login-link-changed',
1329
1339
  });
@@ -1362,26 +1372,104 @@ class HyperFrame extends HTMLElement {
1362
1372
  }
1363
1373
  }
1364
1374
 
1365
- _resetReadyPromise() {
1366
- this._readyPromise = new Promise((resolve) => {
1367
- this._resolveReady = resolve;
1375
+ _createNotReadyError(message, {
1376
+ reason = this._notReadyReason(),
1377
+ retriable = !this._final,
1378
+ ...details
1379
+ } = {}) {
1380
+ return createBrowserBoxError(message, {
1381
+ code: ERROR_CODES.NOT_READY,
1382
+ retriable,
1383
+ status: 409,
1384
+ state: this._ready ? 'ready' : (this._final ? 'failed' : 'connecting'),
1385
+ reason,
1386
+ ...details,
1368
1387
  });
1369
1388
  }
1370
1389
 
1371
- _setReady() {
1372
- if (!this._isReady) {
1373
- this._isReady = true;
1374
- this._setUsable(true, 'ready');
1390
+ _resolveReadyWaiters() {
1391
+ for (const waiter of [...this._readyWaiters]) {
1392
+ this._readyWaiters.delete(waiter);
1393
+ waiter.resolve(true);
1394
+ }
1395
+ }
1396
+
1397
+ _rejectReadyWaiters(error) {
1398
+ for (const waiter of [...this._readyWaiters]) {
1399
+ this._readyWaiters.delete(waiter);
1400
+ waiter.reject(error);
1401
+ }
1402
+ }
1403
+
1404
+ get _ready() {
1405
+ return this._attached && !this._stopReason && this._viewerWord === 'ready';
1406
+ }
1407
+
1408
+ get _final() {
1409
+ return !this._attached || Boolean(this._stopReason) || this._viewerWord === 'fatal';
1410
+ }
1411
+
1412
+ _notReadyReason() {
1413
+ if (this._stopReason) return this._stopReason;
1414
+ if (!this._attached) return 'disconnected';
1415
+ if (this._viewerWord === 'fatal') return this._viewerReason || 'sos:browser-unusable';
1416
+ if (this._viewerWord === 'disconnected') return this._viewerReason || 'ws-closed';
1417
+ return 'connecting';
1418
+ }
1419
+
1420
+ _sync() {
1421
+ const ready = this._ready;
1422
+ const wasReady = this._wasReady;
1423
+ this._wasReady = ready;
1424
+ if (ready) {
1375
1425
  this._iframeRetryCount = 0;
1376
- this._reconnectStopped = false;
1377
1426
  this._stopInitPing();
1378
- if (typeof this._resolveReady === 'function') {
1379
- this._resolveReady(true);
1427
+ this._resolveReadyWaiters();
1428
+ if (!wasReady) {
1429
+ this._invalidateFrameBootstrap('ready');
1430
+ this._scheduleFrameBootstrap('ready', 120);
1431
+ this._startFrameBootstrapRetries('ready');
1432
+ this._emitBrowserBoxEvent('usability-changed', {
1433
+ usable: true,
1434
+ state: 'ready',
1435
+ reason: 'api-ready',
1436
+ });
1437
+ }
1438
+ return;
1439
+ }
1440
+
1441
+ const final = this._final;
1442
+ const reason = this._notReadyReason();
1443
+ this._invalidateFrameBootstrap(`${final ? 'failed' : 'connecting'}:${reason}`);
1444
+ if (wasReady || this._pending.size > 0) {
1445
+ const error = this._createNotReadyError(
1446
+ `hyper-frame session ${final ? 'failed' : 'not ready'} (${reason}).`,
1447
+ { reason, retriable: !final },
1448
+ );
1449
+ this._rememberError(error);
1450
+ this._rejectPending(error);
1451
+ }
1452
+ if (final) {
1453
+ this._stopInitPing();
1454
+ this._stopMidSync();
1455
+ if (this._readyWaiters.size > 0) {
1456
+ const error = this._createNotReadyError(
1457
+ `hyper-frame session failed (${reason}).`,
1458
+ { reason, retriable: false },
1459
+ );
1460
+ this._rememberError(error);
1461
+ this._rejectReadyWaiters(error);
1380
1462
  }
1463
+ if (wasReady || this._viewerWord === 'fatal') {
1464
+ this._emitBrowserBoxEvent('usability-changed', {
1465
+ usable: false,
1466
+ state: 'failed',
1467
+ reason,
1468
+ });
1469
+ }
1470
+ return;
1381
1471
  }
1382
- this._invalidateFrameBootstrap('ready');
1383
- this._scheduleFrameBootstrap('ready', 120);
1384
- this._startFrameBootstrapRetries('ready');
1472
+ this._startInitPing();
1385
1473
  }
1386
1474
 
1387
1475
  _rejectPending(error) {
@@ -1392,16 +1480,6 @@ class HyperFrame extends HTMLElement {
1392
1480
  this._pending.clear();
1393
1481
  }
1394
1482
 
1395
- _setUsable(next, reason = '') {
1396
- const usable = Boolean(next);
1397
- if (this._usable === usable) return;
1398
- this._usable = usable;
1399
- this._emitBrowserBoxEvent('usability-changed', {
1400
- usable,
1401
- reason,
1402
- });
1403
- }
1404
-
1405
1483
  _createAugmentLayer(space) {
1406
1484
  const layer = document.createElement('div');
1407
1485
  layer.className = 'bbx-layer';
@@ -1450,7 +1528,7 @@ class HyperFrame extends HTMLElement {
1450
1528
  this._frameBootstrapRetryRemaining = 0;
1451
1529
  }
1452
1530
 
1453
- _invalidateFrameBootstrap(_reason = 'state-changed') { // eslint-disable-line no-unused-vars
1531
+ _invalidateFrameBootstrap(_reason = 'state-changed') {
1454
1532
  this._frameBootstrapEpoch += 1;
1455
1533
  this._stopFrameBootstrap();
1456
1534
  this._stopFrameBootstrapRetries();
@@ -1638,9 +1716,6 @@ class HyperFrame extends HTMLElement {
1638
1716
  if (!ready) {
1639
1717
  return false;
1640
1718
  }
1641
- if (this._transportMode === 'unknown') {
1642
- await this._resolveTransport();
1643
- }
1644
1719
  const activeTab = await this._getActiveTabInfo(null).catch(() => null);
1645
1720
  const tabId = activeTab?.id || activeTab?.targetId || null;
1646
1721
  if (!tabId) {
@@ -1673,20 +1748,16 @@ class HyperFrame extends HTMLElement {
1673
1748
  if (!activeAfterResetId || activeAfterResetId !== tabId) {
1674
1749
  return false;
1675
1750
  }
1676
- if (this._transportMode === 'legacy') {
1677
- await this._legacyCall('switchToTabById', [tabId]);
1678
- } else {
1679
- await this._request('bbx-api-call', {
1680
- method: 'switchToTabById',
1681
- args: [tabId],
1682
- }, {
1683
- timeoutMs: Math.min(this.requestTimeoutMs, 5000),
1684
- });
1685
- }
1751
+ await this._request('bbx-api-call', {
1752
+ method: 'switchToTabById',
1753
+ args: [tabId],
1754
+ }, {
1755
+ timeoutMs: Math.min(this.requestTimeoutMs, 5000),
1756
+ });
1686
1757
  this._lastSuccessfulBootstrapAt = Date.now();
1687
1758
  console.info(`[hyper-frame] bootstrapped frame (${reason})`, {
1688
1759
  tabId,
1689
- transport: this._transportMode,
1760
+ transport: 'modern',
1690
1761
  kickedViewportGeometry,
1691
1762
  forcedViewportReset,
1692
1763
  });
@@ -1815,40 +1886,33 @@ class HyperFrame extends HTMLElement {
1815
1886
  }
1816
1887
 
1817
1888
  _handleLoad() {
1818
- if (this._reconnectStopped) {
1819
- return;
1889
+ if (this._wasReady) {
1890
+ this._iframeRetryCount = 0;
1820
1891
  }
1821
- const needsReset = this._isReady;
1822
- this._isReady = false;
1823
1892
  this._apiMethods = [];
1824
- this._transportMode = 'unknown';
1825
1893
  this._legacyTabsCache = [];
1826
1894
  this._initPingCount = 0;
1827
1895
  this._lastSuccessfulBootstrapAt = 0;
1828
- if (needsReset) {
1829
- this._iframeRetryCount = 0;
1830
- this._resetReadyPromise();
1831
- }
1896
+ this._viewerWord = 'none';
1897
+ this._viewerReason = '';
1832
1898
  this._midSyncAcked = false;
1833
1899
  this._uiSyncAcked = false;
1834
- this._startMidSync('iframe-load');
1835
- this._sendUISync('iframe-load');
1836
- this._startInitPing();
1900
+ this._sync();
1901
+ if (!this._final) {
1902
+ this._startMidSync('iframe-load');
1903
+ this._sendUISync('iframe-load');
1904
+ }
1837
1905
  }
1838
1906
 
1839
1907
  _startInitPing() {
1840
- if (this._reconnectStopped) {
1908
+ if (this._ready || this._final) {
1841
1909
  return;
1842
1910
  }
1843
1911
  this._stopInitPing();
1844
1912
  this._initPingCount = 0;
1845
1913
  this._postRaw({ type: 'init' });
1846
1914
  this._initPingTimer = setInterval(() => {
1847
- if (this._reconnectStopped) {
1848
- this._stopInitPing();
1849
- return;
1850
- }
1851
- if (this._isReady) {
1915
+ if (this._ready || this._final) {
1852
1916
  this._stopInitPing();
1853
1917
  return;
1854
1918
  }
@@ -1861,7 +1925,9 @@ class HyperFrame extends HTMLElement {
1861
1925
  if (this._attemptSilentRecovery('iframe-unresponsive')) {
1862
1926
  return;
1863
1927
  }
1864
- this.stopReconnectAttempts('iframe-unresponsive');
1928
+ this._viewerWord = 'fatal';
1929
+ this._viewerReason = 'iframe-unresponsive';
1930
+ this._sync();
1865
1931
  return;
1866
1932
  }
1867
1933
  this._postRaw({ type: 'init' });
@@ -1884,14 +1950,14 @@ class HyperFrame extends HTMLElement {
1884
1950
  delayMs: delay,
1885
1951
  });
1886
1952
  setTimeout(() => {
1887
- if (this._isReady || this._reconnectStopped) return;
1953
+ if (this._ready || this._final) return;
1888
1954
  this._assignIframeSrc(src, '_retryIframeLoad');
1889
1955
  }, delay);
1890
1956
  }
1891
1957
 
1892
1958
  _assignIframeSrc(nextSrc, reason) {
1893
1959
  const stack = new Error().stack || '(no stack available)';
1894
- debugBrowserBoxWebview('[DEBUG][SRC_ASSIGN]', {
1960
+ debugHyperFrame('[DEBUG][SRC_ASSIGN]', {
1895
1961
  reason,
1896
1962
  currentSrc: this.iframe.src,
1897
1963
  nextSrc,
@@ -1934,21 +2000,14 @@ class HyperFrame extends HTMLElement {
1934
2000
  }
1935
2001
 
1936
2002
  this._silentRecoveryUsed = true;
1937
- this._isReady = false;
1938
2003
  this._apiMethods = [];
1939
- this._transportMode = 'unknown';
1940
2004
  this._legacyTabsCache = [];
1941
2005
  this._iframeRetryCount = 0;
1942
2006
  this._initPingCount = 0;
1943
2007
  this._midSyncAcked = false;
1944
- this._reconnectStopped = false;
1945
- this._resetReadyPromise();
1946
- this._rejectPending(createBrowserBoxError(`hyper-frame silent recovery (${reason}).`, {
1947
- code: ERROR_CODES.TRANSPORT,
1948
- retriable: true,
1949
- status: 503,
1950
- reason,
1951
- }));
2008
+ this._viewerWord = 'none';
2009
+ this._viewerReason = '';
2010
+ this._sync();
1952
2011
 
1953
2012
  console.info('[hyper-frame] attempting one-shot silent recovery reload', {
1954
2013
  reason,
@@ -2089,7 +2148,6 @@ class HyperFrame extends HTMLElement {
2089
2148
  mid: this._routingMid,
2090
2149
  },
2091
2150
  }));
2092
- this._setUsable(false, 'mid-sync-timeout');
2093
2151
  return;
2094
2152
  }
2095
2153
  this._midSyncAttempt += 1;
@@ -2439,6 +2497,32 @@ class HyperFrame extends HTMLElement {
2439
2497
  this._legacyTabsCache = this._legacyTabsCache.map((tab, i) => ({ ...tab, index: i }));
2440
2498
  }
2441
2499
 
2500
+ _resetTabsToCleanSlate(force = false, urlOverride = null) {
2501
+ const attrValue = this.getAttribute('first-load-cleanse');
2502
+ if (!force && attrValue === null) return;
2503
+ const loginLink = this.getAttribute('login-link');
2504
+ if (!loginLink) return;
2505
+ const storageKey = `bbx-session-init:${loginLink}`;
2506
+ try {
2507
+ if (localStorage.getItem(storageKey)) return;
2508
+ localStorage.setItem(storageKey, '1');
2509
+ } catch {
2510
+ return;
2511
+ }
2512
+
2513
+ const candidateUrl = urlOverride ?? attrValue;
2514
+ const url = typeof candidateUrl === 'string' && candidateUrl.length > 0 ? candidateUrl : null;
2515
+
2516
+ const snapshot = this._legacyTabsCache.slice();
2517
+ for (let i = snapshot.length - 1; i >= 0; i--) {
2518
+ const tabId = snapshot[i]?.id || snapshot[i]?.targetId;
2519
+ if (tabId) this._postRaw({ type: 'closeTab', tabId, data: {} });
2520
+ }
2521
+ if (url) {
2522
+ this._postRaw({ type: 'createTab', data: { url } });
2523
+ }
2524
+ }
2525
+
2442
2526
  _removeLegacyTabCache(detail) {
2443
2527
  const tabId = this._normalizeTabId(detail);
2444
2528
  if (!tabId) return;
@@ -2511,12 +2595,6 @@ class HyperFrame extends HTMLElement {
2511
2595
  for (const capability of this._capabilitiesForMethod(normalizedMethod, args)) {
2512
2596
  this._assertCapability(capability);
2513
2597
  }
2514
- if (this._transportMode === 'unknown') {
2515
- await this._resolveTransport();
2516
- }
2517
- if (this._transportMode === 'legacy') {
2518
- return this._legacyCall(normalizedMethod, args);
2519
- }
2520
2598
  return this._request('bbx-api-call', { method: normalizedMethod, args }, requestOptions);
2521
2599
  }
2522
2600
 
@@ -2895,7 +2973,9 @@ class HyperFrame extends HTMLElement {
2895
2973
  forwardedAt: Date.now(),
2896
2974
  forwardedBy: 'hyper-frame',
2897
2975
  };
2898
- this._setUsable(false, `sos:${reasonCode}`);
2976
+ this._viewerWord = 'fatal';
2977
+ this._viewerReason = `sos:${reasonCode}`;
2978
+ this._sync();
2899
2979
  this._emitBrowserBoxEvent('sos', detail);
2900
2980
  this._forwardToParent({
2901
2981
  type: 'bbx-sos',
@@ -2922,23 +3002,39 @@ class HyperFrame extends HTMLElement {
2922
3002
  return;
2923
3003
  }
2924
3004
 
2925
- if (payload.type === 'tab-api-ready') {
2926
- this._setReady();
2927
- this._emitBrowserBoxEvent('ready', { type: payload.type });
2928
- return;
2929
- }
2930
-
2931
3005
  if (payload.type === 'bbx-api-ready') {
2932
3006
  if (Array.isArray(payload.data?.methods)) {
2933
3007
  this._apiMethods = payload.data.methods.slice();
2934
- this._transportMode = 'modern';
2935
3008
  }
2936
3009
  if (payload.data?.policy) {
2937
3010
  this._serverPolicySnapshot = normalizePolicyStateSnapshot(payload.data.policy);
2938
3011
  this._refreshPolicyState('server-policy-ready');
2939
3012
  }
2940
- this._setReady();
2941
- this._emitBrowserBoxEvent('api-ready', payload.data || {});
3013
+ const wasReady = this._ready;
3014
+ this._viewerWord = 'ready';
3015
+ this._viewerReason = '';
3016
+ this._sync();
3017
+ if (this._ready) {
3018
+ this._emitBrowserBoxEvent('ready', { type: 'tab-api-ready' });
3019
+ this._emitBrowserBoxEvent('api-ready', payload.data || {});
3020
+ if (!wasReady) this._resetTabsToCleanSlate();
3021
+ }
3022
+ return;
3023
+ }
3024
+
3025
+ if (payload.type === 'disconnected') {
3026
+ const reason = typeof payload.data?.reason === 'string' && payload.data.reason.length > 0
3027
+ ? payload.data.reason
3028
+ : 'ws-closed';
3029
+ if (this._viewerWord !== 'fatal') {
3030
+ this._viewerWord = 'disconnected';
3031
+ this._viewerReason = reason;
3032
+ }
3033
+ this._sync();
3034
+ this._emitBrowserBoxEvent('disconnected', {
3035
+ ...(payload.data && typeof payload.data === 'object' ? payload.data : {}),
3036
+ reason,
3037
+ });
2942
3038
  return;
2943
3039
  }
2944
3040
 
@@ -2964,6 +3060,19 @@ class HyperFrame extends HTMLElement {
2964
3060
  }
2965
3061
 
2966
3062
  _request(type, data = {}, options = {}) {
3063
+ if (!this._ready) {
3064
+ const reason = this._notReadyReason();
3065
+ const error = this._createNotReadyError(
3066
+ `hyper-frame session is not ready (${reason}).`,
3067
+ {
3068
+ reason,
3069
+ retriable: !this._final,
3070
+ requestType: type,
3071
+ },
3072
+ );
3073
+ this._rememberError(error);
3074
+ return Promise.reject(error);
3075
+ }
2967
3076
  if (!this.iframe.contentWindow) {
2968
3077
  const error = createBrowserBoxError('hyper-frame iframe is not ready.', {
2969
3078
  code: ERROR_CODES.TRANSPORT,
@@ -3037,21 +3146,44 @@ class HyperFrame extends HTMLElement {
3037
3146
  }
3038
3147
 
3039
3148
  async whenReady({ timeoutMs = this.requestTimeoutMs } = {}) {
3040
- if (this._isReady) {
3149
+ if (this._ready) {
3041
3150
  return true;
3042
3151
  }
3152
+ if (this._final) {
3153
+ const reason = this._notReadyReason();
3154
+ throw this._createNotReadyError(
3155
+ `hyper-frame is not ready (${reason}).`,
3156
+ { reason, retriable: false },
3157
+ );
3158
+ }
3043
3159
 
3044
- const timeout = new Promise((_, reject) => {
3045
- setTimeout(() => reject(createBrowserBoxError(`hyper-frame ready timeout after ${timeoutMs}ms.`, {
3046
- code: ERROR_CODES.TIMEOUT,
3047
- retriable: true,
3048
- status: 504,
3049
- timeoutMs,
3050
- })), timeoutMs);
3160
+ return new Promise((resolve, reject) => {
3161
+ const waiter = {
3162
+ resolve: (value) => {
3163
+ clearTimeout(timer);
3164
+ this._readyWaiters.delete(waiter);
3165
+ resolve(value);
3166
+ },
3167
+ reject: (error) => {
3168
+ clearTimeout(timer);
3169
+ this._readyWaiters.delete(waiter);
3170
+ reject(error);
3171
+ },
3172
+ };
3173
+ const timer = setTimeout(() => {
3174
+ this._readyWaiters.delete(waiter);
3175
+ const reason = this._notReadyReason();
3176
+ reject(createBrowserBoxError(`hyper-frame ready timeout after ${timeoutMs}ms.`, {
3177
+ code: ERROR_CODES.TIMEOUT,
3178
+ retriable: !this._final,
3179
+ status: 504,
3180
+ timeoutMs,
3181
+ state: this._ready ? 'ready' : (this._final ? 'failed' : 'connecting'),
3182
+ reason,
3183
+ }));
3184
+ }, timeoutMs);
3185
+ this._readyWaiters.add(waiter);
3051
3186
  });
3052
-
3053
- await Promise.race([this._readyPromise, timeout]);
3054
- return true;
3055
3187
  }
3056
3188
 
3057
3189
  on(eventName, handler, options) {
@@ -3156,15 +3288,30 @@ class HyperFrame extends HTMLElement {
3156
3288
  }
3157
3289
 
3158
3290
  async _ensureReadyForApi() {
3159
- if (this._isReady) {
3291
+ if (this._ready) {
3160
3292
  return true;
3161
3293
  }
3294
+ if (this._final) {
3295
+ const reason = this._notReadyReason();
3296
+ const error = this._createNotReadyError(
3297
+ `hyper-frame session is not ready (${reason}).`,
3298
+ {
3299
+ reason,
3300
+ retriable: false,
3301
+ },
3302
+ );
3303
+ this._rememberError(error);
3304
+ throw error;
3305
+ }
3162
3306
  const softTimeoutMs = Math.min(this.requestTimeoutMs, 8000);
3163
3307
  try {
3164
3308
  await this.whenReady({ timeoutMs: softTimeoutMs });
3165
3309
  return true;
3166
3310
  } catch (error) {
3167
3311
  this._rememberError(error);
3312
+ if (this._final || error?.code === ERROR_CODES.NOT_READY) {
3313
+ throw error;
3314
+ }
3168
3315
  this.dispatchEvent(new CustomEvent('ready-timeout', {
3169
3316
  detail: {
3170
3317
  timeoutMs: softTimeoutMs,
@@ -3175,78 +3322,25 @@ class HyperFrame extends HTMLElement {
3175
3322
  }
3176
3323
  }
3177
3324
 
3178
- _legacyMethodList() {
3179
- return [
3180
- 'getTabs',
3181
- 'getActiveTabIndex',
3182
- 'getTabCount',
3183
- 'createTab',
3184
- 'createTabs',
3185
- 'closeTab',
3186
- 'closeTabById',
3187
- 'closeAllTabs',
3188
- 'switchToTab',
3189
- 'switchToTabById',
3190
- 'navigateTo',
3191
- 'navigateTab',
3192
- 'submitOmnibox',
3193
- 'reload',
3194
- 'goBack',
3195
- 'goForward',
3196
- 'stop',
3197
- 'evaluate',
3198
- 'waitForTabCount',
3199
- 'waitForTabUrl',
3200
- ];
3201
- }
3202
-
3203
- /**
3204
- * Resolve transport mode. Called once on first API call if transport is
3205
- * still 'unknown'. After resolution, transport is locked for the session.
3206
- * @returns {Promise<'modern'|'legacy'>}
3207
- */
3208
- async _resolveTransport() {
3209
- if (this._transportMode !== 'unknown') return this._transportMode;
3210
- try {
3211
- await this._request('bbx-api-call', { method: 'getTabCount', args: [] }, {
3212
- timeoutMs: Math.min(this.requestTimeoutMs, 5000),
3213
- });
3214
- this._transportMode = 'modern';
3215
- } catch {
3216
- this._transportMode = 'legacy';
3217
- }
3218
- return this._transportMode;
3219
- }
3220
-
3221
3325
  async listApiMethods(options = {}) {
3222
3326
  if (this._apiMethods.length > 0 && options.refresh !== true) {
3223
3327
  return this._apiMethods.slice();
3224
3328
  }
3225
3329
  const ready = await this._ensureReadyForApi();
3226
3330
  if (!ready) {
3227
- throw createBrowserBoxError('hyper-frame API handshake is not ready.', {
3228
- code: ERROR_CODES.NOT_READY,
3229
- retriable: true,
3230
- status: 409,
3331
+ const reason = this._notReadyReason();
3332
+ throw this._createNotReadyError('hyper-frame API handshake is not ready.', {
3333
+ reason,
3334
+ retriable: !this._final,
3231
3335
  });
3232
3336
  }
3233
- if (this._transportMode === 'legacy') {
3234
- this._apiMethods = this._legacyMethodList();
3235
- return this._apiMethods.slice();
3236
- }
3237
- try {
3238
- const methods = await this._request('bbx-api-list', {}, {
3239
- ...options,
3240
- timeoutMs: Number.isFinite(options.timeoutMs)
3241
- ? options.timeoutMs
3242
- : Math.min(this.requestTimeoutMs, 30000),
3243
- });
3244
- this._apiMethods = Array.isArray(methods) ? methods.slice() : [];
3245
- this._transportMode = 'modern';
3246
- } catch {
3247
- this._transportMode = 'legacy';
3248
- this._apiMethods = this._legacyMethodList();
3249
- }
3337
+ const methods = await this._request('bbx-api-list', {}, {
3338
+ ...options,
3339
+ timeoutMs: Number.isFinite(options.timeoutMs)
3340
+ ? options.timeoutMs
3341
+ : Math.min(this.requestTimeoutMs, 30000),
3342
+ });
3343
+ this._apiMethods = Array.isArray(methods) ? methods.slice() : [];
3250
3344
  return this._apiMethods.slice();
3251
3345
  }
3252
3346
 
@@ -3261,50 +3355,32 @@ class HyperFrame extends HTMLElement {
3261
3355
  if (typeof method !== 'string' || method.trim().length === 0) {
3262
3356
  throwInvalidArgument('callApi(method, ...args) requires a non-empty method string.');
3263
3357
  }
3264
- const invoke = async () => {
3358
+ const normalizedMethod = method.trim();
3359
+ try {
3265
3360
  const ready = await this._ensureReadyForApi();
3266
3361
  if (!ready) {
3267
- throw createBrowserBoxError(`hyper-frame API method '${method}' called before handshake completed.`, {
3268
- code: ERROR_CODES.NOT_READY,
3269
- retriable: true,
3270
- status: 409,
3271
- method,
3272
- });
3362
+ const reason = this._notReadyReason();
3363
+ throw this._createNotReadyError(
3364
+ `hyper-frame API method '${normalizedMethod}' called before handshake completed.`,
3365
+ {
3366
+ reason,
3367
+ retriable: !this._final,
3368
+ method: normalizedMethod,
3369
+ },
3370
+ );
3273
3371
  }
3274
- const normalizedMethod = method.trim();
3275
3372
  for (const capability of this._capabilitiesForMethod(normalizedMethod, args)) {
3276
3373
  this._assertCapability(capability);
3277
3374
  }
3278
-
3279
- if (this._transportMode === 'unknown') {
3280
- await this._resolveTransport();
3281
- }
3282
-
3283
- if (this._transportMode === 'legacy') {
3284
- return this._legacyCall(normalizedMethod, args);
3285
- }
3286
-
3287
- return this._request('bbx-api-call', { method: normalizedMethod, args }, {
3375
+ const result = await this._request('bbx-api-call', { method: normalizedMethod, args }, {
3288
3376
  timeoutMs: this.requestTimeoutMs,
3289
3377
  });
3290
- };
3291
-
3292
- try {
3293
- const result = await this._withRetry(invoke, {
3294
- attempts: 3,
3295
- baseDelayMs: 300,
3296
- maxDelayMs: 1500,
3297
- shouldRetry: (error) => this._isRetryableApiError(error),
3298
- });
3299
3378
  this._rememberError(null);
3300
- this._setUsable(true, 'api-ok');
3301
3379
  return result;
3302
3380
  } catch (error) {
3303
- this._rememberError(error);
3304
- if (this._isRetryableApiError(error)) {
3305
- this._setUsable(false, 'api-failed');
3306
- }
3307
- throw this._normalizeRemoteError(error, { method });
3381
+ const normalizedError = this._normalizeRemoteError(error, { method: normalizedMethod });
3382
+ this._rememberError(normalizedError);
3383
+ throw normalizedError;
3308
3384
  }
3309
3385
  }
3310
3386
 
@@ -3424,18 +3500,22 @@ class HyperFrame extends HTMLElement {
3424
3500
  stop() { return this.callApi('stop'); }
3425
3501
  getScreenMetrics() { return this.callApi('getScreenMetrics'); }
3426
3502
  getTransportDiagnostics() { return this.callApi('getTransportDiagnostics'); }
3503
+ getSessionDiagnostics(options = {}) { return this.callApi('getSessionDiagnostics', options); }
3427
3504
  frameCapture(enabled = true) { return this.callApi('frameCapture', Boolean(enabled)); }
3428
3505
  getFrame() { return this.callApi('getFrame'); }
3429
3506
  cleanSlate(url) { return this.callApi('cleanSlate', url); }
3507
+ firstLoadCleanse(url = null) { return this._resetTabsToCleanSlate(true, url); }
3430
3508
  async health({ timeoutMs } = {}) {
3431
3509
  const startedAt = (typeof performance !== 'undefined' && typeof performance.now === 'function')
3432
3510
  ? performance.now()
3433
3511
  : Date.now();
3434
- const finalize = (ok, transport, error = null) => ({
3512
+ const finalize = (ok, error = null) => ({
3435
3513
  ok,
3436
- usable: this._usable,
3437
- ready: this._isReady,
3438
- transport,
3514
+ state: this._ready ? 'ready' : (this._final ? 'failed' : 'connecting'),
3515
+ reason: this._ready ? 'api-ready' : this._notReadyReason(),
3516
+ usable: this._ready,
3517
+ ready: this._ready,
3518
+ transport: 'modern',
3439
3519
  sessionId: this.routingMid || null,
3440
3520
  timestamp: new Date().toISOString(),
3441
3521
  latencyMs: Math.max(
@@ -3445,76 +3525,32 @@ class HyperFrame extends HTMLElement {
3445
3525
  : Date.now()) - startedAt),
3446
3526
  ),
3447
3527
  diagnostics: {
3448
- reconnecting: !this._isReady && !this._reconnectStopped,
3528
+ reconnecting: !this._ready && !this._final,
3449
3529
  lastErrorCode: error?.code || this._lastError?.code,
3450
3530
  lastErrorMessage: error?.message || this._lastError?.message,
3451
3531
  },
3452
3532
  });
3453
3533
  if (!this.iframe.contentWindow) {
3454
- this._setUsable(false, 'iframe-not-ready');
3455
3534
  const error = createBrowserBoxError('hyper-frame health check failed: iframe is not ready.', {
3456
3535
  code: ERROR_CODES.TRANSPORT,
3457
3536
  retriable: true,
3458
3537
  status: 503,
3459
3538
  });
3460
- this._rememberError(error);
3461
- return finalize(false, this._transportMode, error);
3539
+ return finalize(false, error);
3462
3540
  }
3463
3541
  const effectiveTimeoutMs = Number.isFinite(timeoutMs)
3464
3542
  ? Math.max(100, Math.round(timeoutMs))
3465
3543
  : Math.min(this.requestTimeoutMs, 8000);
3466
- const tryModern = () => this._request(
3467
- 'bbx-api-call',
3468
- { method: 'getTabCount', args: [] },
3469
- { timeoutMs: effectiveTimeoutMs },
3470
- );
3471
- const tryLegacy = () => this._request('getTabCount', {}, { timeoutMs: effectiveTimeoutMs });
3472
-
3473
3544
  try {
3474
- const result = await this._withRetry(async () => {
3475
- if (this._transportMode === 'modern') {
3476
- await tryModern();
3477
- return true;
3478
- }
3479
- if (this._transportMode === 'legacy') {
3480
- await tryLegacy();
3481
- return true;
3482
- }
3483
- try {
3484
- await tryModern();
3485
- this._transportMode = 'modern';
3486
- return true;
3487
- } catch (modernError) {
3488
- try {
3489
- await tryLegacy();
3490
- this._transportMode = 'legacy';
3491
- return true;
3492
- } catch (legacyError) {
3493
- const message = `hyper-frame health check failed after ${effectiveTimeoutMs}ms `
3494
- + `(modern error: ${modernError instanceof Error ? modernError.message : String(modernError)}; `
3495
- + `legacy error: ${legacyError instanceof Error ? legacyError.message : String(legacyError)})`;
3496
- throw createBrowserBoxError(message, {
3497
- code: ERROR_CODES.TRANSPORT,
3498
- retriable: true,
3499
- status: 503,
3500
- cause: legacyError,
3501
- });
3502
- }
3503
- }
3504
- }, {
3505
- attempts: 2,
3506
- baseDelayMs: 250,
3507
- maxDelayMs: 750,
3508
- shouldRetry: (error) => this._isRetryableApiError(error),
3509
- });
3510
- this._rememberError(null);
3511
- this._setUsable(true, 'health-ok');
3512
- return finalize(Boolean(result), this._transportMode);
3545
+ await this._request(
3546
+ 'bbx-api-call',
3547
+ { method: 'getTabCount', args: [] },
3548
+ { timeoutMs: effectiveTimeoutMs },
3549
+ );
3550
+ return finalize(true);
3513
3551
  } catch (error) {
3514
3552
  const normalizedError = this._normalizeRemoteError(error, { method: 'health' });
3515
- this._rememberError(normalizedError);
3516
- this._setUsable(false, 'health-failed');
3517
- return finalize(false, this._transportMode, normalizedError);
3553
+ return finalize(false, normalizedError);
3518
3554
  }
3519
3555
  }
3520
3556
 
@@ -3553,31 +3589,24 @@ class HyperFrame extends HTMLElement {
3553
3589
  waitForNavigation(opts = {}) { return this.callApi('waitForNavigation', opts); }
3554
3590
 
3555
3591
  refresh() {
3592
+ this._stopReason = '';
3593
+ this._viewerWord = 'none';
3594
+ this._viewerReason = '';
3556
3595
  if (this.iframe.src) {
3557
- this._isReady = false;
3558
3596
  this._apiMethods = [];
3559
- this._transportMode = 'unknown';
3560
3597
  this._legacyTabsCache = [];
3561
- this._reconnectStopped = false;
3562
3598
  this._midSyncAcked = false;
3563
- this._resetReadyPromise();
3564
- this._rejectPending(createBrowserBoxError('hyper-frame refreshed.', {
3565
- code: ERROR_CODES.TRANSPORT,
3566
- retriable: true,
3567
- status: 503,
3568
- }));
3569
3599
  const currentSrc = this.iframe.src;
3570
3600
  this._assignIframeSrc(currentSrc, 'refresh');
3571
3601
  }
3602
+ this._sync();
3572
3603
  }
3573
3604
 
3574
3605
  async disconnect() {
3575
- this.stopReconnectAttempts('session.disconnect');
3576
- this._isReady = false;
3577
3606
  this._apiMethods = [];
3578
- this._transportMode = 'unknown';
3579
3607
  this._legacyTabsCache = [];
3580
- this._resetReadyPromise();
3608
+ this._stopReason = 'session.disconnect';
3609
+ this._sync();
3581
3610
  if (this.iframe.src) {
3582
3611
  this.iframe.removeAttribute('src');
3583
3612
  }
@@ -3588,16 +3617,9 @@ class HyperFrame extends HTMLElement {
3588
3617
  }
3589
3618
 
3590
3619
  stopReconnectAttempts(reason = 'manual-stop') {
3591
- this._reconnectStopped = true;
3592
- this._stopInitPing();
3593
- this._stopMidSync();
3594
- this._setUsable(false, reason);
3595
- this._rejectPending(createBrowserBoxError(`hyper-frame reconnect stopped (${reason}).`, {
3596
- code: ERROR_CODES.TRANSPORT,
3597
- retriable: true,
3598
- status: 503,
3599
- reason,
3600
- }));
3620
+ const normalized = String(reason || 'manual-stop');
3621
+ this._stopReason = normalized === 'disconnected' ? 'manual-stop' : normalized;
3622
+ this._sync();
3601
3623
  }
3602
3624
 
3603
3625
  /**
@@ -3634,16 +3656,12 @@ class HyperFrame extends HTMLElement {
3634
3656
  this.requestFrameRefresh(reason);
3635
3657
  return false;
3636
3658
  }
3637
- if (this._transportMode === 'legacy') {
3638
- await this._legacyCall('switchToTabById', [tabId]);
3639
- } else {
3640
- await this._request('bbx-api-call', {
3641
- method: 'switchToTabById',
3642
- args: [tabId],
3643
- }, {
3644
- timeoutMs: Math.min(this.requestTimeoutMs, 5000),
3645
- });
3646
- }
3659
+ await this._request('bbx-api-call', {
3660
+ method: 'switchToTabById',
3661
+ args: [tabId],
3662
+ }, {
3663
+ timeoutMs: Math.min(this.requestTimeoutMs, 5000),
3664
+ });
3647
3665
  console.info('[hyper-frame] reactivateActiveTab succeeded', { reason, tabId });
3648
3666
  return true;
3649
3667
  } catch (error) {
@@ -3731,254 +3749,6 @@ class HyperFrame extends HTMLElement {
3731
3749
  }
3732
3750
  this.setAttribute('request-timeout-ms', String(value));
3733
3751
  }
3734
-
3735
- /**
3736
- * Legacy transport dispatch. Each handler is a small function in a lookup
3737
- * table — avoids the 180-line if/else chain (Architecture §6, §3).
3738
- * @param {string} method
3739
- * @param {Array} args
3740
- * @param {Error|null} originalError
3741
- * @returns {Promise<*>}
3742
- */
3743
- async _legacyCall(method, args = [], originalError = null) {
3744
- const handler = this._legacyHandlers[method];
3745
- if (!handler) {
3746
- const detail = originalError?.message ? ` (${originalError.message})` : '';
3747
- throw createBrowserBoxError(`No legacy fallback for API method '${method}'${detail}`, {
3748
- code: ERROR_CODES.UNSUPPORTED,
3749
- status: 501,
3750
- method,
3751
- ...(originalError ? { cause: originalError } : {}),
3752
- });
3753
- }
3754
- return handler.call(this, args, originalError);
3755
- }
3756
-
3757
- get _legacyHandlers() {
3758
- if (this.__legacyHandlers) return this.__legacyHandlers;
3759
- const self = this;
3760
-
3761
- const fail = (message, originalError = null) => {
3762
- const detail = originalError?.message ? ` (${originalError.message})` : '';
3763
- throw self._normalizeRemoteError(
3764
- createBrowserBoxError(`${message}${detail}`, {
3765
- code: ERROR_CODES.INTERNAL,
3766
- status: 500,
3767
- ...(originalError ? { cause: originalError } : {}),
3768
- }),
3769
- );
3770
- };
3771
-
3772
- const resolveTabId = async (indexArg = null) => {
3773
- if (typeof indexArg === 'string' && indexArg.trim().length > 0) return indexArg.trim();
3774
- const tabs = await self._legacyHandlers.getTabs.call(self, []);
3775
- if (Array.isArray(tabs) && tabs.length > 0) {
3776
- const requested = Number.isInteger(indexArg) ? indexArg : 0;
3777
- const normalized = requested < 0 ? tabs.length + requested : requested;
3778
- const safeIndex = Math.max(0, Math.min(tabs.length - 1, normalized));
3779
- return tabs[safeIndex]?.id || tabs[safeIndex]?.targetId || null;
3780
- }
3781
- const activeTab = await self._request('getActiveTab', {}).catch(() => null);
3782
- return activeTab?.id || activeTab?.targetId || null;
3783
- };
3784
-
3785
- this.__legacyHandlers = {
3786
- async getTabs() {
3787
- let tabs;
3788
- try {
3789
- tabs = await self._request('getTabs', {});
3790
- } catch {
3791
- tabs = self._legacyTabsCache.slice();
3792
- }
3793
- if (!Array.isArray(tabs)) return self._legacyTabsCache.slice();
3794
- const normalizedTabs = tabs.map((tab, index) => ({ index, ...tab }));
3795
- self._legacyTabsCache = normalizedTabs.slice();
3796
- return normalizedTabs;
3797
- },
3798
-
3799
- async getActiveTabIndex() {
3800
- const [tabs, activeTab] = await Promise.all([
3801
- self._legacyHandlers.getTabs.call(self, []),
3802
- self._request('getActiveTab', {}).catch(() => null),
3803
- ]);
3804
- if (!activeTab || !Array.isArray(tabs)) return -1;
3805
- const activeId = activeTab.id || activeTab.targetId || null;
3806
- return tabs.findIndex((tab) => (tab.id || tab.targetId) === activeId);
3807
- },
3808
-
3809
- async getTabCount() {
3810
- const tabs = await self._legacyHandlers.getTabs.call(self, []);
3811
- return Array.isArray(tabs) ? tabs.length : 0;
3812
- },
3813
-
3814
- async createTab(args) {
3815
- const url = typeof args[0] === 'string' ? args[0] : '';
3816
- self._postRaw({ type: 'createTab', data: { url } });
3817
- return true;
3818
- },
3819
-
3820
- async createTabs(args) {
3821
- const count = Number.isInteger(args[0]) && args[0] > 0 ? args[0] : 0;
3822
- const opts = args[1] || {};
3823
- const url = typeof opts.url === 'string' ? opts.url : '';
3824
- for (let i = 0; i < count; i += 1) {
3825
- self._postRaw({ type: 'createTab', data: { url } });
3826
- }
3827
- return true;
3828
- },
3829
-
3830
- async closeTab(args, originalError) {
3831
- const tabId = await resolveTabId(args[0]);
3832
- if (!tabId) fail('Legacy closeTab failed: no target tab', originalError);
3833
- self._postRaw({ type: 'closeTab', tabId, data: {} });
3834
- return true;
3835
- },
3836
-
3837
- async closeTabById(args, originalError) {
3838
- const tabId = typeof args[0] === 'string' && args[0].trim().length > 0 ? args[0].trim() : null;
3839
- if (!tabId) fail('Legacy closeTabById requires a non-empty targetId string', originalError);
3840
- self._postRaw({ type: 'closeTab', tabId, data: {} });
3841
- return true;
3842
- },
3843
-
3844
- async closeAllTabs(args) {
3845
- const opts = args[0] || {};
3846
- const keep = Number.isInteger(opts.keep) ? Math.max(0, opts.keep) : 0;
3847
- const tabs = await self._legacyHandlers.getTabs.call(self, []);
3848
- if (!Array.isArray(tabs) || tabs.length <= keep) return tabs?.length || 0;
3849
- for (let i = tabs.length - 1; i >= keep; i -= 1) {
3850
- const tabId = tabs[i]?.id || tabs[i]?.targetId;
3851
- if (!tabId) continue;
3852
- self._postRaw({ type: 'closeTab', tabId, data: {} });
3853
- }
3854
- return Math.max(keep, 0);
3855
- },
3856
-
3857
- async switchToTab(args, originalError) {
3858
- const tabId = await resolveTabId(args[0]);
3859
- if (!tabId) fail('Legacy switchToTab failed: no target tab', originalError);
3860
- self._postRaw({ type: 'setActiveTab', tabId, data: {} });
3861
- return true;
3862
- },
3863
-
3864
- async switchToTabById(args, originalError) {
3865
- const tabId = typeof args[0] === 'string' && args[0].trim().length > 0 ? args[0].trim() : null;
3866
- if (!tabId) fail('Legacy switchToTabById requires a non-empty targetId string', originalError);
3867
- self._postRaw({ type: 'setActiveTab', tabId, data: {} });
3868
- return true;
3869
- },
3870
-
3871
- async navigateTo(args, originalError) {
3872
- const url = typeof args[0] === 'string' ? args[0] : '';
3873
- const tabId = await resolveTabId(null);
3874
- if (!tabId) fail('Legacy navigateTo failed: no active tab', originalError);
3875
- self._postRaw({ type: 'loadURL', tabId, data: { url } });
3876
- return true;
3877
- },
3878
-
3879
- async navigateTab(args, originalError) {
3880
- const tabId = await resolveTabId(args[0]);
3881
- const url = typeof args[1] === 'string' ? args[1] : '';
3882
- if (!tabId) fail('Legacy navigateTab failed: no target tab', originalError);
3883
- self._postRaw({ type: 'setActiveTab', tabId, data: {} });
3884
- self._postRaw({ type: 'loadURL', tabId, data: { url } });
3885
- return true;
3886
- },
3887
-
3888
- async submitOmnibox(args, originalError) {
3889
- const query = typeof args[0] === 'string' ? args[0] : '';
3890
- return self._legacyHandlers.navigateTo.call(self, [query], originalError);
3891
- },
3892
-
3893
- async reload(args, originalError) {
3894
- const tabId = await resolveTabId(null);
3895
- if (!tabId) fail('Legacy reload failed: no active tab', originalError);
3896
- self._postRaw({ type: 'reload', tabId, data: {} });
3897
- return true;
3898
- },
3899
-
3900
- async goBack(args, originalError) {
3901
- const tabId = await resolveTabId(null);
3902
- if (!tabId) fail('Legacy goBack failed: no active tab', originalError);
3903
- self._postRaw({ type: 'goBack', tabId, data: {} });
3904
- return true;
3905
- },
3906
-
3907
- async goForward(args, originalError) {
3908
- const tabId = await resolveTabId(null);
3909
- if (!tabId) fail('Legacy goForward failed: no active tab', originalError);
3910
- self._postRaw({ type: 'goForward', tabId, data: {} });
3911
- return true;
3912
- },
3913
-
3914
- async stop(args, originalError) {
3915
- const tabId = await resolveTabId(null);
3916
- if (!tabId) fail('Legacy stop failed: no active tab', originalError);
3917
- self._postRaw({ type: 'stop', tabId, data: {} });
3918
- return true;
3919
- },
3920
-
3921
- async evaluate(args, originalError) {
3922
- const expression = typeof args[0] === 'string' ? args[0] : '';
3923
- const tabId = await resolveTabId(null);
3924
- if (!tabId) fail('Legacy evaluate failed: no active tab', originalError);
3925
- if (expression.includes('history.back')) {
3926
- self._postRaw({ type: 'goBack', tabId, data: {} });
3927
- return true;
3928
- }
3929
- if (expression.includes('history.forward')) {
3930
- self._postRaw({ type: 'goForward', tabId, data: {} });
3931
- return true;
3932
- }
3933
- if (expression.includes('window.stop')) {
3934
- self._postRaw({ type: 'stop', tabId, data: {} });
3935
- return true;
3936
- }
3937
- fail('Legacy evaluate only supports history.back, history.forward, and window.stop', originalError);
3938
- },
3939
-
3940
- async waitForTabCount(args, originalError) {
3941
- const expectedCount = Number.isInteger(args[0]) ? args[0] : 0;
3942
- const opts = args[1] || {};
3943
- const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : self.requestTimeoutMs;
3944
- const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 150;
3945
- const deadline = Date.now() + timeoutMs;
3946
- while (Date.now() < deadline) {
3947
- const tabs = await self._legacyHandlers.getTabs.call(self, []);
3948
- if (tabs.length === expectedCount) return tabs.length;
3949
- await new Promise((resolve) => setTimeout(resolve, pollMs));
3950
- }
3951
- fail(`Legacy waitForTabCount timed out waiting for ${expectedCount}`, originalError);
3952
- },
3953
-
3954
- async waitForTabUrl(args, originalError) {
3955
- const tabIndex = Number.isInteger(args[0]) ? args[0] : 0;
3956
- const opts = args[1] || {};
3957
- const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : self.requestTimeoutMs;
3958
- const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 150;
3959
- const expectIncludes = typeof opts.expectIncludes === 'string' ? opts.expectIncludes : '';
3960
- const allowBlank = Boolean(opts.allowBlank);
3961
- const deadline = Date.now() + timeoutMs;
3962
- while (Date.now() < deadline) {
3963
- const tabs = await self._legacyHandlers.getTabs.call(self, []);
3964
- if (Array.isArray(tabs) && tabs.length > 0) {
3965
- const safeIndex = Math.max(0, Math.min(tabs.length - 1, tabIndex));
3966
- const url = tabs[safeIndex]?.url || '';
3967
- if (allowBlank || url) {
3968
- if (!expectIncludes || url.includes(expectIncludes)) {
3969
- return { index: safeIndex, id: tabs[safeIndex]?.id || tabs[safeIndex]?.targetId, url };
3970
- }
3971
- }
3972
- }
3973
- await new Promise((resolve) => setTimeout(resolve, pollMs));
3974
- }
3975
- fail(`Legacy waitForTabUrl timed out for tab ${tabIndex}`, originalError);
3976
- },
3977
- };
3978
-
3979
- return this.__legacyHandlers;
3980
- }
3981
-
3982
3752
  }
3983
3753
 
3984
3754
  if (!customElements.get('hyper-frame')) {