@absolutejs/beacon 0.4.13 → 0.4.15

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
@@ -11,15 +11,28 @@ var BEACON_SIGNAL = {
11
11
  CONSOLE_ERROR: "console_error",
12
12
  DEAD_CLICK: "dead_click",
13
13
  FETCH_FAILED: "fetch_failed",
14
+ FOCUS_LOST: "focus_lost",
15
+ FONT_FAILURE: "font_failure",
16
+ FORM_FRUSTRATION: "form_frustration",
14
17
  HTTP_5XX: "http_5xx",
18
+ INVISIBLE_TEXT: "invisible_text",
15
19
  LAYOUT_OVERFLOW: "layout_overflow",
20
+ OCCLUDED_CONTROL: "occluded_control",
16
21
  RAGE_CLICK: "rage_click",
17
- SLOW_RESPONSE: "slow_response"
22
+ RELOAD_LOOP: "reload_loop",
23
+ REQUEST_STORM: "request_storm",
24
+ SCROLL_JAIL: "scroll_jail",
25
+ SLOW_RESPONSE: "slow_response",
26
+ SOCKET_FLAPPING: "socket_flapping",
27
+ STALE_RELEASE: "stale_release",
28
+ STALLED_STREAM: "stalled_stream",
29
+ STUCK_LOADING: "stuck_loading"
18
30
  };
19
31
  var BEACON_ATTRIBUTE = {
20
32
  DEAD_CLICK: "data-beacon-dead-click",
21
33
  NAME: "data-beacon-name",
22
- OVERFLOW: "data-beacon-overflow"
34
+ OVERFLOW: "data-beacon-overflow",
35
+ SCAN: "data-beacon-scan"
23
36
  };
24
37
  var BEACON_TRACE_HEADER = "x-absolute-trace-id";
25
38
  var inBrowser = () => typeof window !== "undefined";
@@ -353,6 +366,9 @@ var describeElement = (element) => {
353
366
  };
354
367
  var SHORT_URL_MAX = 80;
