@absolutejs/beacon 0.4.17 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,31 +8,49 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
 
9
9
  // src/index.ts
10
10
  var BEACON_SIGNAL = {
11
+ AUTH_FAILURE_STORM: "auth_failure_storm",
12
+ BROWSER_INTERVENTION: "browser_intervention",
11
13
  CONSOLE_ERROR: "console_error",
14
+ CSP_VIOLATION: "csp_violation",
15
+ CLIPBOARD_FAILURE: "clipboard_failure",
12
16
  DEAD_CLICK: "dead_click",
13
17
  FETCH_FAILED: "fetch_failed",
14
18
  FOCUS_LOST: "focus_lost",
15
19
  FONT_FAILURE: "font_failure",
16
20
  FORM_FRUSTRATION: "form_frustration",
21
+ FOCUSED_CONTROL_OFFSCREEN: "focused_control_offscreen",
17
22
  HTTP_5XX: "http_5xx",
18
23
  INVISIBLE_TEXT: "invisible_text",
24
+ EMBEDDED_CONTENT_STALLED: "embedded_content_stalled",
19
25
  LAYOUT_OVERFLOW: "layout_overflow",
26
+ MAIN_THREAD_STALL: "main_thread_stall",
27
+ MODAL_FOCUS_ESCAPE: "modal_focus_escape",
20
28
  OCCLUDED_CONTROL: "occluded_control",
21
29
  RAGE_CLICK: "rage_click",
30
+ RATE_LIMITED: "rate_limited",
22
31
  RELOAD_LOOP: "reload_loop",
23
32
  REQUEST_STORM: "request_storm",
24
33
  SCROLL_JAIL: "scroll_jail",
25
34
  SLOW_RESPONSE: "slow_response",
35
+ SOCKET_ABNORMAL_CLOSE: "socket_abnormal_close",
26
36
  SOCKET_FLAPPING: "socket_flapping",
37
+ SSE_FLAPPING: "sse_flapping",
27
38
  STALE_RELEASE: "stale_release",
28
39
  STALLED_STREAM: "stalled_stream",
29
- STUCK_LOADING: "stuck_loading"
40
+ STUCK_LOADING: "stuck_loading",
41
+ THEME_MISMATCH: "theme_mismatch",
42
+ WEBGL_CONTEXT_LOST: "webgl_context_lost",
43
+ SERVICE_WORKER_FAILURE: "service_worker_failure",
44
+ WORKER_FAILURE: "worker_failure"
30
45
  };
31
46
  var BEACON_ATTRIBUTE = {
32
47
  DEAD_CLICK: "data-beacon-dead-click",
33
48
  NAME: "data-beacon-name",
49
+ EMBED: "data-beacon-embed",
50
+ LOADING: "data-beacon-loading",
34
51
  OVERFLOW: "data-beacon-overflow",
35
- SCAN: "data-beacon-scan"
52
+ SCAN: "data-beacon-scan",
53
+ THEME: "data-beacon-theme"
36
54
  };
37
55
  var BEACON_TRACE_HEADER = "x-absolute-trace-id";
38
56
  var inBrowser = () => typeof window !== "undefined";
@@ -197,9 +215,12 @@ var SENSITIVE_KEY_NAMES = new Set([
197
215
  "token"
198
216
  ]);
199
217
  var URL_KEY_NAMES = new Set([
218
+ "blockeduri",
200
219
  "endpoint",
201
220
  "errorfilename",
221
+ "reporturl",
202
222
  "resourceurl",
223
+ "sourcefile",
203
224
  "url"
204
225
  ]);
205
226
  var normalizeFieldName = (key) => key.replace(/[^a-z0-9]/gi, "").toLowerCase();
@@ -540,16 +561,32 @@ var createBeacon = (options) => {
540
561
  const OCCLUSION_COVERAGE_MIN = 0.9;
541
562
  const INVISIBLE_TEXT_SAMPLE_LIMIT = 40;
542
563
  const INVISIBLE_TEXT_CONTRAST_MAX = 1.2;
564
+ const THEME_SURFACE_SAMPLE_LIMIT = 200;
565
+ const THEME_MISMATCH_DEFAULT_MIN_AREA = 1e4;
566
+ const THEME_DARK_SURFACE_LUMINANCE_MAX = 0.12;
567
+ const THEME_LIGHT_SURFACE_LUMINANCE_MIN = 0.85;
543
568
  const STUCK_LOADING_DEFAULT_MS = 20000;
544
569
  const STUCK_LOADING_POLL_MS = 5000;
570
+ const EMBEDDED_CONTENT_STALL_DEFAULT_MS = 15000;
571
+ const WEBGL_RESTORE_GRACE_DEFAULT_MS = 2000;
572
+ const FOCUSED_CONTROL_SETTLE_DEFAULT_MS = 500;
573
+ const KEYBOARD_VIEWPORT_HEIGHT_RATIO_MAX = 0.8;
545
574
  const SCROLL_JAIL_EVENT_COUNT = 8;
546
575
  const SCROLL_JAIL_WINDOW_MS = 2000;
547
576
  const SCROLL_JAIL_BOUNDARY_TOLERANCE_PX = 2;
577
+ const AUTH_FAILURE_STORM_DEFAULT_COUNT = 4;
578
+ const AUTH_FAILURE_STORM_DEFAULT_WINDOW_MS = 30000;
548
579
  const REQUEST_STORM_DEFAULT_COUNT = 15;
549
580
  const REQUEST_STORM_DEFAULT_WINDOW_MS = 1e4;
550
581
  const SOCKET_FLAP_CYCLES = 4;
551
582
  const SOCKET_FLAP_WINDOW_MS = 60000;
583
+ const SSE_FLAP_DEFAULT_COUNT = 4;
584
+ const SSE_FLAP_DEFAULT_WINDOW_MS = 60000;
552
585
  const STALLED_STREAM_DEFAULT_MS = 60000;
586
+ const MODAL_FOCUS_SETTLE_MS = 100;
587
+ const MAIN_THREAD_STALL_DEFAULT_MS = 200;
588
+ const MAIN_THREAD_STALL_DEFAULT_COUNT = 3;
589
+ const MAIN_THREAD_STALL_DEFAULT_WINDOW_MS = 1e4;
553
590
  const RELOAD_LOOP_COUNT = 4;
554
591
  const RELOAD_LOOP_WINDOW_MS = 60000;
555
592
  const RELOAD_LOOP_STORAGE_KEY = "beacon:reload-times";
@@ -788,6 +825,33 @@ var createBeacon = (options) => {
788
825
  const traceId = value?.trim().toLowerCase();
789
826
  return traceId !== undefined && /^[0-9a-f]{32}$/.test(traceId) ? traceId : undefined;
790
827
  };
828
+ const authFailureStormCount = signals?.authFailureStormCount ?? AUTH_FAILURE_STORM_DEFAULT_COUNT;
829
+ const authFailureStormWindowMs = signals?.authFailureStormWindowMs ?? AUTH_FAILURE_STORM_DEFAULT_WINDOW_MS;
830
+ const authFailuresByEndpoint = new Map;
831
+ const reportedAuthFailureStorms = new Set;
832
+ const recordAuthFailure = (endpoint2, method, status) => {
833
+ if (signals === null || signals.authFailureStorms === false)
834
+ return false;
835
+ const label = `${method} ${endpoint2}`;
836
+ const now = Date.now();
837
+ const failures = (authFailuresByEndpoint.get(label) ?? []).filter(({ at }) => now - at < authFailureStormWindowMs);
838
+ failures.push({ at: now, status });
839
+ authFailuresByEndpoint.set(label, failures);
840
+ if (failures.length < authFailureStormCount || reportedAuthFailureStorms.has(label)) {
841
+ return false;
842
+ }
843
+ reportedAuthFailureStorms.add(label);
844
+ const statuses = [...new Set(failures.map((failure) => failure.status))];
845
+ emitSignal(`Authorization failure storm — ${label} repeatedly rejected requests — ${shortUrl(location.href)}`, {
846
+ endpoint: endpoint2,
847
+ failureCount: String(failures.length),
848
+ method,
849
+ signal: BEACON_SIGNAL.AUTH_FAILURE_STORM,
850
+ statuses: statuses.join(","),
851
+ windowMs: String(authFailureStormWindowMs)
852
+ });
853
+ return true;
854
+ };
791
855
  const reportResponseSignal = (url, method, status, durationMs, traceId) => {
792
856
  if (signals === null)
793
857
  return;
@@ -802,6 +866,18 @@ var createBeacon = (options) => {
802
866
  }, traceId);
803
867
  return;
804
868
  }