355
368
  var shortUrl = (url) => {
369
+ try {
370
+ return new URL(url).pathname;
371
+ } catch {}
356
372
  try {
357
373
  return new URL(url, location.origin).pathname;
358
374
  } catch {
@@ -520,6 +536,29 @@ var createBeacon = (options) => {
520
536
  const VIEWPORT_BUCKET_MD_PX = 768;
521
537
  const VIEWPORT_BUCKET_LG_PX = 1024;
522
538
  const VIEWPORT_BUCKET_XL_PX = 1440;
539
+ const OCCLUSION_SAMPLE_LIMIT = 25;
540
+ const OCCLUSION_COVERAGE_MIN = 0.9;
541
+ const INVISIBLE_TEXT_SAMPLE_LIMIT = 40;
542
+ const INVISIBLE_TEXT_CONTRAST_MAX = 1.2;
543
+ const STUCK_LOADING_DEFAULT_MS = 20000;
544
+ const STUCK_LOADING_POLL_MS = 5000;
545
+ const SCROLL_JAIL_EVENT_COUNT = 8;
546
+ const SCROLL_JAIL_WINDOW_MS = 2000;
547
+ const SCROLL_JAIL_BOUNDARY_TOLERANCE_PX = 2;
548
+ const REQUEST_STORM_DEFAULT_COUNT = 15;
549
+ const REQUEST_STORM_DEFAULT_WINDOW_MS = 1e4;
550
+ const SOCKET_FLAP_CYCLES = 4;
551
+ const SOCKET_FLAP_WINDOW_MS = 60000;
552
+ const STALLED_STREAM_DEFAULT_MS = 60000;
553
+ const RELOAD_LOOP_COUNT = 4;
554
+ const RELOAD_LOOP_WINDOW_MS = 60000;
555
+ const RELOAD_LOOP_STORAGE_KEY = "beacon:reload-times";
556
+ const STALE_RELEASE_STORAGE_KEY = "beacon:release-first-seen";
557
+ const STALE_RELEASE_GRACE_MS = 600000;
558
+ const STALE_RELEASE_HISTORY_LIMIT = 5;
559
+ const FORM_FRUSTRATION_THRESHOLD = 3;
560
+ const FORM_FRUSTRATION_WINDOW_MS = 60000;
561
+ const FORM_INVALID_BURST_GAP_MS = 100;
523
562
  const SIGNAL_TEXT_MAX = 180;
524
563
  const slowResponseMs = signals?.slowResponseMs ?? SLOW_RESPONSE_DEFAULT_MS;
525
564
  const navigationResponseMs = Math.max(DEAD_CLICK_WINDOW_MS, signals?.navigationResponseMs ?? NAVIGATION_RESPONSE_DEFAULT_MS);
@@ -529,6 +568,33 @@ var createBeacon = (options) => {
529
568
  let inSignalConsole = false;
530
569
  let pageLifecycleEnding = false;
531
570
  let overflowScanOnNavigation = null;
571
+ let recordRequestForStorm = null;
572
+ const OVERLAY_VIEWPORT_COVERAGE_MIN = 0.9;
573
+ const viewportCoveredByOverlay = () => {
574
+ if (typeof document === "undefined")
575
+ return false;
576
+ if (document.querySelector('[aria-modal="true"], dialog[open]') !== null) {
577
+ return true;
578
+ }
579
+ if (typeof document.elementFromPoint !== "function")
580
+ return false;
581
+ const viewportWidth = document.documentElement.clientWidth;
582
+ const viewportHeight = document.documentElement.clientHeight;
583
+ if (viewportWidth === 0 || viewportHeight === 0)
584
+ return false;
585
+ let node = document.elementFromPoint(viewportWidth / 2, viewportHeight / 2);
586
+ while (node !== null) {
587
+ const style = window.getComputedStyle(node);
588
+ if (style.position === "fixed") {
589
+ const rect = node.getBoundingClientRect();
590
+ const coverage = rect.width * rect.height / (viewportWidth * viewportHeight);
591
+ if (coverage >= OVERLAY_VIEWPORT_COVERAGE_MIN)
592
+ return true;
593
+ }
594
+ node = node.parentElement;
595
+ }
596
+ return false;
597
+ };
532
598
  const vitalsOptions = options.vitals === undefined || options.vitals === false ? null : options.vitals === true ? {} : options.vitals;
533
599
  if (vitalsOptions !== null) {
534
600
  const vitalsEndpoint = vitalsOptions.endpoint ?? "/ingest/vitals";
@@ -1067,9 +1133,14 @@ var createBeacon = (options) => {
1067
1133
  document.addEventListener("click", onClick, true);
1068
1134
  cleanups.push(() => document.removeEventListener("click", onClick, true));
1069
1135
  }
1070
- if (signals !== null && signals.layoutOverflows !== false && typeof document !== "undefined" && typeof window.getComputedStyle === "function") {
1136
+ if (signals !== null && typeof document !== "undefined" && typeof window.getComputedStyle === "function") {
1137
+ const detectOverflow = signals.layoutOverflows !== false;
1138
+ const detectOcclusion = signals.occludedControls !== false;
1139
+ const detectInvisibleText = signals.invisibleText !== false;
1140
+ const detectStuckLoading = signals.stuckLoading !== false;
1071
1141
  const overflowSettleMs = signals.layoutOverflowSettleMs ?? LAYOUT_OVERFLOW_SETTLE_DEFAULT_MS;
1072
1142
  const overflowMaxReports = signals.layoutOverflowMaxReports ?? LAYOUT_OVERFLOW_MAX_REPORTS_DEFAULT;
1143
+ const stuckLoadingMs = signals.stuckLoadingMs ?? STUCK_LOADING_DEFAULT_MS;
1073
1144
  const seenOverflows = new Set;
1074
1145
  let overflowReports = 0;
1075
1146
  let overflowTimer;
@@ -1085,6 +1156,27 @@ var createBeacon = (options) => {
1085
1156
  return "lg";
1086
1157
  return "xl";
1087
1158
  };
1159
+ const isScanExempt = (element) => element.closest(`[${BEACON_ATTRIBUTE.SCAN}="allow"]`) !== null;
1160
+ const seenScanIssues = new Set;
1161
+ let scanIssueReports = 0;
1162
+ const SCAN_ISSUE_MAX_REPORTS = 10;
1163
+ const reportScanIssue = (element, signal, detail, extraTags) => {
1164
+ const bucket = viewportBucket();
1165
+ const key = `${signal}:${describeElement(element)}@${bucket}`;
1166
+ if (seenScanIssues.has(key))
1167
+ return;
1168
+ if (scanIssueReports >= SCAN_ISSUE_MAX_REPORTS)
1169
+ return;
1170
+ seenScanIssues.add(key);
1171
+ scanIssueReports += 1;
1172
+ emitSignal(`${detail} — ${shortUrl(location.href)} [${bucket}]`, {
1173
+ ...extraTags,
1174
+ signal,
1175
+ target: describeElement(element),
1176
+ viewportBucket: bucket,
1177
+ viewportWidth: String(document.documentElement.clientWidth)
1178
+ });
1179
+ };
1088
1180
  const reportOverflow = (element, kind, detail, spillPx) => {
1089
1181
  const bucket = viewportBucket();
1090
1182
  const key = `${kind}:${describeElement(element)}@${bucket}`;
@@ -1148,12 +1240,173 @@ var createBeacon = (options) => {
1148
1240
  };
1149
1241
  visit(body, null);
1150
1242
  };
1243
+ const scanForOcclusion = () => {
1244
+ if (typeof document.elementFromPoint !== "function")
1245
+ return;
1246
+ if (viewportCoveredByOverlay())
1247
+ return;
1248
+ const viewportWidth = document.documentElement.clientWidth;
1249
+ const viewportHeight = document.documentElement.clientHeight;
1250
+ const controls = document.querySelectorAll('a[href], button, input, select, textarea, [role="button"]');
1251
+ let sampled = 0;
1252
+ for (const control of Array.from(controls)) {
1253
+ if (sampled >= OCCLUSION_SAMPLE_LIMIT)
1254
+ return;
1255
+ if (isScanExempt(control))
1256
+ continue;
1257
+ const rect = control.getBoundingClientRect();
1258
+ if (rect.width === 0 || rect.height === 0)
1259
+ continue;
1260
+ if (rect.left < 0 || rect.top < 0 || rect.right > viewportWidth || rect.bottom > viewportHeight) {
1261
+ continue;
1262
+ }
1263
+ sampled += 1;
1264
+ const top = document.elementFromPoint((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
1265
+ if (top === null || top === control || control.contains(top) || top.contains(control)) {
1266
+ continue;
1267
+ }
1268
+ const topRect = top.getBoundingClientRect();
1269
+ const overlapX = Math.min(rect.right, topRect.right) - Math.max(rect.left, topRect.left);
1270
+ const overlapY = Math.min(rect.bottom, topRect.bottom) - Math.max(rect.top, topRect.top);
1271
+ const coverage = Math.max(overlapX, 0) * Math.max(overlapY, 0) / (rect.width * rect.height);
1272
+ if (coverage < OCCLUSION_COVERAGE_MIN)
1273
+ continue;
1274
+ reportScanIssue(control, BEACON_SIGNAL.OCCLUDED_CONTROL, `Occluded control — ${describeElement(control)} is covered by ${describeElement(top)}`, { coveredBy: describeElement(top) });
1275
+ }
1276
+ };
1277
+ const parseColor = (value) => {
1278
+ const match = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[\s,/]+([\d.]+))?\s*\)$/u.exec(value);
1279
+ if (match === null)
1280
+ return null;
1281
+ return {
1282
+ a: match[4] === undefined ? 1 : Number(match[4]),
1283
+ b: Number(match[3]),
1284
+ g: Number(match[2]),
1285
+ r: Number(match[1])
1286
+ };
1287
+ };
1288
+ const channelLuminance = (channel) => {
1289
+ const scaled = channel / 255;
1290
+ return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
1291
+ };
1292
+ const relativeLuminance = (color) => 0.2126 * channelLuminance(color.r) + 0.7152 * channelLuminance(color.g) + 0.0722 * channelLuminance(color.b);
1293
+ const compositeOver = (top, bottom) => {
1294
+ const alpha = top.a + bottom.a * (1 - top.a);
1295
+ if (alpha === 0)
1296
+ return { a: 0, b: 0, g: 0, r: 0 };
1297
+ const blend = (topChannel, bottomChannel) => (topChannel * top.a + bottomChannel * bottom.a * (1 - top.a)) / alpha;
1298
+ return {
1299
+ a: alpha,
1300
+ b: blend(top.b, bottom.b),
1301
+ g: blend(top.g, bottom.g),
1302
+ r: blend(top.r, bottom.r)
1303
+ };
1304
+ };
1305
+ const effectiveBackground = (element) => {
1306
+ let accumulated = null;
1307
+ let node = element;
1308
+ while (node !== null) {
1309
+ const style = window.getComputedStyle(node);
1310
+ if (style.backgroundImage !== "none" && style.backgroundImage !== "") {
1311
+ return null;
1312
+ }
1313
+ const background = parseColor(style.backgroundColor);
1314
+ if (background !== null && background.a > 0) {
1315
+ accumulated = accumulated === null ? background : compositeOver(accumulated, background);
1316
+ if (accumulated.a >= 0.999)
1317
+ return accumulated;
1318
+ }
1319
+ node = node.parentElement;
1320
+ }
1321
+ return null;
1322
+ };
1323
+ const scanForInvisibleText = () => {
1324
+ const viewportWidth = document.documentElement.clientWidth;
1325
+ const viewportHeight = document.documentElement.clientHeight;
1326
+ const candidates = document.querySelectorAll('h1, h2, h3, button, a[href], label, [role="button"]');
1327
+ let sampled = 0;
1328
+ for (const element of Array.from(candidates)) {
1329
+ if (sampled >= INVISIBLE_TEXT_SAMPLE_LIMIT)
1330
+ return;
1331
+ if (isScanExempt(element))
1332
+ continue;
1333
+ if ((element.textContent ?? "").trim() === "")
1334
+ continue;
1335
+ const rect = element.getBoundingClientRect();
1336
+ if (rect.width === 0 || rect.height === 0)
1337
+ continue;
1338
+ if (rect.bottom < 0 || rect.top > viewportHeight || rect.right < 0 || rect.left > viewportWidth) {
1339
+ continue;
1340
+ }
1341
+ const style = window.getComputedStyle(element);
1342
+ if (Number(style.opacity || "1") < 0.1)
1343
+ continue;
1344
+ const foreground = parseColor(style.color);
1345
+ if (foreground === null)
1346
+ continue;
1347
+ sampled += 1;
1348
+ const background = effectiveBackground(element);
1349
+ if (background === null)
1350
+ continue;
1351
+ const transparentText = foreground.a < 0.05;
1352
+ const contrast = (() => {
1353
+ const fgLuminance = relativeLuminance(foreground);
1354
+ const bgLuminance = relativeLuminance(background);
1355
+ const lighter = Math.max(fgLuminance, bgLuminance);
1356
+ const darker = Math.min(fgLuminance, bgLuminance);
1357
+ return (lighter + 0.05) / (darker + 0.05);
1358
+ })();
1359
+ if (!transparentText && contrast > INVISIBLE_TEXT_CONTRAST_MAX) {
1360
+ continue;
1361
+ }
1362
+ reportScanIssue(element, BEACON_SIGNAL.INVISIBLE_TEXT, `Invisible text — ${describeElement(element)} renders (nearly) the same color as its background`, {
1363
+ background: `rgb(${Math.round(background.r)},${Math.round(background.g)},${Math.round(background.b)})`,
1364
+ contrast: contrast.toFixed(2),
1365
+ foreground: style.color
1366
+ });
1367
+ }
1368
+ };
1369
+ const loadingFirstSeen = new WeakMap;
1370
+ const reportedStuckLoading = new WeakSet;
1371
+ const checkStuckLoading = () => {
1372
+ if (document.visibilityState === "hidden")
1373
+ return;
1374
+ const indicators = document.querySelectorAll('[aria-busy="true"], [role="progressbar"]');
1375
+ const now = Date.now();
1376
+ for (const indicator of Array.from(indicators)) {
1377
+ if (isScanExempt(indicator))
1378
+ continue;
1379
+ const rect = indicator.getBoundingClientRect();
1380
+ if (rect.width === 0 && rect.height === 0)
1381
+ continue;
1382
+ const firstSeen = loadingFirstSeen.get(indicator);
1383
+ if (firstSeen === undefined) {
1384
+ loadingFirstSeen.set(indicator, now);
1385
+ continue;
1386
+ }
1387
+ if (now - firstSeen < stuckLoadingMs || reportedStuckLoading.has(indicator)) {
1388
+ continue;
1389
+ }
1390
+ reportedStuckLoading.add(indicator);
1391
+ reportScanIssue(indicator, BEACON_SIGNAL.STUCK_LOADING, `Stuck loading — ${describeElement(indicator)} never resolved`, { visibleMs: String(now - firstSeen) });
1392
+ }
1393
+ };
1394
+ const runSettledScan = () => {
1395
+ if (detectOverflow)
1396
+ scanForOverflow();
1397
+ if (detectOcclusion)
1398
+ scanForOcclusion();
1399
+ if (detectInvisibleText)
1400
+ scanForInvisibleText();
1401
+ if (detectStuckLoading)
1402
+ checkStuckLoading();
1403
+ };
1151
1404
  const scheduleOverflowScan = () => {
1152
1405
  if (overflowTimer !== undefined)
1153
1406
  clearTimeout(overflowTimer);
1154
1407
  overflowTimer = setTimeout(() => {
1155
1408
  overflowTimer = undefined;
1156
- scanForOverflow();
1409
+ runSettledScan();
1157
1410
  }, overflowSettleMs);
1158
1411
  };
1159
1412
  if (document.readyState === "complete") {
@@ -1171,6 +1424,370 @@ var createBeacon = (options) => {
1171
1424
  if (overflowTimer !== undefined)
1172
1425
  clearTimeout(overflowTimer);
1173
1426
  });
1427
+ if (detectStuckLoading) {
1428
+ const stuckTimer = setInterval(checkStuckLoading, STUCK_LOADING_POLL_MS);
1429
+ stuckTimer.unref?.();
1430
+ cleanups.push(() => clearInterval(stuckTimer));
1431
+ }
1432
+ }
1433
+ if (signals !== null && typeof document !== "undefined") {
1434
+ if (signals.scrollJail !== false) {
1435
+ const nearestScrollable = (start) => {
1436
+ let node = start;
1437
+ while (node !== null && node !== document.body) {
1438
+ const style = window.getComputedStyle(node);
1439
+ const overflowY = style.overflowY;
1440
+ if ((overflowY === "auto" || overflowY === "scroll") && node.scrollHeight > node.clientHeight + 1) {
1441
+ return node;
1442
+ }
1443
+ node = node.parentElement;
1444
+ }
1445
+ return null;
1446
+ };
1447
+ let jailBurst = [];
1448
+ let jailScroller = null;
1449
+ const reportedScrollers = new Set;
1450
+ const onWheel = (event) => {
1451
+ if (event.ctrlKey || event.defaultPrevented || event.deltaY === 0) {
1452
+ jailBurst = [];
1453
+ return;
1454
+ }
1455
+ const target = event.target instanceof Element ? event.target : null;
1456
+ const scroller = nearestScrollable(target) ?? document.scrollingElement;
1457
+ if (!(scroller instanceof Element)) {
1458
+ jailBurst = [];
1459
+ return;
1460
+ }
1461
+ const scrollingDown = event.deltaY > 0;
1462
+ const canMove = scrollingDown ? scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - SCROLL_JAIL_BOUNDARY_TOLERANCE_PX : scroller.scrollTop > SCROLL_JAIL_BOUNDARY_TOLERANCE_PX;
1463
+ if (!canMove) {
1464
+ jailBurst = [];
1465
+ return;
1466
+ }
1467
+ const now = Date.now();
1468
+ if (jailScroller !== scroller) {
1469
+ jailScroller = scroller;
1470
+ jailBurst = [];
1471
+ }
1472
+ jailBurst = jailBurst.filter((entry) => now - entry.at < SCROLL_JAIL_WINDOW_MS);
1473
+ jailBurst.push({ at: now, position: scroller.scrollTop });
1474
+ if (jailBurst.length < SCROLL_JAIL_EVENT_COUNT)
1475
+ return;
1476
+ const first = jailBurst[0];
1477
+ const moved = first === undefined || jailBurst.some((entry) => entry.position !== first.position) || scroller.scrollTop !== first.position;
1478
+ jailBurst = [];
1479
+ if (moved)
1480
+ return;
1481
+ if (viewportCoveredByOverlay())
1482
+ return;
1483
+ const descriptor = describeElement(scroller);
1484
+ if (reportedScrollers.has(descriptor))
1485
+ return;
1486
+ reportedScrollers.add(descriptor);
1487
+ emitSignal(`Scroll jail — ${descriptor} has scrollable content but never moves — ${shortUrl(location.href)}`, { signal: BEACON_SIGNAL.SCROLL_JAIL, target: descriptor });
1488
+ };
1489
+ document.addEventListener("wheel", onWheel, { passive: true });
1490
+ cleanups.push(() => document.removeEventListener("wheel", onWheel));
1491
+ }
1492
+ if (signals.focusLoss !== false) {
1493
+ const DIALOG_SELECTOR = '[role="dialog"], [aria-modal="true"], dialog';
1494
+ let lastDialogFocus = null;
1495
+ const reportedFocusLoss = new Set;
1496
+ const onFocusIn = (event) => {
1497
+ const target = event.target;
1498
+ lastDialogFocus = target instanceof Element && target.closest(DIALOG_SELECTOR) !== null ? target : null;
1499
+ };
1500
+ const onFocusOut = () => {
1501
+ const candidate = lastDialogFocus;
1502
+ if (candidate === null)
1503
+ return;
1504
+ setTimeout(() => {
1505
+ const active = document.activeElement;
1506
+ const focusDropped = active === null || active === document.body;
1507
+ if (!focusDropped || candidate.isConnected)
1508
+ return;
1509
+ const descriptor = describeElement(candidate);
1510
+ if (reportedFocusLoss.has(descriptor))
1511
+ return;
1512
+ reportedFocusLoss.add(descriptor);
1513
+ emitSignal(`Focus lost — a dialog closed and dropped keyboard focus on body — ${shortUrl(location.href)}`, { lastFocused: descriptor, signal: BEACON_SIGNAL.FOCUS_LOST });
1514
+ }, 0);
1515
+ };
1516
+ document.addEventListener("focusin", onFocusIn, true);
1517
+ document.addEventListener("focusout", onFocusOut, true);
1518
+ cleanups.push(() => {
1519
+ document.removeEventListener("focusin", onFocusIn, true);
1520
+ document.removeEventListener("focusout", onFocusOut, true);
1521
+ });
1522
+ }
1523
+ if (signals.formFrustration !== false) {
1524
+ const formActivity = new WeakMap;
1525
+ const reportedForms = new WeakSet;
1526
+ const activityFor = (form) => {
1527
+ const existing = formActivity.get(form);
1528
+ if (existing !== undefined)
1529
+ return existing;
1530
+ const created = {
1531
+ identicalSubmits: [],
1532
+ invalidBursts: [],
1533
+ lastData: null,
1534
+ lastInvalidAt: 0
1535
+ };
1536
+ formActivity.set(form, created);
1537
+ return created;
1538
+ };
1539
+ const serializeForm = (form) => {
1540
+ try {
1541
+ return Array.from(new FormData(form).entries()).map(([key, value]) => `${key}=${typeof value === "string" ? value : "file"}`).join("&");
1542
+ } catch {
1543
+ return null;
1544
+ }
1545
+ };
1546
+ const reportForm = (form, reason) => {
1547
+ if (reportedForms.has(form))
1548
+ return;
1549
+ reportedForms.add(form);
1550
+ emitSignal(`Form frustration — ${describeElement(form)} ${reason} — ${shortUrl(location.href)}`, {
1551
+ signal: BEACON_SIGNAL.FORM_FRUSTRATION,
1552
+ target: describeElement(form)
1553
+ });
1554
+ };
1555
+ const onSubmit = (event) => {
1556
+ const form = event.target;
1557
+ if (!(form instanceof HTMLFormElement))
1558
+ return;
1559
+ const data = serializeForm(form);
1560
+ if (data === null)
1561
+ return;
1562
+ const activity = activityFor(form);
1563
+ const now = Date.now();
1564
+ if (data !== activity.lastData) {
1565
+ activity.lastData = data;
1566
+ activity.identicalSubmits = [now];
1567
+ return;
1568
+ }
1569
+ activity.identicalSubmits = activity.identicalSubmits.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
1570
+ activity.identicalSubmits.push(now);
1571
+ if (activity.identicalSubmits.length >= FORM_FRUSTRATION_THRESHOLD) {
1572
+ reportForm(form, "was submitted with identical values repeatedly");
1573
+ }
1574
+ };
1575
+ const onInvalid = (event) => {
1576
+ const control = event.target;
1577
+ const form = control instanceof HTMLInputElement || control instanceof HTMLSelectElement || control instanceof HTMLTextAreaElement ? control.form : null;
1578
+ if (form === null)
1579
+ return;
1580
+ const activity = activityFor(form);
1581
+ const now = Date.now();
1582
+ if (now - activity.lastInvalidAt < FORM_INVALID_BURST_GAP_MS) {
1583
+ activity.lastInvalidAt = now;
1584
+ return;
1585
+ }
1586
+ activity.lastInvalidAt = now;
1587
+ activity.invalidBursts = activity.invalidBursts.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
1588
+ activity.invalidBursts.push(now);
1589
+ if (activity.invalidBursts.length >= FORM_FRUSTRATION_THRESHOLD) {
1590
+ reportForm(form, "keeps failing native validation");
1591
+ }
1592
+ };
1593
+ document.addEventListener("submit", onSubmit, true);
1594
+ document.addEventListener("invalid", onInvalid, true);
1595
+ cleanups.push(() => {
1596
+ document.removeEventListener("submit", onSubmit, true);
1597
+ document.removeEventListener("invalid", onInvalid, true);
1598
+ });
1599
+ }
1600
+ }
1601
+ if (signals !== null && signals.stalledStreams !== false && typeof window.EventSource === "function") {
1602
+ const stalledStreamMs = signals.stalledStreamMs ?? STALLED_STREAM_DEFAULT_MS;
1603
+ const OriginalEventSource = window.EventSource;
1604
+ const reportedStreams = new Set;
1605
+ const instrumentSource = (source, endpointLabel) => {
1606
+ let stallTimer;
1607
+ const disarm = () => {
1608
+ if (stallTimer !== undefined)
1609
+ clearTimeout(stallTimer);
1610
+ };
1611
+ const check = () => {
1612
+ if (source.readyState !== OriginalEventSource.OPEN)
1613
+ return;
1614
+ if (document.visibilityState === "hidden") {
1615
+ arm();
1616
+ return;
1617
+ }
1618
+ if (reportedStreams.has(endpointLabel))
1619
+ return;
1620
+ reportedStreams.add(endpointLabel);
1621
+ emitSignal(`Stalled stream — ${endpointLabel} is open but silent — ${shortUrl(location.href)}`, {
1622
+ endpoint: endpointLabel,
1623
+ quietMs: String(stalledStreamMs),
1624
+ signal: BEACON_SIGNAL.STALLED_STREAM
1625
+ });
1626
+ };
1627
+ const arm = () => {
1628
+ disarm();
1629
+ stallTimer = setTimeout(check, stalledStreamMs);
1630
+ };
1631
+ const originalAddEventListener = source.addEventListener.bind(source);
1632
+ const armedTypes = new Set(["error", "message", "open"]);
1633
+ source.addEventListener = (type, listener, options2) => {
1634
+ if (!armedTypes.has(type)) {
1635
+ armedTypes.add(type);
1636
+ originalAddEventListener(type, arm);
1637
+ }
1638
+ if (listener !== null) {
1639
+ originalAddEventListener(type, listener, options2);
1640
+ }
1641
+ };
1642
+ originalAddEventListener("open", arm);
1643
+ originalAddEventListener("message", arm);
1644
+ originalAddEventListener("error", disarm);
1645
+ const originalClose = source.close.bind(source);
1646
+ source.close = () => {
1647
+ disarm();
1648
+ originalClose();
1649
+ };
1650
+ arm();
1651
+ };
1652
+ const wrappedEventSource = new Proxy(OriginalEventSource, {
1653
+ construct(target, args) {
1654
+ const source = Reflect.construct(target, args);
1655
+ instrumentSource(source, shortUrl(String(args[0])));
1656
+ return source;
1657
+ }
1658
+ });
1659
+ window.EventSource = wrappedEventSource;
1660
+ cleanups.push(() => {
1661
+ if (window.EventSource === wrappedEventSource) {
1662
+ window.EventSource = OriginalEventSource;
1663
+ }
1664
+ });
1665
+ }
1666
+ if (signals !== null && signals.socketFlapping !== false && typeof window.WebSocket === "function") {
1667
+ const OriginalWebSocket = window.WebSocket;
1668
+ const closesByUrl = new Map;
1669
+ const reportedSockets = new Set;
1670
+ const wrappedWebSocket = new Proxy(OriginalWebSocket, {
1671
+ construct(target, args) {
1672
+ const socket = Reflect.construct(target, args);
1673
+ const label = shortUrl(String(args[0]));
1674
+ socket.addEventListener("close", () => {
1675
+ if (pageLifecycleEnding)
1676
+ return;
1677
+ const now = Date.now();
1678
+ const closes = (closesByUrl.get(label) ?? []).filter((at) => now - at < SOCKET_FLAP_WINDOW_MS);
1679
+ closes.push(now);
1680
+ closesByUrl.set(label, closes);
1681
+ if (closes.length < SOCKET_FLAP_CYCLES || reportedSockets.has(label)) {
1682
+ return;
1683
+ }
1684
+ reportedSockets.add(label);
1685
+ emitSignal(`Socket flapping — ${label} keeps connecting and closing — ${shortUrl(location.href)}`, {
1686
+ closeCount: String(closes.length),
1687
+ endpoint: label,
1688
+ signal: BEACON_SIGNAL.SOCKET_FLAPPING,
1689
+ windowMs: String(SOCKET_FLAP_WINDOW_MS)
1690
+ });
1691
+ });
1692
+ return socket;
1693
+ }
1694
+ });
1695
+ window.WebSocket = wrappedWebSocket;
1696
+ cleanups.push(() => {
1697
+ if (window.WebSocket === wrappedWebSocket) {
1698
+ window.WebSocket = OriginalWebSocket;
1699
+ }
1700
+ });
1701
+ }
1702
+ if (signals !== null && signals.reloadLoops !== false && typeof sessionStorage !== "undefined") {
1703
+ try {
1704
+ const now = Date.now();
1705
+ const raw = sessionStorage.getItem(RELOAD_LOOP_STORAGE_KEY);
1706
+ const parsed = raw === null ? [] : JSON.parse(raw);
1707
+ const times = (Array.isArray(parsed) ? parsed : []).filter((at) => typeof at === "number" && now - at < RELOAD_LOOP_WINDOW_MS);
1708
+ times.push(now);
1709
+ sessionStorage.setItem(RELOAD_LOOP_STORAGE_KEY, JSON.stringify(times));
1710
+ if (times.length >= RELOAD_LOOP_COUNT) {
1711
+ emitSignal(`Reload loop — repeated page loads within a minute — ${shortUrl(location.href)}`, {
1712
+ loadCount: String(times.length),
1713
+ signal: BEACON_SIGNAL.RELOAD_LOOP
1714
+ });
1715
+ }
1716
+ } catch {}
1717
+ }
1718
+ if (signals !== null && signals.staleReleases !== false && typeof localStorage !== "undefined" && typeof options.release === "string" && options.release !== "") {
1719
+ try {
1720
+ const currentRelease = options.release;
1721
+ const now = Date.now();
1722
+ const raw = localStorage.getItem(STALE_RELEASE_STORAGE_KEY);
1723
+ const parsed = raw === null ? {} : JSON.parse(raw);
1724
+ const firstSeenByRelease = {};
1725
+ if (parsed !== null && typeof parsed === "object") {
1726
+ for (const [release, at] of Object.entries(parsed)) {
1727
+ if (typeof at === "number")
1728
+ firstSeenByRelease[release] = at;
1729
+ }
1730
+ }
1731
+ const currentFirstSeen = firstSeenByRelease[currentRelease] ?? now;
1732
+ firstSeenByRelease[currentRelease] = currentFirstSeen;
1733
+ const newest = Object.entries(firstSeenByRelease).filter(([release, at]) => release !== currentRelease && at > currentFirstSeen).sort((left, right) => right[1] - left[1])[0];
1734
+ if (newest !== undefined && now - newest[1] > STALE_RELEASE_GRACE_MS) {
1735
+ emitSignal(`Stale release — this page is running a build older than one this browser already saw — ${shortUrl(location.href)}`, {
1736
+ currentRelease,
1737
+ newestRelease: newest[0],
1738
+ signal: BEACON_SIGNAL.STALE_RELEASE
1739
+ });
1740
+ }
1741
+ const trimmed = Object.fromEntries(Object.entries(firstSeenByRelease).sort((left, right) => right[1] - left[1]).slice(0, STALE_RELEASE_HISTORY_LIMIT));
1742
+ localStorage.setItem(STALE_RELEASE_STORAGE_KEY, JSON.stringify(trimmed));
1743
+ } catch {}
1744
+ }
1745
+ if (signals !== null && signals.fontFailures !== false && typeof document !== "undefined" && "fonts" in document) {
1746
+ const reportedFonts = new Set;
1747
+ const sweepFonts = () => {
1748
+ document.fonts.forEach((face) => {
1749
+ if (face.status !== "error" || reportedFonts.has(face.family))
1750
+ return;
1751
+ reportedFonts.add(face.family);
1752
+ emitSignal(`Font failure — ${face.family} failed to load — ${shortUrl(location.href)}`, { fontFamily: face.family, signal: BEACON_SIGNAL.FONT_FAILURE });
1753
+ });
1754
+ };
1755
+ const fontsReady = document.fonts.ready;
1756
+ if (fontsReady !== undefined) {
1757
+ fontsReady.then(sweepFonts).catch(() => {
1758
+ return;
1759
+ });
1760
+ }
1761
+ if (typeof document.fonts.addEventListener === "function") {
1762
+ document.fonts.addEventListener("loadingerror", sweepFonts);
1763
+ cleanups.push(() => document.fonts.removeEventListener("loadingerror", sweepFonts));
1764
+ }
1765
+ }
1766
+ if (signals !== null && signals.requestStorms !== false) {
1767
+ const stormWindowMs = signals.requestStormWindowMs ?? REQUEST_STORM_DEFAULT_WINDOW_MS;
1768
+ const stormCount = signals.requestStormCount ?? REQUEST_STORM_DEFAULT_COUNT;
1769
+ const hitsByEndpoint = new Map;
1770
+ const reportedStorms = new Set;
1771
+ recordRequestForStorm = (url, method) => {
1772
+ const label = `${method.toUpperCase()} ${shortUrl(url)}`;
1773
+ const now = Date.now();
1774
+ const hits = (hitsByEndpoint.get(label) ?? []).filter((at) => now - at < stormWindowMs);
1775
+ hits.push(now);
1776
+ hitsByEndpoint.set(label, hits);
1777
+ if (hits.length < stormCount || reportedStorms.has(label))
1778
+ return;
1779
+ reportedStorms.add(label);
1780
+ emitSignal(`Request storm — ${label} hit repeatedly within seconds — ${shortUrl(location.href)}`, {
1781
+ endpoint: shortUrl(url),
1782
+ method: method.toUpperCase(),
1783
+ requestCount: String(hits.length),
1784
+ signal: BEACON_SIGNAL.REQUEST_STORM,
1785
+ windowMs: String(stormWindowMs)
1786
+ });
1787
+ };
1788
+ cleanups.push(() => {
1789
+ recordRequestForStorm = null;
1790
+ });
1174
1791
  }
1175
1792
  if (instrument.fetch !== false && typeof window.fetch === "function") {
1176
1793
  const originalFetch = window.fetch;
@@ -1182,6 +1799,7 @@ var createBeacon = (options) => {
1182
1799
  return originalFetch(...args);
1183
1800
  const start = Date.now();
1184
1801
  networkRequestCount += 1;
1802
+ recordRequestForStorm?.(url, method);
1185
1803
  try {
1186
1804
  const response = await originalFetch(...args);
1187
1805
  addBreadcrumb({
@@ -1221,6 +1839,7 @@ var createBeacon = (options) => {
1221
1839
  if (request !== undefined && !request.url.includes(endpoint)) {
1222
1840
  const start = Date.now();
1223
1841
  networkRequestCount += 1;
1842
+ recordRequestForStorm?.(request.url, request.method);
1224
1843
  let outcome = "error";
1225
1844
  this.addEventListener("abort", () => {
1226
1845
  outcome = "aborted";
@@ -1342,5 +1961,5 @@ export {
1342
1961
  BEACON_ATTRIBUTE
1343
1962
  };
1344
1963
 
1345
- //# debugId=92E5FD994B7535B364756E2164756E21
1964
+ //# debugId=390F9E7761FF6A1664756E2164756E21
1346
1965
  //# sourceMappingURL=index.js.map