869
+ if (signals.rateLimits !== false && status === 429) {
870
+ emitSignal(`Rate limited — ${responseMethod} ${responseEndpoint} returned 429`, {
871
+ endpoint: responseEndpoint,
872
+ method: responseMethod,
873
+ signal: BEACON_SIGNAL.RATE_LIMITED,
874
+ status: String(status)
875
+ }, traceId);
876
+ return;
877
+ }
878
+ if ((status === 401 || status === 403) && recordAuthFailure(responseEndpoint, responseMethod, status)) {
879
+ return;
880
+ }
805
881
  if (signals.slowResponses !== false && durationMs > slowResponseMs) {
806
882
  emitSignal(`Slow response — ${responseMethod} ${responseEndpoint}`, {
807
883
  durationMs: String(durationMs),
@@ -988,6 +1064,108 @@ var createBeacon = (options) => {
988
1064
  }, DEAD_CLICK_WINDOW_MS);
989
1065
  };
990
1066
  const clickSignalMessage = (message, control) => `${message} — ${shortUrl(location.href)} — ${describeElement(control)}`;
1067
+ if (signals !== null && signals.cspViolations !== false && typeof document !== "undefined") {
1068
+ const reportedViolations = new Set;
1069
+ const onSecurityPolicyViolation = (event) => {
1070
+ const violation = event;
1071
+ if (violation.disposition !== "enforce")
1072
+ return;
1073
+ const directive = violation.effectiveDirective || violation.violatedDirective || "unknown";
1074
+ const blockedUri = violation.blockedURI || "unknown";
1075
+ const key = `${directive}|${blockedUri}`;
1076
+ if (reportedViolations.has(key))
1077
+ return;
1078
+ reportedViolations.add(key);
1079
+ emitSignal(`CSP violation — ${directive} blocked a resource — ${shortUrl(location.href)}`, {
1080
+ blockedUri,
1081
+ directive,
1082
+ disposition: violation.disposition,
1083
+ signal: BEACON_SIGNAL.CSP_VIOLATION,
1084
+ ...violation.sourceFile === "" ? {} : { sourceFile: violation.sourceFile },
1085
+ ...violation.lineNumber > 0 ? { sourceLine: String(violation.lineNumber) } : {}
1086
+ });
1087
+ };
1088
+ document.addEventListener("securitypolicyviolation", onSecurityPolicyViolation);
1089
+ cleanups.push(() => document.removeEventListener("securitypolicyviolation", onSecurityPolicyViolation));
1090
+ }
1091
+ if (signals !== null && signals.browserInterventions !== false && typeof ReportingObserver !== "undefined") {
1092
+ try {
1093
+ const reportedInterventions = new Set;
1094
+ const observer = new ReportingObserver((reports) => {
1095
+ for (const report of reports) {
1096
+ if (report.type !== "intervention")
1097
+ continue;
1098
+ const body = report.body;
1099
+ const interventionId = typeof body.id === "string" && body.id !== "" ? body.id.slice(0, SIGNAL_TEXT_MAX) : "browser-intervention";
1100
+ const reportUrl = report.url || location.href;
1101
+ const key = `${interventionId}|${shortUrl(reportUrl)}`;
1102
+ if (reportedInterventions.has(key))
1103
+ continue;
1104
+ reportedInterventions.add(key);
1105
+ emitSignal(`Browser intervention — ${interventionId} — ${shortUrl(location.href)}`, {
1106
+ interventionId,
1107
+ reportUrl,
1108
+ signal: BEACON_SIGNAL.BROWSER_INTERVENTION,
1109
+ ...typeof body.sourceFile === "string" ? { sourceFile: body.sourceFile } : {},
1110
+ ...typeof body.lineNumber === "number" ? { sourceLine: String(body.lineNumber) } : {}
1111
+ }, undefined, {
1112
+ ...typeof body.message === "string" ? {
1113
+ interventionMessage: body.message.slice(0, SIGNAL_TEXT_MAX)
1114
+ } : {}
1115
+ });
1116
+ }
1117
+ }, { buffered: true, types: ["intervention"] });
1118
+ observer.observe();
1119
+ cleanups.push(() => observer.disconnect());
1120
+ } catch {}
1121
+ }
1122
+ if (signals !== null && signals.mainThreadStalls !== false && typeof PerformanceObserver !== "undefined") {
1123
+ const stallMs = signals.mainThreadStallMs ?? MAIN_THREAD_STALL_DEFAULT_MS;
1124
+ const stallCount = signals.mainThreadStallCount ?? MAIN_THREAD_STALL_DEFAULT_COUNT;
1125
+ const stallWindowMs = signals.mainThreadStallWindowMs ?? MAIN_THREAD_STALL_DEFAULT_WINDOW_MS;
1126
+ let stallTimes = [];
1127
+ let reported = false;
1128
+ try {
1129
+ const observer = new PerformanceObserver((list) => {
1130
+ if (reported || document.visibilityState === "hidden")
1131
+ return;
1132
+ for (const entry of list.getEntries()) {
1133
+ if (entry.duration < stallMs)
1134
+ continue;
1135
+ const now = Date.now();
1136
+ stallTimes = stallTimes.filter((at) => now - at < stallWindowMs);
1137
+ stallTimes.push(now);
1138
+ if (stallTimes.length < stallCount)
1139
+ continue;
1140
+ reported = true;
1141
+ emitSignal(`Main-thread stall — repeated long frames blocked the page — ${shortUrl(location.href)}`, {
1142
+ durationMs: String(Math.round(entry.duration)),
1143
+ entryType: entry.entryType,
1144
+ signal: BEACON_SIGNAL.MAIN_THREAD_STALL,
1145
+ stallCount: String(stallTimes.length),
1146
+ windowMs: String(stallWindowMs)
1147
+ });
1148
+ break;
1149
+ }
1150
+ });
1151
+ const supportedTypes = PerformanceObserver.supportedEntryTypes;
1152
+ let observing = false;
1153
+ if (supportedTypes?.includes("long-animation-frame")) {
1154
+ observer.observe({ buffered: true, type: "long-animation-frame" });
1155
+ observing = true;
1156
+ } else if (supportedTypes?.includes("longtask")) {
1157
+ observer.observe({ buffered: true, type: "longtask" });
1158
+ observing = true;
1159
+ } else if (supportedTypes === undefined || supportedTypes.length === 0) {
1160
+ observer.observe({ buffered: true, type: "long-animation-frame" });
1161
+ observing = true;
1162
+ } else {
1163
+ observer.disconnect();
1164
+ }
1165
+ if (observing)
1166
+ cleanups.push(() => observer.disconnect());
1167
+ } catch {}
1168
+ }
991
1169
  if (instrument.globalErrors !== false) {
992
1170
  const onError = (event) => {
993
1171
  if (event instanceof ErrorEvent) {
@@ -1075,6 +1253,35 @@ var createBeacon = (options) => {
1075
1253
  });
1076
1254
  }
1077
1255
  }
1256
+ if (signals !== null && signals.clipboardFailures !== false && typeof navigator !== "undefined" && navigator.clipboard !== undefined && typeof navigator.clipboard.writeText === "function") {
1257
+ const clipboard = navigator.clipboard;
1258
+ const originalWriteText = clipboard.writeText;
1259
+ const wrappedWriteText = async (value) => {
1260
+ const target = typeof document !== "undefined" && document.activeElement instanceof Element ? describeElement(document.activeElement) : "unknown";
1261
+ const activation = navigator.userActivation?.isActive ?? false;
1262
+ try {
1263
+ return await originalWriteText.call(clipboard, value);
1264
+ } catch (error) {
1265
+ if (!pageLifecycleEnding && typeof document !== "undefined" && document.visibilityState !== "hidden") {
1266
+ const resolved = toError(error);
1267
+ emitSignal(`Clipboard write failed — ${target} — ${shortUrl(location.href)}`, {
1268
+ errorName: resolved.name,
1269
+ secureContext: String(globalThis.isSecureContext === true),
1270
+ signal: BEACON_SIGNAL.CLIPBOARD_FAILURE,
1271
+ target,
1272
+ userActivation: String(activation)
1273
+ });
1274
+ }
1275
+ throw error;
1276
+ }
1277
+ };
1278
+ try {
1279
+ clipboard.writeText = wrappedWriteText;
1280
+ cleanups.push(() => {
1281
+ clipboard.writeText = originalWriteText;
1282
+ });
1283
+ } catch {}
1284
+ }
1078
1285
  if (instrument.clicks !== false && typeof document !== "undefined") {
1079
1286
  if (signals !== null) {
1080
1287
  const originalWindowOpen = window.open;
@@ -1138,9 +1345,11 @@ var createBeacon = (options) => {
1138
1345
  const detectOcclusion = signals.occludedControls !== false;
1139
1346
  const detectInvisibleText = signals.invisibleText !== false;
1140
1347
  const detectStuckLoading = signals.stuckLoading !== false;
1348
+ const detectThemeMismatch = signals.themeMismatches !== false;
1141
1349
  const overflowSettleMs = signals.layoutOverflowSettleMs ?? LAYOUT_OVERFLOW_SETTLE_DEFAULT_MS;
1142
1350
  const overflowMaxReports = signals.layoutOverflowMaxReports ?? LAYOUT_OVERFLOW_MAX_REPORTS_DEFAULT;
1143
1351
  const stuckLoadingMs = signals.stuckLoadingMs ?? STUCK_LOADING_DEFAULT_MS;
1352
+ const themeMismatchMinArea = signals.themeMismatchMinArea ?? THEME_MISMATCH_DEFAULT_MIN_AREA;
1144
1353
  const seenOverflows = new Set;
1145
1354
  let overflowReports = 0;
1146
1355
  let overflowTimer;
@@ -1441,12 +1650,72 @@ var createBeacon = (options) => {
1441
1650
  });
1442
1651
  }
1443
1652
  };
1653
+ const activeTheme = () => {
1654
+ const root = document.documentElement;
1655
+ const declared = window.getComputedStyle(root).colorScheme.trim();
1656
+ if (declared === "dark")
1657
+ return "dark";
1658
+ if (declared === "light")
1659
+ return "light";
1660
+ const dataTheme = root.getAttribute("data-theme");
1661
+ if (dataTheme === "dark" || dataTheme === "light")
1662
+ return dataTheme;
1663
+ if (root.classList.contains("dark"))
1664
+ return "dark";
1665
+ return null;
1666
+ };
1667
+ const scanForThemeMismatch = () => {
1668
+ const theme = activeTheme();
1669
+ if (theme === null)
1670
+ return;
1671
+ const roots = document.querySelectorAll(`[${BEACON_ATTRIBUTE.THEME}="adaptive"]`);
1672
+ const viewportWidth = document.documentElement.clientWidth;
1673
+ const viewportHeight = document.documentElement.clientHeight;
1674
+ let sampled = 0;
1675
+ for (const root of Array.from(roots)) {
1676
+ const candidates = [root, ...Array.from(root.querySelectorAll("*"))];
1677
+ for (const element of candidates) {
1678
+ if (sampled >= THEME_SURFACE_SAMPLE_LIMIT)
1679
+ return;
1680
+ if (element.closest(`[${BEACON_ATTRIBUTE.THEME}="allow"]`) !== null || isScanExempt(element) || element.matches("canvas, iframe, img, picture, svg, video")) {
1681
+ continue;
1682
+ }
1683
+ const rect = element.getBoundingClientRect();
1684
+ if (rect.width * rect.height < themeMismatchMinArea)
1685
+ continue;
1686
+ if (rect.bottom < 0 || rect.top > viewportHeight || rect.right < 0 || rect.left > viewportWidth) {
1687
+ continue;
1688
+ }
1689
+ const hasContent = (element.textContent ?? "").trim() !== "" || element.querySelector("button, input, select, textarea, [role=button]") !== null;
1690
+ if (!hasContent)
1691
+ continue;
1692
+ const style = window.getComputedStyle(element);
1693
+ if (style.display === "none" || style.visibility === "hidden" || style.backgroundImage !== "none" && style.backgroundImage !== "") {
1694
+ continue;
1695
+ }
1696
+ const surface = parseColor(style.backgroundColor);
1697
+ if (surface === null || surface.a < 0.95)
1698
+ continue;
1699
+ sampled += 1;
1700
+ const luminance = relativeLuminance(surface);
1701
+ const opposite = theme === "dark" ? luminance >= THEME_LIGHT_SURFACE_LUMINANCE_MIN : luminance <= THEME_DARK_SURFACE_LUMINANCE_MAX;
1702
+ if (!opposite)
1703
+ continue;
1704
+ reportScanIssue(element, BEACON_SIGNAL.THEME_MISMATCH, `Theme mismatch — ${describeElement(element)} renders an opposite-polarity surface in ${theme} mode`, {
1705
+ activeTheme: theme,
1706
+ area: String(Math.round(rect.width * rect.height)),
1707
+ surfaceColor: style.backgroundColor,
1708
+ surfaceLuminance: luminance.toFixed(3)
1709
+ });
1710
+ }
1711
+ }
1712
+ };
1444
1713
  const loadingFirstSeen = new WeakMap;
1445
1714
  const reportedStuckLoading = new WeakSet;
1446
1715
  const checkStuckLoading = () => {
1447
1716
  if (document.visibilityState === "hidden")
1448
1717
  return;
1449
- const indicators = document.querySelectorAll('[aria-busy="true"], [role="progressbar"]');
1718
+ const indicators = document.querySelectorAll(`[aria-busy="true"], [role="progressbar"], [${BEACON_ATTRIBUTE.LOADING}]`);
1450
1719
  const now = Date.now();
1451
1720
  for (const indicator of Array.from(indicators)) {
1452
1721
  if (isScanExempt(indicator))
@@ -1473,6 +1742,8 @@ var createBeacon = (options) => {
1473
1742
  scanForOcclusion();
1474
1743
  if (detectInvisibleText)
1475
1744
  scanForInvisibleText();
1745
+ if (detectThemeMismatch)
1746
+ scanForThemeMismatch();
1476
1747
  if (detectStuckLoading)
1477
1748
  checkStuckLoading();
1478
1749
  };
@@ -1492,9 +1763,15 @@ var createBeacon = (options) => {
1492
1763
  cleanups.push(() => window.removeEventListener("load", onLoad));
1493
1764
  }
1494
1765
  window.addEventListener("resize", scheduleOverflowScan);
1766
+ const themeObserver = new MutationObserver(scheduleOverflowScan);
1767
+ themeObserver.observe(document.documentElement, {
1768
+ attributeFilter: ["class", "data-theme", "style"],
1769
+ attributes: true
1770
+ });
1495
1771
  overflowScanOnNavigation = scheduleOverflowScan;
1496
1772
  cleanups.push(() => {
1497
1773
  window.removeEventListener("resize", scheduleOverflowScan);
1774
+ themeObserver.disconnect();
1498
1775
  overflowScanOnNavigation = null;
1499
1776
  if (overflowTimer !== undefined)
1500
1777
  clearTimeout(overflowTimer);
@@ -1505,7 +1782,188 @@ var createBeacon = (options) => {
1505
1782
  cleanups.push(() => clearInterval(stuckTimer));
1506
1783
  }
1507
1784
  }
1785
+ if (signals !== null && signals.embeddedContentStalls !== false && typeof document !== "undefined") {
1786
+ const stallMs = signals.embeddedContentStallMs ?? EMBEDDED_CONTENT_STALL_DEFAULT_MS;
1787
+ const watched = new Map;
1788
+ const stopWatching = (frame) => {
1789
+ const state = watched.get(frame);
1790
+ if (state === undefined)
1791
+ return;
1792
+ clearTimeout(state.timer);
1793
+ frame.removeEventListener("load", state.onLoad);
1794
+ watched.delete(frame);
1795
+ };
1796
+ const watchFrame = (frame) => {
1797
+ stopWatching(frame);
1798
+ const name = frame.getAttribute(BEACON_ATTRIBUTE.EMBED);
1799
+ if (name === null)
1800
+ return;
1801
+ const onLoad = () => stopWatching(frame);
1802
+ const timer2 = setTimeout(() => {
1803
+ stopWatching(frame);
1804
+ if (pageLifecycleEnding || document.visibilityState === "hidden" || !frame.isConnected) {
1805
+ return;
1806
+ }
1807
+ const rect = frame.getBoundingClientRect();
1808
+ if (rect.width === 0 || rect.height === 0)
1809
+ return;
1810
+ const source = frame.getAttribute("src") ?? "";
1811
+ emitSignal(`Embedded content stalled — ${describeElement(frame)} never loaded — ${shortUrl(location.href)}`, {
1812
+ embed: name.slice(0, 64),
1813
+ elapsedMs: String(stallMs),
1814
+ signal: BEACON_SIGNAL.EMBEDDED_CONTENT_STALLED,
1815
+ sourcePath: shortUrl(source),
1816
+ target: describeElement(frame)
1817
+ });
1818
+ }, stallMs);
1819
+ watched.set(frame, { onLoad, timer: timer2 });
1820
+ frame.addEventListener("load", onLoad, { once: true });
1821
+ };
1822
+ const discoverFrames = (root) => {
1823
+ if (root instanceof HTMLIFrameElement && root.hasAttribute(BEACON_ATTRIBUTE.EMBED)) {
1824
+ watchFrame(root);
1825
+ }
1826
+ for (const frame of Array.from(root.querySelectorAll(`iframe[${BEACON_ATTRIBUTE.EMBED}]`))) {
1827
+ watchFrame(frame);
1828
+ }
1829
+ };
1830
+ discoverFrames(document);
1831
+ const observer = new MutationObserver((records) => {
1832
+ for (const record of records) {
1833
+ if (record.type === "attributes") {
1834
+ if (record.target instanceof HTMLIFrameElement) {
1835
+ watchFrame(record.target);
1836
+ }
1837
+ continue;
1838
+ }
1839
+ for (const node of Array.from(record.addedNodes)) {
1840
+ if (node instanceof Element)
1841
+ discoverFrames(node);
1842
+ }
1843
+ for (const node of Array.from(record.removedNodes)) {
1844
+ if (node instanceof HTMLIFrameElement)
1845
+ stopWatching(node);
1846
+ if (node instanceof Element) {
1847
+ for (const frame of Array.from(node.querySelectorAll("iframe"))) {
1848
+ stopWatching(frame);
1849
+ }
1850
+ }
1851
+ }
1852
+ }
1853
+ });
1854
+ observer.observe(document.documentElement, {
1855
+ attributeFilter: [BEACON_ATTRIBUTE.EMBED, "src"],
1856
+ attributes: true,
1857
+ childList: true,
1858
+ subtree: true
1859
+ });
1860
+ cleanups.push(() => {
1861
+ observer.disconnect();
1862
+ for (const frame of Array.from(watched.keys()))
1863
+ stopWatching(frame);
1864
+ });
1865
+ }
1866
+ if (signals !== null && signals.webglContextLosses !== false && typeof document !== "undefined") {
1867
+ const graceMs = signals.webglRestoreGraceMs ?? WEBGL_RESTORE_GRACE_DEFAULT_MS;
1868
+ const pending = new Map;
1869
+ const reported = new WeakSet;
1870
+ const clearPending = (canvas) => {
1871
+ const timer2 = pending.get(canvas);
1872
+ if (timer2 !== undefined)
1873
+ clearTimeout(timer2);
1874
+ pending.delete(canvas);
1875
+ };
1876
+ const onLost = (event) => {
1877
+ if (!(event.target instanceof HTMLCanvasElement))
1878
+ return;
1879
+ const canvas = event.target;
1880
+ clearPending(canvas);
1881
+ const timer2 = setTimeout(() => {
1882
+ pending.delete(canvas);
1883
+ if (reported.has(canvas) || pageLifecycleEnding || document.visibilityState === "hidden" || !canvas.isConnected) {
1884
+ return;
1885
+ }
1886
+ const rect = canvas.getBoundingClientRect();
1887
+ if (rect.width === 0 || rect.height === 0)
1888
+ return;
1889
+ reported.add(canvas);
1890
+ emitSignal(`WebGL context lost — ${describeElement(canvas)} did not restore — ${shortUrl(location.href)}`, {
1891
+ canvasHeight: String(canvas.height),
1892
+ canvasWidth: String(canvas.width),
1893
+ graceMs: String(graceMs),
1894
+ signal: BEACON_SIGNAL.WEBGL_CONTEXT_LOST,
1895
+ target: describeElement(canvas)
1896
+ });
1897
+ }, graceMs);
1898
+ pending.set(canvas, timer2);
1899
+ };
1900
+ const onRestored = (event) => {
1901
+ if (event.target instanceof HTMLCanvasElement)
1902
+ clearPending(event.target);
1903
+ };
1904
+ document.addEventListener("webglcontextlost", onLost, true);
1905
+ document.addEventListener("webglcontextrestored", onRestored, true);
1906
+ cleanups.push(() => {
1907
+ document.removeEventListener("webglcontextlost", onLost, true);
1908
+ document.removeEventListener("webglcontextrestored", onRestored, true);
1909
+ for (const timer2 of pending.values())
1910
+ clearTimeout(timer2);
1911
+ pending.clear();
1912
+ });
1913
+ }
1508
1914
  if (signals !== null && typeof document !== "undefined") {
1915
+ if (signals.focusedControlsOffscreen !== false && window.visualViewport !== undefined && window.visualViewport !== null) {
1916
+ const visualViewport = window.visualViewport;
1917
+ const settleMs = signals.focusedControlSettleMs ?? FOCUSED_CONTROL_SETTLE_DEFAULT_MS;
1918
+ const reported = new Set;
1919
+ let timer2;
1920
+ const checkFocusedControl = () => {
1921
+ timer2 = undefined;
1922
+ if (pageLifecycleEnding || document.visibilityState === "hidden" || visualViewport.height >= window.innerHeight * KEYBOARD_VIEWPORT_HEIGHT_RATIO_MAX) {
1923
+ return;
1924
+ }
1925
+ const active = document.activeElement;
1926
+ const editable = active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement || active instanceof HTMLElement && active.isContentEditable;
1927
+ if (!editable || !(active instanceof HTMLElement))
1928
+ return;
1929
+ const rect = active.getBoundingClientRect();
1930
+ if (rect.width === 0 || rect.height === 0)
1931
+ return;
1932
+ const viewportTop = visualViewport.offsetTop;
1933
+ const viewportBottom = viewportTop + visualViewport.height;
1934
+ const obscuredPx = Math.max(viewportTop - rect.top, rect.bottom - viewportBottom, 0);
1935
+ if (obscuredPx <= 1)
1936
+ return;
1937
+ const target = describeElement(active);
1938
+ const key = target;
1939
+ if (reported.has(key))
1940
+ return;
1941
+ reported.add(key);
1942
+ emitSignal(`Focused control offscreen — ${target} is outside the mobile visual viewport — ${shortUrl(location.href)}`, {
1943
+ layoutViewportHeight: String(window.innerHeight),
1944
+ obscuredPx: String(Math.round(obscuredPx)),
1945
+ signal: BEACON_SIGNAL.FOCUSED_CONTROL_OFFSCREEN,
1946
+ target,
1947
+ visualViewportHeight: String(Math.round(visualViewport.height)),
1948
+ visualViewportOffsetTop: String(Math.round(visualViewport.offsetTop))
1949
+ });
1950
+ };
1951
+ const scheduleCheck = () => {
1952
+ if (timer2 !== undefined)
1953
+ clearTimeout(timer2);
1954
+ timer2 = setTimeout(checkFocusedControl, settleMs);
1955
+ };
1956
+ document.addEventListener("focusin", scheduleCheck, true);
1957
+ visualViewport.addEventListener("resize", scheduleCheck);
1958
+ visualViewport.addEventListener("scroll", scheduleCheck);
1959
+ cleanups.push(() => {
1960
+ document.removeEventListener("focusin", scheduleCheck, true);
1961
+ visualViewport.removeEventListener("resize", scheduleCheck);
1962
+ visualViewport.removeEventListener("scroll", scheduleCheck);
1963
+ if (timer2 !== undefined)
1964
+ clearTimeout(timer2);
1965
+ });
1966
+ }
1509
1967
  if (signals.scrollJail !== false) {
1510
1968
  const nearestScrollable = (start) => {
1511
1969
  let node = start;
@@ -1564,12 +2022,47 @@ var createBeacon = (options) => {
1564
2022
  document.addEventListener("wheel", onWheel, { passive: true });
1565
2023
  cleanups.push(() => document.removeEventListener("wheel", onWheel));
1566
2024
  }
1567
- if (signals.focusLoss !== false) {
2025
+ if (signals.focusLoss !== false || signals.modalFocusEscape !== false) {
1568
2026
  const DIALOG_SELECTOR = '[role="dialog"], [aria-modal="true"], dialog';
2027
+ const MODAL_SELECTOR = '[aria-modal="true"], dialog[open]';
1569
2028
  let lastDialogFocus = null;
1570
2029
  const reportedFocusLoss = new Set;
2030
+ const reportedModalEscapes = new WeakSet;
2031
+ const modalTimers = new Set;
2032
+ const reportModalEscape = (modal, active, reason) => {
2033
+ if (signals.modalFocusEscape === false || reportedModalEscapes.has(modal) || document.visibilityState === "hidden") {
2034
+ return;
2035
+ }
2036
+ reportedModalEscapes.add(modal);
2037
+ const modalDescriptor = describeElement(modal);
2038
+ emitSignal(`Modal focus escape — ${modalDescriptor} did not contain keyboard focus — ${shortUrl(location.href)}`, {
2039
+ modal: modalDescriptor,
2040
+ reason,
2041
+ signal: BEACON_SIGNAL.MODAL_FOCUS_ESCAPE,
2042
+ target: active === null ? "none" : describeElement(active)
2043
+ });
2044
+ };
2045
+ const openModals = () => Array.from(document.querySelectorAll(MODAL_SELECTOR));
2046
+ const checkInitialModalFocus = (modal) => {
2047
+ const timer2 = setTimeout(() => {
2048
+ modalTimers.delete(timer2);
2049
+ if (!modal.isConnected || !modal.matches(MODAL_SELECTOR))
2050
+ return;
2051
+ const active = document.activeElement instanceof Element ? document.activeElement : null;
2052
+ if (active !== null && modal.contains(active))
2053
+ return;
2054
+ reportModalEscape(modal, active, "initial-focus-missing");
2055
+ }, MODAL_FOCUS_SETTLE_MS);
2056
+ modalTimers.add(timer2);
2057
+ };
1571
2058
  const onFocusIn = (event) => {
1572
2059
  const target = event.target;
2060
+ if (signals.modalFocusEscape !== false && target instanceof Element) {
2061
+ const modals = openModals();
2062
+ if (modals.length > 0 && !modals.some((modal) => modal.contains(target))) {
2063
+ reportModalEscape(modals[modals.length - 1], target, "escaped");
2064
+ }
2065
+ }
1573
2066
  lastDialogFocus = target instanceof Element && target.closest(DIALOG_SELECTOR) !== null ? target : null;
1574
2067
  };
1575
2068
  const onFocusOut = () => {
@@ -1590,9 +2083,40 @@ var createBeacon = (options) => {
1590
2083
  };
1591
2084
  document.addEventListener("focusin", onFocusIn, true);
1592
2085
  document.addEventListener("focusout", onFocusOut, true);
2086
+ let modalObserver;
2087
+ if (signals.modalFocusEscape !== false && typeof MutationObserver !== "undefined") {
2088
+ for (const modal of openModals())
2089
+ checkInitialModalFocus(modal);
2090
+ modalObserver = new MutationObserver((records) => {
2091
+ for (const record of records) {
2092
+ if (record.type === "attributes" && record.target instanceof Element && record.target.matches(MODAL_SELECTOR)) {
2093
+ checkInitialModalFocus(record.target);
2094
+ }
2095
+ for (const added of Array.from(record.addedNodes)) {
2096
+ if (!(added instanceof Element))
2097
+ continue;
2098
+ if (added.matches(MODAL_SELECTOR))
2099
+ checkInitialModalFocus(added);
2100
+ for (const modal of Array.from(added.querySelectorAll(MODAL_SELECTOR))) {
2101
+ checkInitialModalFocus(modal);
2102
+ }
2103
+ }
2104
+ }
2105
+ });
2106
+ modalObserver.observe(document.documentElement, {
2107
+ attributeFilter: ["aria-modal", "open"],
2108
+ attributes: true,
2109
+ childList: true,
2110
+ subtree: true
2111
+ });
2112
+ }
1593
2113
  cleanups.push(() => {
1594
2114
  document.removeEventListener("focusin", onFocusIn, true);
1595
2115
  document.removeEventListener("focusout", onFocusOut, true);
2116
+ modalObserver?.disconnect();
2117
+ for (const timer2 of modalTimers)
2118
+ clearTimeout(timer2);
2119
+ modalTimers.clear();
1596
2120
  });
1597
2121
  }
1598
2122
  if (signals.formFrustration !== false) {
@@ -1673,10 +2197,14 @@ var createBeacon = (options) => {
1673
2197
  });
1674
2198
  }
1675
2199
  }
1676
- if (signals !== null && signals.stalledStreams !== false && typeof window.EventSource === "function") {
2200
+ if (signals !== null && (signals.stalledStreams !== false || signals.sseFlapping !== false) && typeof window.EventSource === "function") {
1677
2201
  const stalledStreamMs = signals.stalledStreamMs ?? STALLED_STREAM_DEFAULT_MS;
2202
+ const sseFlapCount = signals.sseFlapCount ?? SSE_FLAP_DEFAULT_COUNT;
2203
+ const sseFlapWindowMs = signals.sseFlapWindowMs ?? SSE_FLAP_DEFAULT_WINDOW_MS;
1678
2204
  const OriginalEventSource = window.EventSource;
1679
2205
  const reportedStreams = new Set;
2206
+ const errorsByEndpoint = new Map;
2207
+ const reportedFlappingStreams = new Set;
1680
2208
  const instrumentSource = (source, endpointLabel) => {
1681
2209
  let stallTimer;
1682
2210
  const disarm = () => {
@@ -1684,6 +2212,8 @@ var createBeacon = (options) => {
1684
2212
  clearTimeout(stallTimer);
1685
2213
  };
1686
2214
  const check = () => {
2215
+ if (signals.stalledStreams === false)
2216
+ return;
1687
2217
  if (source.readyState !== OriginalEventSource.OPEN)
1688
2218
  return;
1689
2219
  if (document.visibilityState === "hidden") {
@@ -1699,8 +2229,30 @@ var createBeacon = (options) => {
1699
2229
  signal: BEACON_SIGNAL.STALLED_STREAM
1700
2230
  });
1701
2231
  };
2232
+ const recordError = () => {
2233
+ disarm();
2234
+ if (signals.sseFlapping === false || pageLifecycleEnding || document.visibilityState === "hidden") {
2235
+ return;
2236
+ }
2237
+ const now = Date.now();
2238
+ const errors = (errorsByEndpoint.get(endpointLabel) ?? []).filter((at) => now - at < sseFlapWindowMs);
2239
+ errors.push(now);
2240
+ errorsByEndpoint.set(endpointLabel, errors);
2241
+ if (errors.length < sseFlapCount || reportedFlappingStreams.has(endpointLabel)) {
2242
+ return;
2243
+ }
2244
+ reportedFlappingStreams.add(endpointLabel);
2245
+ emitSignal(`SSE flapping — ${endpointLabel} keeps failing and reconnecting — ${shortUrl(location.href)}`, {
2246
+ endpoint: endpointLabel,
2247
+ errorCount: String(errors.length),
2248
+ signal: BEACON_SIGNAL.SSE_FLAPPING,
2249
+ windowMs: String(sseFlapWindowMs)
2250
+ });
2251
+ };
1702
2252
  const arm = () => {
1703
2253
  disarm();
2254
+ if (signals.stalledStreams === false)
2255
+ return;
1704
2256
  stallTimer = setTimeout(check, stalledStreamMs);
1705
2257
  };
1706
2258
  const originalAddEventListener = source.addEventListener.bind(source);
@@ -1716,7 +2268,7 @@ var createBeacon = (options) => {
1716
2268
  };
1717
2269
  originalAddEventListener("open", arm);
1718
2270
  originalAddEventListener("message", arm);
1719
- originalAddEventListener("error", disarm);
2271
+ originalAddEventListener("error", recordError);
1720
2272
  const originalClose = source.close.bind(source);
1721
2273
  source.close = () => {
1722
2274
  disarm();
@@ -1738,17 +2290,32 @@ var createBeacon = (options) => {
1738
2290
  }
1739
2291
  });
1740
2292
  }
1741
- if (signals !== null && signals.socketFlapping !== false && typeof window.WebSocket === "function") {
2293
+ if (signals !== null && (signals.socketFlapping !== false || signals.socketAbnormalCloses !== false) && typeof window.WebSocket === "function") {
1742
2294
  const OriginalWebSocket = window.WebSocket;
1743
2295
  const closesByUrl = new Map;
1744
2296
  const reportedSockets = new Set;
2297
+ const reportedAbnormalCloses = new Set;
1745
2298
  const wrappedWebSocket = new Proxy(OriginalWebSocket, {
1746
2299
  construct(target, args) {
1747
2300
  const socket = Reflect.construct(target, args);
1748
2301
  const label = shortUrl(String(args[0]));
1749
- socket.addEventListener("close", () => {
2302
+ socket.addEventListener("close", (event) => {
1750
2303
  if (pageLifecycleEnding)
1751
2304
  return;
2305
+ if (signals.socketAbnormalCloses !== false && typeof CloseEvent !== "undefined" && event instanceof CloseEvent && (!event.wasClean || event.code !== 1000 && event.code !== 1001)) {
2306
+ const abnormalKey = `${label}|${event.code}`;
2307
+ if (!reportedAbnormalCloses.has(abnormalKey)) {
2308
+ reportedAbnormalCloses.add(abnormalKey);
2309
+ emitSignal(`Abnormal socket close — ${label} closed unexpectedly — ${shortUrl(location.href)}`, {
2310
+ closeCode: String(event.code),
2311
+ endpoint: label,
2312
+ signal: BEACON_SIGNAL.SOCKET_ABNORMAL_CLOSE,
2313
+ wasClean: String(event.wasClean)
2314
+ });
2315
+ }
2316
+ }
2317
+ if (signals.socketFlapping === false)
2318
+ return;
1752
2319
  const now = Date.now();
1753
2320
  const closes = (closesByUrl.get(label) ?? []).filter((at) => now - at < SOCKET_FLAP_WINDOW_MS);
1754
2321
  closes.push(now);
@@ -1774,6 +2341,168 @@ var createBeacon = (options) => {
1774
2341
  }
1775
2342
  });
1776
2343
  }
2344
+ if (signals !== null && signals.workerFailures !== false) {
2345
+ const reportedWorkerFailures = new Set;
2346
+ const workerListenerCleanups = [];
2347
+ cleanups.push(() => {
2348
+ for (const cleanup of workerListenerCleanups.splice(0, workerListenerCleanups.length)) {
2349
+ cleanup();
2350
+ }
2351
+ });
2352
+ const reportWorkerFailure = (workerType, endpointLabel, failureKind2, error) => {
2353
+ const key = `${workerType}|${endpointLabel}|${failureKind2}`;
2354
+ if (reportedWorkerFailures.has(key))
2355
+ return;
2356
+ reportedWorkerFailures.add(key);
2357
+ emitSignal(`Worker failure — ${workerType} worker ${endpointLabel} failed — ${shortUrl(location.href)}`, {
2358
+ endpoint: endpointLabel,
2359
+ failureKind: failureKind2,
2360
+ signal: BEACON_SIGNAL.WORKER_FAILURE,
2361
+ workerType
2362
+ }, undefined, error === undefined ? undefined : {
2363
+ workerError: {
2364
+ message: error.message,
2365
+ name: error.name,
2366
+ ...error.stack === undefined ? {} : { stack: error.stack }
2367
+ }
2368
+ });
2369
+ };
2370
+ if (typeof window.Worker === "function") {
2371
+ const OriginalWorker = window.Worker;
2372
+ const wrappedWorker = new Proxy(OriginalWorker, {
2373
+ construct(target, args) {
2374
+ const endpointLabel = shortUrl(String(args[0]));
2375
+ try {
2376
+ const worker = Reflect.construct(target, args);
2377
+ const onError = (event) => {
2378
+ const error = event instanceof ErrorEvent ? errorWithStack("WorkerError", event.message || "Worker runtime error", errorEventLocation(event)) : undefined;
2379
+ reportWorkerFailure("dedicated", endpointLabel, "error", error);
2380
+ };
2381
+ const onMessageError = () => reportWorkerFailure("dedicated", endpointLabel, "messageerror");
2382
+ worker.addEventListener("error", onError);
2383
+ worker.addEventListener("messageerror", onMessageError);
2384
+ workerListenerCleanups.push(() => {
2385
+ worker.removeEventListener("error", onError);
2386
+ worker.removeEventListener("messageerror", onMessageError);
2387
+ });
2388
+ return worker;
2389
+ } catch (error) {
2390
+ reportWorkerFailure("dedicated", endpointLabel, "construction", toError(error));
2391
+ throw error;
2392
+ }
2393
+ }
2394
+ });
2395
+ window.Worker = wrappedWorker;
2396
+ cleanups.push(() => {
2397
+ if (window.Worker === wrappedWorker)
2398
+ window.Worker = OriginalWorker;
2399
+ });
2400
+ }
2401
+ if (typeof window.SharedWorker === "function") {
2402
+ const OriginalSharedWorker = window.SharedWorker;
2403
+ const wrappedSharedWorker = new Proxy(OriginalSharedWorker, {
2404
+ construct(target, args) {
2405
+ const endpointLabel = shortUrl(String(args[0]));
2406
+ try {
2407
+ const worker = Reflect.construct(target, args);
2408
+ const onError = (event) => {
2409
+ const error = event instanceof ErrorEvent ? errorWithStack("WorkerError", event.message || "Shared worker runtime error", errorEventLocation(event)) : undefined;
2410
+ reportWorkerFailure("shared", endpointLabel, "error", error);
2411
+ };
2412
+ const onMessageError = () => reportWorkerFailure("shared", endpointLabel, "messageerror");
2413
+ worker.addEventListener("error", onError);
2414
+ worker.port.addEventListener("messageerror", onMessageError);
2415
+ workerListenerCleanups.push(() => {
2416
+ worker.removeEventListener("error", onError);
2417
+ worker.port.removeEventListener("messageerror", onMessageError);
2418
+ });
2419
+ return worker;
2420
+ } catch (error) {
2421
+ reportWorkerFailure("shared", endpointLabel, "construction", toError(error));
2422
+ throw error;
2423
+ }
2424
+ }
2425
+ });
2426
+ window.SharedWorker = wrappedSharedWorker;
2427
+ cleanups.push(() => {
2428
+ if (window.SharedWorker === wrappedSharedWorker) {
2429
+ window.SharedWorker = OriginalSharedWorker;
2430
+ }
2431
+ });
2432
+ }
2433
+ }
2434
+ if (signals !== null && signals.serviceWorkerFailures !== false && typeof navigator !== "undefined" && "serviceWorker" in navigator) {
2435
+ try {
2436
+ const container = navigator.serviceWorker;
2437
+ const reportedServiceWorkerFailures = new Set;
2438
+ const serviceWorkerListenerCleanups = [];
2439
+ const reportServiceWorkerFailure = (endpointLabel, failureKind2, error) => {
2440
+ const key = `${endpointLabel}|${failureKind2}`;
2441
+ if (reportedServiceWorkerFailures.has(key))
2442
+ return;
2443
+ reportedServiceWorkerFailures.add(key);
2444
+ emitSignal(`Service worker failure — ${endpointLabel} failed during ${failureKind2} — ${shortUrl(location.href)}`, {
2445
+ endpoint: endpointLabel,
2446
+ failureKind: failureKind2,
2447
+ signal: BEACON_SIGNAL.SERVICE_WORKER_FAILURE
2448
+ }, undefined, error === undefined ? undefined : {
2449
+ serviceWorkerError: {
2450
+ message: error.message,
2451
+ name: error.name,
2452
+ ...error.stack === undefined ? {} : { stack: error.stack }
2453
+ }
2454
+ });
2455
+ };
2456
+ const watchInstallingWorker = (worker) => {
2457
+ let activated = worker.state === "activated";
2458
+ const onStateChange = () => {
2459
+ if (worker.state === "activated")
2460
+ activated = true;
2461
+ if (worker.state !== "redundant" || activated)
2462
+ return;
2463
+ reportServiceWorkerFailure(shortUrl(worker.scriptURL), "installation");
2464
+ };
2465
+ worker.addEventListener("statechange", onStateChange);
2466
+ serviceWorkerListenerCleanups.push(() => worker.removeEventListener("statechange", onStateChange));
2467
+ };
2468
+ const watchRegistration = (registration) => {
2469
+ if (registration.installing !== null) {
2470
+ watchInstallingWorker(registration.installing);
2471
+ }
2472
+ const onUpdateFound = () => {
2473
+ if (registration.installing !== null) {
2474
+ watchInstallingWorker(registration.installing);
2475
+ }
2476
+ };
2477
+ registration.addEventListener("updatefound", onUpdateFound);
2478
+ serviceWorkerListenerCleanups.push(() => registration.removeEventListener("updatefound", onUpdateFound));
2479
+ };
2480
+ const originalRegister = container.register;
2481
+ const wrappedRegister = async function(scriptURL, registrationOptions) {
2482
+ const endpointLabel = shortUrl(String(scriptURL));
2483
+ try {
2484
+ const registration = await originalRegister.call(this, scriptURL, registrationOptions);
2485
+ watchRegistration(registration);
2486
+ return registration;
2487
+ } catch (error) {
2488
+ reportServiceWorkerFailure(endpointLabel, "registration", toError(error));
2489
+ throw error;
2490
+ }
2491
+ };
2492
+ container.register = wrappedRegister;
2493
+ const onMessageError = () => reportServiceWorkerFailure("service-worker", "messageerror");
2494
+ container.addEventListener("messageerror", onMessageError);
2495
+ cleanups.push(() => {
2496
+ container.removeEventListener("messageerror", onMessageError);
2497
+ for (const cleanup of serviceWorkerListenerCleanups.splice(0, serviceWorkerListenerCleanups.length)) {
2498
+ cleanup();
2499
+ }
2500
+ if (container.register === wrappedRegister) {
2501
+ container.register = originalRegister;
2502
+ }
2503
+ });
2504
+ } catch {}
2505
+ }
1777
2506
  if (signals !== null && signals.reloadLoops !== false && typeof sessionStorage !== "undefined") {
1778
2507
  try {
1779
2508
  const now = Date.now();
@@ -2036,5 +2765,5 @@ export {
2036
2765
  BEACON_ATTRIBUTE
2037
2766
  };
2038
2767
 
2039
- //# debugId=9933C27D67CFEF2364756E2164756E21
2768
+ //# debugId=317C700390399FC364756E2164756E21
2040
2769
  //# sourceMappingURL=index.js.map