@ansight/capacitor 1.3.0-preview.10 → 1.3.0-preview.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/AnsightCapacitor.podspec +1 -1
  2. package/Package.swift +1 -1
  3. package/README.md +112 -25
  4. package/android/build.gradle +2 -2
  5. package/android/src/main/kotlin/ai/ansight/capacitor/AnsightCapacitorPlugin.kt +21 -0
  6. package/dist/esm/definitions.d.ts +70 -0
  7. package/dist/esm/definitions.d.ts.map +1 -1
  8. package/dist/esm/dom.d.ts +11 -0
  9. package/dist/esm/dom.d.ts.map +1 -1
  10. package/dist/esm/dom.js +69 -14
  11. package/dist/esm/dom.js.map +1 -1
  12. package/dist/esm/index.d.ts +10 -1
  13. package/dist/esm/index.d.ts.map +1 -1
  14. package/dist/esm/index.js +111 -3
  15. package/dist/esm/index.js.map +1 -1
  16. package/dist/esm/network.d.ts +6 -0
  17. package/dist/esm/network.d.ts.map +1 -0
  18. package/dist/esm/network.js +742 -0
  19. package/dist/esm/network.js.map +1 -0
  20. package/dist/esm/options.d.ts +7 -1
  21. package/dist/esm/options.d.ts.map +1 -1
  22. package/dist/esm/options.js +44 -0
  23. package/dist/esm/options.js.map +1 -1
  24. package/dist/esm/session-properties.d.ts +16 -0
  25. package/dist/esm/session-properties.d.ts.map +1 -0
  26. package/dist/esm/session-properties.js +123 -0
  27. package/dist/esm/session-properties.js.map +1 -0
  28. package/dist/esm/standalone-options.d.ts +3 -0
  29. package/dist/esm/standalone-options.d.ts.map +1 -0
  30. package/dist/esm/standalone-options.js +15 -0
  31. package/dist/esm/standalone-options.js.map +1 -0
  32. package/dist/esm/standalone.d.ts.map +1 -1
  33. package/dist/esm/standalone.js +2 -11
  34. package/dist/esm/standalone.js.map +1 -1
  35. package/dist/plugin.cjs.js +1090 -17
  36. package/dist/plugin.cjs.js.map +1 -1
  37. package/dist/plugin.js +1090 -17
  38. package/dist/plugin.js.map +1 -1
  39. package/dist/standalone.js +1093 -20
  40. package/dist/standalone.js.map +1 -1
  41. package/ios/Sources/AnsightCapacitorPlugin/AnsightCapacitorPlugin.swift +28 -0
  42. package/package.json +1 -1
@@ -700,6 +700,19 @@
700
700
  element.id ??
701
701
  undefined)?.trim() || undefined);
702
702
  }
703
+ const tapRoles = new Set([
704
+ "button",
705
+ "checkbox",
706
+ "combobox",
707
+ "link",
708
+ "menuitem",
709
+ "menuitemcheckbox",
710
+ "menuitemradio",
711
+ "option",
712
+ "radio",
713
+ "switch",
714
+ "tab",
715
+ ]);
703
716
  function semanticRole(element) {
704
717
  const declared = element.getAttribute("role")?.trim().toLowerCase();
705
718
  if (declared)
@@ -731,24 +744,54 @@
731
744
  if (!allowActions)
732
745
  return [];
733
746
  const actions = [];
747
+ const htmlElement = element;
748
+ const role = semanticRole(element);
734
749
  if (["A", "BUTTON", "SUMMARY"].includes(element.tagName) ||
735
- element instanceof HTMLInputElement) {
750
+ element instanceof HTMLInputElement ||
751
+ tapRoles.has(role) ||
752
+ element.hasAttribute("onclick") ||
753
+ typeof htmlElement.onclick === "function") {
736
754
  actions.push("tap");
737
755
  }
738
756
  if (element instanceof HTMLInputElement ||
739
757
  element instanceof HTMLTextAreaElement ||
740
- element instanceof HTMLSelectElement) {
758
+ element instanceof HTMLSelectElement ||
759
+ htmlElement.isContentEditable) {
741
760
  actions.push("typeText", "focus");
742
761
  }
743
- else if (element.tabIndex >= 0) {
762
+ else if (htmlElement.tabIndex >= 0) {
744
763
  actions.push("focus");
745
764
  }
746
- if (element.scrollHeight >
747
- element.clientHeight) {
765
+ if (htmlElement.scrollHeight > htmlElement.clientHeight ||
766
+ htmlElement.scrollWidth > htmlElement.clientWidth) {
748
767
  actions.push("scroll", "swipe");
749
768
  }
750
769
  return [...new Set(actions)];
751
770
  }
771
+ function positiveFinite(value) {
772
+ const parsed = Number(value);
773
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
774
+ }
775
+ function createDomCoordinateSpace(browserWindow = typeof window === "undefined"
776
+ ? undefined
777
+ : window, documentElement = typeof document === "undefined"
778
+ ? null
779
+ : document.documentElement) {
780
+ const width = positiveFinite(browserWindow?.innerWidth) ??
781
+ positiveFinite(documentElement?.clientWidth);
782
+ const height = positiveFinite(browserWindow?.innerHeight) ??
783
+ positiveFinite(documentElement?.clientHeight);
784
+ if (width === undefined || height === undefined)
785
+ return undefined;
786
+ return { x: 0, y: 0, width, height, source: "dom.viewport" };
787
+ }
788
+ function normalizeDomAction(action) {
789
+ if (action === "tap")
790
+ return "click";
791
+ if (action === "typeText")
792
+ return "setValue";
793
+ return String(action ?? "");
794
+ }
752
795
  function computedColorToArgbHex(value) {
753
796
  const normalized = value.trim().toLowerCase();
754
797
  if (!normalized)
@@ -913,6 +956,7 @@
913
956
  platform: "web",
914
957
  source: options.source,
915
958
  adapter: "@ansight/capacitor",
959
+ coordinateSpace: createDomCoordinateSpace(),
916
960
  capturedAtUtc: new Date().toISOString(),
917
961
  types: typeRegistry.types,
918
962
  truncated: limits.count >= limits.maxNodes,
@@ -947,6 +991,7 @@
947
991
  platform: "web",
948
992
  source: options.source,
949
993
  adapter: "@ansight/capacitor",
994
+ coordinateSpace: createDomCoordinateSpace(),
950
995
  capturedAtUtc: new Date().toISOString(),
951
996
  types: typeRegistry.types,
952
997
  node,
@@ -985,7 +1030,7 @@
985
1030
  registrations.push(registerTool({
986
1031
  id: "dom.invoke_action",
987
1032
  name: "Invoke DOM action",
988
- description: "Clicks, focuses, blurs, or changes a DOM node.",
1033
+ description: "Taps, focuses, blurs, or enters text in a DOM node.",
989
1034
  category: "UI",
990
1035
  scope: "write",
991
1036
  argumentsSchema: {
@@ -993,7 +1038,10 @@
993
1038
  required: ["nodeId", "action"],
994
1039
  properties: {
995
1040
  nodeId: { type: "string" },
996
- action: { enum: ["click", "focus", "blur", "setValue"] },
1041
+ action: {
1042
+ type: "string",
1043
+ enum: ["tap", "typeText", "click", "focus", "blur", "setValue"],
1044
+ },
997
1045
  value: { type: "string" },
998
1046
  },
999
1047
  },
@@ -1010,17 +1058,24 @@
1010
1058
  errorCode: "dom_node_not_found",
1011
1059
  };
1012
1060
  }
1013
- if (action === "click")
1061
+ const normalizedAction = normalizeDomAction(action);
1062
+ if (normalizedAction === "click")
1014
1063
  element.click();
1015
- else if (action === "focus")
1064
+ else if (normalizedAction === "focus")
1016
1065
  element.focus();
1017
- else if (action === "blur")
1066
+ else if (normalizedAction === "blur")
1018
1067
  element.blur();
1019
- else if (action === "setValue" &&
1068
+ else if (normalizedAction === "setValue" &&
1020
1069
  (element instanceof HTMLInputElement ||
1021
1070
  element instanceof HTMLTextAreaElement ||
1022
- element instanceof HTMLSelectElement)) {
1023
- element.value = value ?? "";
1071
+ element instanceof HTMLSelectElement ||
1072
+ element.isContentEditable)) {
1073
+ if (element.isContentEditable) {
1074
+ element.textContent = value ?? "";
1075
+ }
1076
+ else {
1077
+ element.value = value ?? "";
1078
+ }
1024
1079
  element.dispatchEvent(new Event("input", { bubbles: true }));
1025
1080
  element.dispatchEvent(new Event("change", { bubbles: true }));
1026
1081
  }
@@ -1031,7 +1086,7 @@
1031
1086
  errorCode: "dom_action_unsupported",
1032
1087
  };
1033
1088
  }
1034
- return successful({ nodeId: id, action }, `DOM action '${action}' invoked.`);
1089
+ return successful({ nodeId: id, action, performedAction: normalizedAction }, `DOM action '${action}' invoked.`);
1035
1090
  }));
1036
1091
  }
1037
1092
  return {
@@ -1203,6 +1258,50 @@
1203
1258
  };
1204
1259
  return this;
1205
1260
  }
1261
+ withNetworkCapture(options = {}) {
1262
+ this.options.networkCapture = { ...options };
1263
+ return this;
1264
+ }
1265
+ withNetworkRequestBodies(maximumBodyBytes) {
1266
+ if (typeof this.options.networkCapture !== "object")
1267
+ return this;
1268
+ const current = this.options.networkCapture;
1269
+ this.options.networkCapture = {
1270
+ ...current,
1271
+ captureRequestBody: true,
1272
+ ...(maximumBodyBytes == null ? {} : { maximumBodyBytes }),
1273
+ };
1274
+ return this;
1275
+ }
1276
+ withoutNetworkRequestBodies() {
1277
+ if (typeof this.options.networkCapture !== "object")
1278
+ return this;
1279
+ const current = this.options.networkCapture;
1280
+ this.options.networkCapture = { ...current, captureRequestBody: false };
1281
+ return this;
1282
+ }
1283
+ withNetworkResponseBodies(maximumBodyBytes) {
1284
+ if (typeof this.options.networkCapture !== "object")
1285
+ return this;
1286
+ const current = this.options.networkCapture;
1287
+ this.options.networkCapture = {
1288
+ ...current,
1289
+ captureResponseBody: true,
1290
+ ...(maximumBodyBytes == null ? {} : { maximumBodyBytes }),
1291
+ };
1292
+ return this;
1293
+ }
1294
+ withoutNetworkResponseBodies() {
1295
+ if (typeof this.options.networkCapture !== "object")
1296
+ return this;
1297
+ const current = this.options.networkCapture;
1298
+ this.options.networkCapture = { ...current, captureResponseBody: false };
1299
+ return this;
1300
+ }
1301
+ withoutNetworkCapture() {
1302
+ this.options.networkCapture = false;
1303
+ return this;
1304
+ }
1206
1305
  withToolGuard(toolGuard) {
1207
1306
  this.options.toolGuard = toolGuard;
1208
1307
  return this;
@@ -1370,6 +1469,871 @@
1370
1469
  return new AnsightOptionsBuilder(options);
1371
1470
  }
1372
1471
 
1472
+ const networkRequestSchema = "ansight.network-request.v1";
1473
+ const redactedNetworkValue = "<redacted>";
1474
+ const maximumHeaderCount = 128;
1475
+ const maximumHeaderValueLength = 4096;
1476
+ const maximumErrorMessageLength = 4096;
1477
+ const maximumUrlLength = 16384;
1478
+ const defaultMaximumBodyBytes = 64 * 1024;
1479
+ const sensitiveHeaderNames = new Set([
1480
+ "authorization",
1481
+ "cookie",
1482
+ "proxy-authorization",
1483
+ "set-cookie",
1484
+ "x-api-key",
1485
+ "x-auth-token",
1486
+ ]);
1487
+ const sensitiveQueryNames = new Set([
1488
+ "access_token",
1489
+ "accesskey",
1490
+ "access_key",
1491
+ "api_key",
1492
+ "apikey",
1493
+ "auth",
1494
+ "authorization",
1495
+ "client_secret",
1496
+ "code",
1497
+ "credential",
1498
+ "credentials",
1499
+ "id_token",
1500
+ "jwt",
1501
+ "key",
1502
+ "password",
1503
+ "passwd",
1504
+ "refresh_token",
1505
+ "sas",
1506
+ "sastoken",
1507
+ "secret",
1508
+ "secret_key",
1509
+ "security_token",
1510
+ "session_token",
1511
+ "sig",
1512
+ "signature",
1513
+ "token",
1514
+ ]);
1515
+ const azureSasFingerprintNames = new Set([
1516
+ "se",
1517
+ "skoid",
1518
+ "sp",
1519
+ "sr",
1520
+ "srt",
1521
+ "ss",
1522
+ "sv",
1523
+ ]);
1524
+ const azureSasQueryNames = new Set([
1525
+ "epk",
1526
+ "erk",
1527
+ "rscc",
1528
+ "rscd",
1529
+ "rsce",
1530
+ "rscl",
1531
+ "rsct",
1532
+ "saoid",
1533
+ "scid",
1534
+ "se",
1535
+ "sig",
1536
+ "si",
1537
+ "sip",
1538
+ "ske",
1539
+ "skoid",
1540
+ "sks",
1541
+ "skt",
1542
+ "sktid",
1543
+ "skv",
1544
+ "snapshot",
1545
+ "sp",
1546
+ "spk",
1547
+ "spr",
1548
+ "sr",
1549
+ "srk",
1550
+ "srt",
1551
+ "ss",
1552
+ "st",
1553
+ "suoid",
1554
+ "tn",
1555
+ "versionid",
1556
+ "sv",
1557
+ ]);
1558
+ function truncate(value, maximumLength) {
1559
+ const text = String(value);
1560
+ return text.length <= maximumLength
1561
+ ? text
1562
+ : `${text.slice(0, maximumLength)}…`;
1563
+ }
1564
+ function normalizeRequired(value, fallback, maximumLength) {
1565
+ const normalized = value == null ? "" : String(value).trim();
1566
+ return truncate(normalized || fallback, maximumLength);
1567
+ }
1568
+ function normalizeOptional(value, maximumLength) {
1569
+ if (value == null)
1570
+ return undefined;
1571
+ const normalized = String(value).trim();
1572
+ return normalized ? truncate(normalized, maximumLength) : undefined;
1573
+ }
1574
+ function lowercaseSet(values) {
1575
+ return new Set((values ?? []).map((value) => value.toLowerCase()));
1576
+ }
1577
+ function isSensitiveHeader(name, options) {
1578
+ const lowered = name.toLowerCase();
1579
+ if (sensitiveHeaderNames.has(lowered) ||
1580
+ lowercaseSet(options.additionalSensitiveHeaderNames).has(lowered)) {
1581
+ return true;
1582
+ }
1583
+ const compact = lowered.replaceAll("-", "");
1584
+ return (compact.includes("token") ||
1585
+ compact.includes("secret") ||
1586
+ compact.includes("apikey"));
1587
+ }
1588
+ function headerEntries(headers) {
1589
+ if (!headers)
1590
+ return [];
1591
+ if (Array.isArray(headers)) {
1592
+ return headers.flatMap((header) => {
1593
+ if (Array.isArray(header))
1594
+ return [[header[0], header[1]]];
1595
+ if (header && typeof header === "object") {
1596
+ const value = header;
1597
+ return [[value.name, value.value]];
1598
+ }
1599
+ return [];
1600
+ });
1601
+ }
1602
+ if (typeof headers.forEach === "function") {
1603
+ const entries = [];
1604
+ headers.forEach((value, name) => entries.push([name, value]));
1605
+ return entries;
1606
+ }
1607
+ return typeof headers === "object" ? Object.entries(headers) : [];
1608
+ }
1609
+ function sanitizeHeaders(headers, options) {
1610
+ return headerEntries(headers)
1611
+ .filter(([name]) => name != null && String(name).trim())
1612
+ .slice(0, maximumHeaderCount)
1613
+ .map(([rawName, rawValue]) => {
1614
+ const name = normalizeRequired(rawName, "Header", 256);
1615
+ return {
1616
+ name,
1617
+ value: isSensitiveHeader(name, options)
1618
+ ? redactedNetworkValue
1619
+ : normalizeRequired(rawValue, "", maximumHeaderValueLength),
1620
+ };
1621
+ });
1622
+ }
1623
+ function sanitizeQuery(query, options) {
1624
+ const appSensitive = lowercaseSet(options.additionalSensitiveQueryParameterNames);
1625
+ const pairs = query.split("&");
1626
+ const decodedNames = new Set(pairs.map((pair) => decodeQueryName(pair).toLowerCase()));
1627
+ const hasAzureSas = decodedNames.has("sig") &&
1628
+ [...azureSasFingerprintNames].some((name) => decodedNames.has(name));
1629
+ const hasAwsSignature = decodedNames.has("x-amz-signature");
1630
+ const hasGoogleSignature = decodedNames.has("x-goog-signature");
1631
+ const hasCloudFrontSignature = decodedNames.has("signature") &&
1632
+ ["key-pair-id", "policy", "expires"].some((name) => decodedNames.has(name));
1633
+ const hasLegacyGoogleSignature = decodedNames.has("signature") && decodedNames.has("googleaccessid");
1634
+ const hasAlibabaSignature = (decodedNames.has("signature") && decodedNames.has("ossaccesskeyid")) ||
1635
+ decodedNames.has("x-oss-signature");
1636
+ return pairs
1637
+ .map((pair) => {
1638
+ const equalsIndex = pair.indexOf("=");
1639
+ const encodedName = equalsIndex < 0 ? pair : pair.slice(0, equalsIndex);
1640
+ const decodedName = decodeQueryName(pair);
1641
+ const lowered = decodedName.toLowerCase();
1642
+ const providerSensitive = (hasAzureSas && azureSasQueryNames.has(lowered)) ||
1643
+ (hasAwsSignature && lowered.startsWith("x-amz-")) ||
1644
+ (hasGoogleSignature && lowered.startsWith("x-goog-")) ||
1645
+ (hasCloudFrontSignature &&
1646
+ [
1647
+ "signature",
1648
+ "key-pair-id",
1649
+ "policy",
1650
+ "expires",
1651
+ "hash-algorithm",
1652
+ ].includes(lowered)) ||
1653
+ (hasLegacyGoogleSignature &&
1654
+ ["signature", "googleaccessid", "expires"].includes(lowered)) ||
1655
+ (hasAlibabaSignature &&
1656
+ (lowered.startsWith("x-oss-") ||
1657
+ ["signature", "ossaccesskeyid", "security-token"].includes(lowered)));
1658
+ return providerSensitive ||
1659
+ sensitiveQueryNames.has(lowered) ||
1660
+ appSensitive.has(lowered)
1661
+ ? `${encodedName}=${encodeURIComponent(redactedNetworkValue)}`
1662
+ : pair;
1663
+ })
1664
+ .join("&");
1665
+ }
1666
+ function decodeQueryName(pair) {
1667
+ const equalsIndex = pair.indexOf("=");
1668
+ const encodedName = equalsIndex < 0 ? pair : pair.slice(0, equalsIndex);
1669
+ try {
1670
+ return decodeURIComponent(encodedName.replaceAll("+", " "));
1671
+ }
1672
+ catch {
1673
+ return encodedName;
1674
+ }
1675
+ }
1676
+ function sanitizeUrl(value, options) {
1677
+ let normalized = normalizeRequired(value, "<unknown>", maximumUrlLength);
1678
+ normalized = normalized.replace(/^(https?:\/\/)[^/@]+@/i, `$1${redactedNetworkValue}@`);
1679
+ const queryIndex = normalized.indexOf("?");
1680
+ if (queryIndex < 0)
1681
+ return truncate(normalized, maximumUrlLength);
1682
+ const fragmentIndex = normalized.indexOf("#", queryIndex);
1683
+ if (options.includeQueryString === false) {
1684
+ return truncate(normalized.slice(0, queryIndex) +
1685
+ (fragmentIndex < 0 ? "" : normalized.slice(fragmentIndex)), maximumUrlLength);
1686
+ }
1687
+ const queryEnd = fragmentIndex < 0 ? normalized.length : fragmentIndex;
1688
+ return truncate(normalized.slice(0, queryIndex + 1) +
1689
+ sanitizeQuery(normalized.slice(queryIndex + 1, queryEnd), options) +
1690
+ (fragmentIndex < 0 ? "" : normalized.slice(fragmentIndex)), maximumUrlLength);
1691
+ }
1692
+ function sanitizeErrorMessage(value, options) {
1693
+ const normalized = normalizeOptional(value, maximumErrorMessageLength);
1694
+ if (!normalized)
1695
+ return undefined;
1696
+ return truncate(normalized
1697
+ .replace(/(access_token|api_key|apikey|auth|authorization|code|key|password|passwd|secret|signature|token)(\s*=\s*)([^&\s,;]+)/gi, `$1$2${redactedNetworkValue}`)
1698
+ .replace(/https?:\/\/[^\s"'<>]+/gi, (url) => sanitizeUrl(url, options)), maximumErrorMessageLength);
1699
+ }
1700
+ function normalizeTimestamp(value, fallback) {
1701
+ const date = new Date(value == null ? fallback : String(value));
1702
+ return Number.isFinite(date.valueOf()) ? date.toISOString() : fallback;
1703
+ }
1704
+ function generateId(globalObject) {
1705
+ if (typeof globalObject.crypto?.randomUUID === "function") {
1706
+ return globalObject.crypto.randomUUID().replaceAll("-", "");
1707
+ }
1708
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1709
+ }
1710
+ function normalizeSize(value) {
1711
+ const number = Number(value);
1712
+ return Number.isFinite(number) && number >= 0
1713
+ ? Math.round(number)
1714
+ : undefined;
1715
+ }
1716
+ function maximumBodyBytes(options) {
1717
+ const configured = Number(options.maximumBodyBytes);
1718
+ const value = Number.isFinite(configured)
1719
+ ? Math.round(configured)
1720
+ : defaultMaximumBodyBytes;
1721
+ return Math.max(0, value);
1722
+ }
1723
+ function sanitizeSensitiveText(value, options) {
1724
+ return value
1725
+ .replace(/(access_token|accesskey|access_key|api_key|apikey|auth|authorization|client_secret|code|credential|credentials|id_token|jwt|key|password|passwd|refresh_token|sas|sastoken|secret|secret_key|security_token|session_token|sig|signature|token)(["']?\s*[:=]\s*["']?)([^&\s,;}"']+)/gi, `$1$2${redactedNetworkValue}`)
1726
+ .replace(/https?:\/\/[^\s"'<>]+/gi, (url) => sanitizeUrl(url, options));
1727
+ }
1728
+ function truncateUtf8(bytes, maximum) {
1729
+ let length = Math.min(bytes.length, maximum);
1730
+ const decoder = new TextDecoder("utf-8", { fatal: true });
1731
+ while (length > 0) {
1732
+ try {
1733
+ decoder.decode(bytes.slice(0, length));
1734
+ return bytes.slice(0, length);
1735
+ }
1736
+ catch {
1737
+ length -= 1;
1738
+ }
1739
+ }
1740
+ return new Uint8Array();
1741
+ }
1742
+ function bytesToBase64$1(bytes) {
1743
+ let binary = "";
1744
+ for (const byte of bytes)
1745
+ binary += String.fromCharCode(byte);
1746
+ return btoa(binary);
1747
+ }
1748
+ function base64ToBytes(value) {
1749
+ const binary = atob(value);
1750
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
1751
+ }
1752
+ function normalizeBody(body, options) {
1753
+ const maximum = maximumBodyBytes(options);
1754
+ if (!body || maximum <= 0)
1755
+ return undefined;
1756
+ const encoding = body.encoding?.toLowerCase();
1757
+ let bytes;
1758
+ try {
1759
+ if (encoding === "utf8") {
1760
+ bytes = new TextEncoder().encode(sanitizeSensitiveText(body.data, options));
1761
+ }
1762
+ else if (encoding === "base64" && options.captureBinaryBodies === true) {
1763
+ bytes = base64ToBytes(body.data);
1764
+ }
1765
+ else {
1766
+ return undefined;
1767
+ }
1768
+ }
1769
+ catch {
1770
+ return undefined;
1771
+ }
1772
+ const originalLength = bytes.length;
1773
+ const captured = encoding === "utf8"
1774
+ ? truncateUtf8(bytes, maximum)
1775
+ : bytes.slice(0, maximum);
1776
+ const totalBytes = normalizeSize(body.totalBytes);
1777
+ return {
1778
+ contentType: normalizeOptional(body.contentType, 512),
1779
+ encoding,
1780
+ data: encoding === "base64"
1781
+ ? bytesToBase64$1(captured)
1782
+ : new TextDecoder().decode(captured),
1783
+ capturedBytes: captured.length,
1784
+ totalBytes,
1785
+ truncated: body.truncated ||
1786
+ originalLength > captured.length ||
1787
+ (totalBytes != null && totalBytes > captured.length),
1788
+ };
1789
+ }
1790
+ function normalizeRecord(input, options, globalObject) {
1791
+ const now = new Date().toISOString();
1792
+ const startedAtUtc = normalizeTimestamp(input.startedAtUtc, now);
1793
+ const completedAtUtc = normalizeTimestamp(input.completedAtUtc, startedAtUtc);
1794
+ const duration = Number(input.durationMilliseconds);
1795
+ return {
1796
+ schema: networkRequestSchema,
1797
+ id: normalizeRequired(input.id, generateId(globalObject), 128),
1798
+ source: normalizeRequired(input.source, "unknown", 128),
1799
+ startedAtUtc,
1800
+ completedAtUtc: completedAtUtc < startedAtUtc ? startedAtUtc : completedAtUtc,
1801
+ durationMilliseconds: Number.isFinite(duration) && duration >= 0 ? duration : 0,
1802
+ method: normalizeRequired(input.method, "GET", 32).toUpperCase(),
1803
+ url: sanitizeUrl(input.url, options),
1804
+ protocol: normalizeOptional(input.protocol, 64),
1805
+ requestHeaders: options.includeRequestHeaders === false
1806
+ ? []
1807
+ : sanitizeHeaders(input.requestHeaders, options),
1808
+ requestBodySizeBytes: options.includeBodySizes === false
1809
+ ? undefined
1810
+ : normalizeSize(input.requestBodySizeBytes),
1811
+ requestBody: options.captureRequestBody !== false
1812
+ ? normalizeBody(input.requestBody, options)
1813
+ : undefined,
1814
+ statusCode: Number.isInteger(Number(input.statusCode)) &&
1815
+ Number(input.statusCode) >= 100 &&
1816
+ Number(input.statusCode) <= 999
1817
+ ? Number(input.statusCode)
1818
+ : undefined,
1819
+ reasonPhrase: normalizeOptional(input.reasonPhrase, 512),
1820
+ responseHeaders: options.includeResponseHeaders === false
1821
+ ? []
1822
+ : sanitizeHeaders(input.responseHeaders, options),
1823
+ responseBodySizeBytes: options.includeBodySizes === false
1824
+ ? undefined
1825
+ : normalizeSize(input.responseBodySizeBytes),
1826
+ responseBody: options.captureResponseBody !== false
1827
+ ? normalizeBody(input.responseBody, options)
1828
+ : undefined,
1829
+ errorType: normalizeOptional(input.errorType, 512),
1830
+ errorMessage: sanitizeErrorMessage(input.errorMessage, options),
1831
+ };
1832
+ }
1833
+ function sanitizeNetworkRequest(input, options = {}, globalObject = globalThis) {
1834
+ try {
1835
+ let normalized = normalizeRecord(input, options, globalObject);
1836
+ if (options.urlSanitizer) {
1837
+ normalized = normalizeRecord({ ...normalized, url: options.urlSanitizer(normalized.url) }, options, globalObject);
1838
+ }
1839
+ if (options.requestSanitizer) {
1840
+ const transformed = options.requestSanitizer(normalized);
1841
+ if (transformed == null)
1842
+ return null;
1843
+ normalized = normalizeRecord(transformed, options, globalObject);
1844
+ }
1845
+ return normalized;
1846
+ }
1847
+ catch {
1848
+ return null;
1849
+ }
1850
+ }
1851
+ function parseContentLength(headers) {
1852
+ const entry = headerEntries(headers).find(([name]) => String(name).toLowerCase() === "content-length");
1853
+ return entry ? normalizeSize(entry[1]) : undefined;
1854
+ }
1855
+ function headerValue(headers, wantedName) {
1856
+ const entry = headerEntries(headers).find(([name]) => String(name).toLowerCase() === wantedName);
1857
+ return entry == null ? undefined : String(entry[1]);
1858
+ }
1859
+ function isTextContentType(contentType) {
1860
+ if (!contentType)
1861
+ return true;
1862
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
1863
+ return (mediaType.startsWith("text/") ||
1864
+ mediaType.endsWith("+json") ||
1865
+ mediaType.endsWith("+xml") ||
1866
+ [
1867
+ "application/json",
1868
+ "application/xml",
1869
+ "application/graphql",
1870
+ "application/javascript",
1871
+ "application/x-www-form-urlencoded",
1872
+ ].includes(mediaType));
1873
+ }
1874
+ function bodyFromBytes(bytes, totalBytes, contentType, options) {
1875
+ const binary = !isTextContentType(contentType);
1876
+ if (binary && options.captureBinaryBodies !== true)
1877
+ return undefined;
1878
+ const maximum = maximumBodyBytes(options);
1879
+ if (maximum <= 0)
1880
+ return undefined;
1881
+ const captured = binary
1882
+ ? bytes.slice(0, maximum)
1883
+ : truncateUtf8(bytes, maximum);
1884
+ return {
1885
+ contentType,
1886
+ encoding: binary ? "base64" : "utf8",
1887
+ data: binary ? bytesToBase64$1(captured) : new TextDecoder().decode(captured),
1888
+ capturedBytes: captured.length,
1889
+ totalBytes,
1890
+ truncated: bytes.length > captured.length ||
1891
+ (totalBytes != null && totalBytes > captured.length),
1892
+ };
1893
+ }
1894
+ function bodyFromValue(value, headers, options) {
1895
+ if (value == null || options.captureRequestBody === false)
1896
+ return undefined;
1897
+ const contentType = headerValue(headers, "content-type");
1898
+ if (typeof value === "string" || value instanceof URLSearchParams) {
1899
+ const bytes = new TextEncoder().encode(String(value));
1900
+ return bodyFromBytes(bytes, bytes.length, contentType ||
1901
+ (value instanceof URLSearchParams
1902
+ ? "application/x-www-form-urlencoded"
1903
+ : undefined), options);
1904
+ }
1905
+ if (value instanceof ArrayBuffer) {
1906
+ const bytes = new Uint8Array(value);
1907
+ return bodyFromBytes(bytes, bytes.length, contentType, options);
1908
+ }
1909
+ if (ArrayBuffer.isView(value)) {
1910
+ const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1911
+ return bodyFromBytes(bytes, bytes.length, contentType, options);
1912
+ }
1913
+ return undefined;
1914
+ }
1915
+ async function bodyFromFetchResponse(response, headers, options, shouldContinue = () => true) {
1916
+ if (!shouldContinue() || options.captureResponseBody === false)
1917
+ return undefined;
1918
+ const contentType = headerValue(headers, "content-type");
1919
+ if (!isTextContentType(contentType) && options.captureBinaryBodies !== true) {
1920
+ return undefined;
1921
+ }
1922
+ const totalBytes = parseContentLength(headers);
1923
+ const maximum = maximumBodyBytes(options);
1924
+ if (maximum <= 0)
1925
+ return undefined;
1926
+ const clone = response.clone();
1927
+ if (clone.body) {
1928
+ const reader = clone.body.getReader();
1929
+ const chunks = [];
1930
+ let capturedLength = 0;
1931
+ let observedLength = 0;
1932
+ try {
1933
+ while (capturedLength <= maximum) {
1934
+ if (!shouldContinue()) {
1935
+ await reader.cancel().catch(() => undefined);
1936
+ return undefined;
1937
+ }
1938
+ const result = await reader.read();
1939
+ if (!shouldContinue()) {
1940
+ await reader.cancel().catch(() => undefined);
1941
+ return undefined;
1942
+ }
1943
+ if (result.done)
1944
+ break;
1945
+ const chunk = result.value;
1946
+ observedLength += chunk.length;
1947
+ const remaining = maximum - capturedLength;
1948
+ if (remaining > 0) {
1949
+ const kept = chunk.slice(0, remaining);
1950
+ chunks.push(kept);
1951
+ capturedLength += kept.length;
1952
+ }
1953
+ if (observedLength > maximum) {
1954
+ await reader.cancel().catch(() => undefined);
1955
+ break;
1956
+ }
1957
+ }
1958
+ }
1959
+ finally {
1960
+ reader.releaseLock();
1961
+ }
1962
+ const joined = new Uint8Array(capturedLength);
1963
+ let offset = 0;
1964
+ for (const chunk of chunks) {
1965
+ joined.set(chunk, offset);
1966
+ offset += chunk.length;
1967
+ }
1968
+ return bodyFromBytes(joined, totalBytes ?? observedLength, contentType, options);
1969
+ }
1970
+ if (totalBytes == null || totalBytes > maximum)
1971
+ return undefined;
1972
+ const bytes = new Uint8Array(await clone.arrayBuffer());
1973
+ if (!shouldContinue())
1974
+ return undefined;
1975
+ return bodyFromBytes(bytes, totalBytes, contentType, options);
1976
+ }
1977
+ function parseXhrResponseHeaders(value) {
1978
+ return value
1979
+ .trim()
1980
+ .split(/[\r\n]+/)
1981
+ .flatMap((line) => {
1982
+ const separator = line.indexOf(":");
1983
+ return separator < 0
1984
+ ? []
1985
+ : [
1986
+ {
1987
+ name: line.slice(0, separator),
1988
+ value: line.slice(separator + 1),
1989
+ },
1990
+ ];
1991
+ });
1992
+ }
1993
+ function monotonicNow(globalObject) {
1994
+ return typeof globalObject.performance?.now === "function"
1995
+ ? globalObject.performance.now()
1996
+ : Date.now();
1997
+ }
1998
+ function installBrowserNetworkCapture(capture, options = {}, sourcePrefix = "capacitor", globalObject = globalThis) {
1999
+ const cleanups = [];
2000
+ let active = true;
2001
+ let fetchInvocationDepth = 0;
2002
+ if (options.captureFetch !== false &&
2003
+ typeof globalObject.fetch === "function") {
2004
+ const originalFetch = globalObject.fetch;
2005
+ const wrappedFetch = function (input, init) {
2006
+ const startedAtUtc = new Date().toISOString();
2007
+ const started = monotonicNow(globalObject);
2008
+ const inputRequest = typeof input === "object" && "headers" in input && "method" in input
2009
+ ? input
2010
+ : undefined;
2011
+ const requestHeaders = headerEntries(inputRequest?.headers).concat(headerEntries(init?.headers));
2012
+ const requestBody = bodyFromValue(init?.body, requestHeaders, options);
2013
+ const method = init?.method || inputRequest?.method || "GET";
2014
+ const url = typeof input === "string" ? input : inputRequest?.url || String(input);
2015
+ let promise;
2016
+ fetchInvocationDepth += 1;
2017
+ try {
2018
+ promise = originalFetch(input, init);
2019
+ }
2020
+ catch (error) {
2021
+ fetchInvocationDepth -= 1;
2022
+ const request = sanitizeNetworkRequest({
2023
+ source: `${sourcePrefix}.fetch`,
2024
+ startedAtUtc,
2025
+ completedAtUtc: new Date().toISOString(),
2026
+ durationMilliseconds: monotonicNow(globalObject) - started,
2027
+ method,
2028
+ url,
2029
+ requestHeaders: sanitizeHeaders(requestHeaders, {}),
2030
+ requestBodySizeBytes: parseContentLength(requestHeaders) ?? requestBody?.totalBytes,
2031
+ requestBody,
2032
+ errorType: error instanceof Error ? error.name : "Error",
2033
+ errorMessage: error instanceof Error ? error.message : String(error),
2034
+ }, options, globalObject);
2035
+ if (active && request)
2036
+ Promise.resolve(capture(request)).catch(() => undefined);
2037
+ throw error;
2038
+ }
2039
+ fetchInvocationDepth -= 1;
2040
+ return promise.then((response) => {
2041
+ if (!active)
2042
+ return response;
2043
+ const responseHeaders = headerEntries(response.headers);
2044
+ const responseRecord = {
2045
+ source: `${sourcePrefix}.fetch`,
2046
+ startedAtUtc,
2047
+ completedAtUtc: new Date().toISOString(),
2048
+ durationMilliseconds: monotonicNow(globalObject) - started,
2049
+ method,
2050
+ url: response.url || url,
2051
+ requestHeaders: sanitizeHeaders(requestHeaders, {}),
2052
+ requestBodySizeBytes: parseContentLength(requestHeaders) ?? requestBody?.totalBytes,
2053
+ requestBody,
2054
+ statusCode: response.status,
2055
+ reasonPhrase: response.statusText,
2056
+ responseHeaders: sanitizeHeaders(responseHeaders, {}),
2057
+ responseBodySizeBytes: parseContentLength(responseHeaders),
2058
+ };
2059
+ return bodyFromFetchResponse(response, responseHeaders, options, () => active).then((responseBody) => {
2060
+ const request = sanitizeNetworkRequest({
2061
+ ...responseRecord,
2062
+ responseBody,
2063
+ responseBodySizeBytes: responseRecord.responseBodySizeBytes ??
2064
+ responseBody?.totalBytes,
2065
+ }, options, globalObject);
2066
+ if (active && request)
2067
+ void Promise.resolve(capture(request)).catch(() => undefined);
2068
+ return response;
2069
+ }, () => {
2070
+ const request = sanitizeNetworkRequest(responseRecord, options, globalObject);
2071
+ if (active && request)
2072
+ void Promise.resolve(capture(request)).catch(() => undefined);
2073
+ return response;
2074
+ });
2075
+ }, (error) => {
2076
+ const request = sanitizeNetworkRequest({
2077
+ source: `${sourcePrefix}.fetch`,
2078
+ startedAtUtc,
2079
+ completedAtUtc: new Date().toISOString(),
2080
+ durationMilliseconds: monotonicNow(globalObject) - started,
2081
+ method,
2082
+ url,
2083
+ requestHeaders: sanitizeHeaders(requestHeaders, {}),
2084
+ requestBodySizeBytes: parseContentLength(requestHeaders) ?? requestBody?.totalBytes,
2085
+ requestBody,
2086
+ errorType: error instanceof Error ? error.name : "Error",
2087
+ errorMessage: error instanceof Error ? error.message : String(error),
2088
+ }, options, globalObject);
2089
+ if (active && request)
2090
+ Promise.resolve(capture(request)).catch(() => undefined);
2091
+ throw error;
2092
+ });
2093
+ };
2094
+ globalObject.fetch = wrappedFetch;
2095
+ cleanups.push(() => {
2096
+ if (globalObject.fetch === wrappedFetch)
2097
+ globalObject.fetch = originalFetch;
2098
+ });
2099
+ }
2100
+ const Xhr = globalObject.XMLHttpRequest;
2101
+ if (options.captureXmlHttpRequest !== false && Xhr?.prototype) {
2102
+ const states = new WeakMap();
2103
+ const prototype = Xhr.prototype;
2104
+ const originalOpen = prototype.open;
2105
+ const originalSend = prototype.send;
2106
+ const originalSetRequestHeader = prototype.setRequestHeader;
2107
+ const wrappedOpen = function (method, url, ...rest) {
2108
+ states.set(this, {
2109
+ method,
2110
+ url: String(url),
2111
+ requestHeaders: [],
2112
+ suppressed: fetchInvocationDepth > 0,
2113
+ });
2114
+ Reflect.apply(originalOpen, this, [method, url, ...rest]);
2115
+ };
2116
+ const wrappedSetRequestHeader = function (name, value) {
2117
+ states.get(this)?.requestHeaders.push({ name, value });
2118
+ Reflect.apply(originalSetRequestHeader, this, [name, value]);
2119
+ };
2120
+ const wrappedSend = function (body) {
2121
+ const state = states.get(this);
2122
+ if (!state || state.suppressed) {
2123
+ Reflect.apply(originalSend, this, [body]);
2124
+ return;
2125
+ }
2126
+ state.startedAtUtc = new Date().toISOString();
2127
+ state.started = monotonicNow(globalObject);
2128
+ state.requestBody = bodyFromValue(body, state.requestHeaders, options);
2129
+ let failure;
2130
+ const markFailure = (event) => {
2131
+ failure = event.type;
2132
+ };
2133
+ const complete = () => {
2134
+ if (!active)
2135
+ return;
2136
+ let responseHeaders = [];
2137
+ try {
2138
+ responseHeaders = parseXhrResponseHeaders(this.getAllResponseHeaders());
2139
+ }
2140
+ catch {
2141
+ // Some WebViews throw before response headers exist.
2142
+ }
2143
+ let responseBody;
2144
+ try {
2145
+ const responseType = this.responseType || "text";
2146
+ const responseOptions = {
2147
+ ...options,
2148
+ captureRequestBody: options.captureResponseBody,
2149
+ };
2150
+ if (responseType === "text") {
2151
+ responseBody = bodyFromValue(this.responseText, responseHeaders, responseOptions);
2152
+ }
2153
+ else if (responseType === "arraybuffer") {
2154
+ responseBody = bodyFromValue(this.response, responseHeaders, responseOptions);
2155
+ }
2156
+ }
2157
+ catch {
2158
+ // Response data is not readable for every XHR response type.
2159
+ }
2160
+ const request = sanitizeNetworkRequest({
2161
+ source: `${sourcePrefix}.xhr`,
2162
+ startedAtUtc: state.startedAtUtc,
2163
+ completedAtUtc: new Date().toISOString(),
2164
+ durationMilliseconds: monotonicNow(globalObject) - (state.started ?? 0),
2165
+ method: state.method,
2166
+ url: this.responseURL || state.url,
2167
+ requestHeaders: state.requestHeaders,
2168
+ requestBodySizeBytes: parseContentLength(state.requestHeaders) ??
2169
+ state.requestBody?.totalBytes,
2170
+ requestBody: state.requestBody,
2171
+ statusCode: this.status || undefined,
2172
+ reasonPhrase: this.statusText,
2173
+ responseHeaders,
2174
+ responseBodySizeBytes: parseContentLength(responseHeaders) ?? responseBody?.totalBytes,
2175
+ responseBody,
2176
+ errorType: failure,
2177
+ errorMessage: failure ? `XMLHttpRequest ${failure}` : undefined,
2178
+ }, options, globalObject);
2179
+ if (request)
2180
+ Promise.resolve(capture(request)).catch(() => undefined);
2181
+ };
2182
+ this.addEventListener("error", markFailure);
2183
+ this.addEventListener("abort", markFailure);
2184
+ this.addEventListener("timeout", markFailure);
2185
+ this.addEventListener("loadend", complete, { once: true });
2186
+ Reflect.apply(originalSend, this, [body]);
2187
+ };
2188
+ prototype.open = wrappedOpen;
2189
+ prototype.setRequestHeader = wrappedSetRequestHeader;
2190
+ prototype.send = wrappedSend;
2191
+ cleanups.push(() => {
2192
+ if (prototype.open === wrappedOpen)
2193
+ prototype.open = originalOpen;
2194
+ if (prototype.send === wrappedSend)
2195
+ prototype.send = originalSend;
2196
+ if (prototype.setRequestHeader === wrappedSetRequestHeader) {
2197
+ prototype.setRequestHeader = originalSetRequestHeader;
2198
+ }
2199
+ });
2200
+ }
2201
+ let removed = false;
2202
+ return {
2203
+ remove() {
2204
+ if (removed)
2205
+ return;
2206
+ removed = true;
2207
+ active = false;
2208
+ for (const cleanup of cleanups.reverse())
2209
+ cleanup();
2210
+ },
2211
+ };
2212
+ }
2213
+
2214
+ const ANSIGHT_CAPACITOR_SDK_VERSION = "1.3.0-preview.12";
2215
+ const COMPILED_CAPACITOR_CORE_VERSION = "8.4.2";
2216
+ const CAPACITOR_GROUP = "capacitor";
2217
+ const LOCALIZATION_GROUP = "localization";
2218
+ function normalized(value) {
2219
+ if (value == null)
2220
+ return undefined;
2221
+ const result = String(value).trim();
2222
+ return result || undefined;
2223
+ }
2224
+ function canonicalizeLocale(value) {
2225
+ const locale = normalized(value)?.replace(/_/g, "-");
2226
+ if (!locale)
2227
+ return undefined;
2228
+ try {
2229
+ return Intl.getCanonicalLocales(locale)[0] ?? locale;
2230
+ }
2231
+ catch {
2232
+ return locale;
2233
+ }
2234
+ }
2235
+ function parseLocale(locale) {
2236
+ const parts = (locale ?? "").split("-").filter(Boolean);
2237
+ const language = parts[0]?.toLowerCase();
2238
+ const region = parts.find((part, index) => index > 0 && (/^[A-Za-z]{2}$/.test(part) || /^\d{3}$/.test(part)));
2239
+ return { language, region: region?.toUpperCase() };
2240
+ }
2241
+ function webViewDetails(platform, nativePlatform, userAgent) {
2242
+ const agent = userAgent ?? "";
2243
+ if (nativePlatform && platform === "ios") {
2244
+ return {
2245
+ engine: "wkWebView",
2246
+ version: /AppleWebKit\/([^\s]+)/.exec(agent)?.[1],
2247
+ };
2248
+ }
2249
+ if (nativePlatform && platform === "android") {
2250
+ return {
2251
+ engine: "chromiumWebView",
2252
+ version: /(?:Chrome|Chromium)\/([^\s]+)/.exec(agent)?.[1],
2253
+ };
2254
+ }
2255
+ if (/Firefox\/([^\s]+)/.test(agent)) {
2256
+ return { engine: "gecko", version: /Firefox\/([^\s]+)/.exec(agent)?.[1] };
2257
+ }
2258
+ if (/(?:Chrome|Chromium)\/([^\s]+)/.test(agent)) {
2259
+ return {
2260
+ engine: "chromium",
2261
+ version: /(?:Chrome|Chromium)\/([^\s]+)/.exec(agent)?.[1],
2262
+ };
2263
+ }
2264
+ if (/AppleWebKit\/([^\s]+)/.test(agent)) {
2265
+ return {
2266
+ engine: "webkit",
2267
+ version: /AppleWebKit\/([^\s]+)/.exec(agent)?.[1],
2268
+ };
2269
+ }
2270
+ return { engine: "unknown" };
2271
+ }
2272
+ function currentCapacitorSessionEnvironment(platform, nativePlatform) {
2273
+ let resolved;
2274
+ try {
2275
+ resolved = Intl.DateTimeFormat().resolvedOptions();
2276
+ }
2277
+ catch {
2278
+ resolved = undefined;
2279
+ }
2280
+ return {
2281
+ platform,
2282
+ nativePlatform,
2283
+ userAgent: typeof navigator === "undefined" ? undefined : navigator.userAgent,
2284
+ locale: resolved?.locale ??
2285
+ (typeof navigator === "undefined" ? undefined : navigator.language),
2286
+ timeZone: resolved?.timeZone,
2287
+ utcOffsetMinutes: -new Date().getTimezoneOffset(),
2288
+ };
2289
+ }
2290
+ function createAutomaticSessionProperties(environment) {
2291
+ const platform = normalized(environment.platform) ?? "unknown";
2292
+ const userAgent = normalized(environment.userAgent);
2293
+ const webView = webViewDetails(platform, environment.nativePlatform, userAgent);
2294
+ const locale = canonicalizeLocale(environment.locale);
2295
+ const parsedLocale = parseLocale(locale);
2296
+ const capacitor = {
2297
+ sdkVersion: ANSIGHT_CAPACITOR_SDK_VERSION,
2298
+ capacitorVersion: "8.x",
2299
+ compiledCapacitorVersion: COMPILED_CAPACITOR_CORE_VERSION,
2300
+ platform,
2301
+ runtimeLanguage: "javascript",
2302
+ executionMode: environment.nativePlatform ? "native" : "web",
2303
+ webViewEngine: webView.engine,
2304
+ };
2305
+ if (webView.version)
2306
+ capacitor.webViewEngineVersion = webView.version;
2307
+ if (userAgent)
2308
+ capacitor.userAgent = userAgent;
2309
+ const localization = {
2310
+ utcOffsetMinutes: String(environment.utcOffsetMinutes ?? -new Date().getTimezoneOffset()),
2311
+ };
2312
+ if (locale)
2313
+ localization.locale = locale;
2314
+ if (parsedLocale.language)
2315
+ localization.language = parsedLocale.language;
2316
+ if (parsedLocale.region)
2317
+ localization.region = parsedLocale.region;
2318
+ if (normalized(environment.timeZone)) {
2319
+ localization.timeZone = String(environment.timeZone).trim();
2320
+ }
2321
+ return {
2322
+ [CAPACITOR_GROUP]: capacitor,
2323
+ [LOCALIZATION_GROUP]: localization,
2324
+ };
2325
+ }
2326
+ function mergeSessionProperties(automaticProperties, customProperties) {
2327
+ const merged = Object.fromEntries(Object.entries(automaticProperties).map(([group, properties]) => [
2328
+ group,
2329
+ { ...properties },
2330
+ ]));
2331
+ for (const [group, properties] of Object.entries(customProperties ?? {})) {
2332
+ merged[group] = { ...(merged[group] ?? {}), ...properties };
2333
+ }
2334
+ return merged;
2335
+ }
2336
+
1373
2337
  const AnsightNative = registerPlugin("Ansight");
1374
2338
  const toolHandlers = new Map();
1375
2339
  const artifactProviders = new Map();
@@ -1380,6 +2344,9 @@
1380
2344
  let lifecycleCleanup;
1381
2345
  let artifactToolRegistrations = [];
1382
2346
  let domToolRegistration;
2347
+ let networkCaptureSubscription;
2348
+ let networkCaptureRegistration;
2349
+ let networkConnectionListener;
1383
2350
  function normalizePairingPayload(payload) {
1384
2351
  if (payload == null)
1385
2352
  return payload;
@@ -1387,11 +2354,19 @@
1387
2354
  }
1388
2355
  function normalizeOptions(input) {
1389
2356
  const options = JSON.parse(JSON.stringify(input));
2357
+ options.customProperties = mergeSessionProperties(automaticSessionProperties(), options.customProperties);
1390
2358
  delete options.domTools;
1391
2359
  delete options.errorCapture;
1392
2360
  delete options.lifecycle;
2361
+ delete options.networkCapture;
1393
2362
  return options;
1394
2363
  }
2364
+ function automaticSessionProperties() {
2365
+ return createAutomaticSessionProperties(currentCapacitorSessionEnvironment(Capacitor.getPlatform(), Capacitor.isNativePlatform()));
2366
+ }
2367
+ function automaticSessionPropertyValue(group, key) {
2368
+ return automaticSessionProperties()[group]?.[key];
2369
+ }
1395
2370
  function normalizeToolResult(value) {
1396
2371
  if (value && typeof value === "object" && "success" in value) {
1397
2372
  return value;
@@ -1441,11 +2416,13 @@
1441
2416
  }
1442
2417
  async function afterConnectionChange(operation) {
1443
2418
  const result = await operation();
2419
+ await refreshNetworkCaptureConnection();
1444
2420
  await emitHostConnectionStatus();
1445
2421
  return result;
1446
2422
  }
1447
2423
  async function initialize(options = {}) {
1448
2424
  const result = await AnsightNative.initialize(normalizeOptions(options));
2425
+ await configureNetworkCapture(options.networkCapture);
1449
2426
  if (options.lifecycle !== false)
1450
2427
  startLifecycleTracking();
1451
2428
  if (options.errorCapture) {
@@ -1459,6 +2436,7 @@
1459
2436
  }
1460
2437
  async function initializeAndActivate(options = {}) {
1461
2438
  const result = await AnsightNative.initializeAndActivate(normalizeOptions(options));
2439
+ await configureNetworkCapture(options.networkCapture);
1462
2440
  if (options.lifecycle !== false)
1463
2441
  startLifecycleTracking();
1464
2442
  if (options.errorCapture) {
@@ -1483,6 +2461,80 @@
1483
2461
  return AnsightNative.recordEvent(typeof input === "string" ? { label: input } : input);
1484
2462
  }
1485
2463
  const recordEvent = event;
2464
+ async function recordNetworkRequest(input, sanitizationOptions = {}) {
2465
+ const request = sanitizeNetworkRequest(input, sanitizationOptions);
2466
+ if (!request) {
2467
+ return {
2468
+ success: false,
2469
+ message: "Network request capture was suppressed by the sanitizer.",
2470
+ };
2471
+ }
2472
+ return AnsightNative.recordNetworkRequest(request);
2473
+ }
2474
+ function installNetworkCapture(options = {}) {
2475
+ uninstallNetworkCapture();
2476
+ const registration = { options };
2477
+ networkCaptureRegistration = registration;
2478
+ ensureNetworkConnectionListener();
2479
+ void refreshNetworkCaptureConnection();
2480
+ return {
2481
+ remove() {
2482
+ if (networkCaptureRegistration === registration) {
2483
+ uninstallNetworkCapture();
2484
+ }
2485
+ },
2486
+ };
2487
+ }
2488
+ function uninstallNetworkCapture() {
2489
+ networkCaptureRegistration = undefined;
2490
+ const listener = networkConnectionListener;
2491
+ networkConnectionListener = undefined;
2492
+ if (listener)
2493
+ void listener.then((value) => value.remove());
2494
+ detachNetworkCapture();
2495
+ }
2496
+ function detachNetworkCapture() {
2497
+ networkCaptureSubscription?.remove();
2498
+ networkCaptureSubscription = undefined;
2499
+ }
2500
+ async function refreshNetworkCaptureConnection() {
2501
+ const registration = networkCaptureRegistration;
2502
+ if (!registration) {
2503
+ detachNetworkCapture();
2504
+ return;
2505
+ }
2506
+ try {
2507
+ const status = await AnsightNative.hostConnectionStatus();
2508
+ if (networkCaptureRegistration !== registration)
2509
+ return;
2510
+ applyNetworkConnectionStatus(status);
2511
+ }
2512
+ catch {
2513
+ if (networkCaptureRegistration === registration)
2514
+ detachNetworkCapture();
2515
+ }
2516
+ }
2517
+ function ensureNetworkConnectionListener() {
2518
+ networkConnectionListener ??= AnsightNative.addListener("ansightHostConnectionStatus", applyNetworkConnectionStatus);
2519
+ }
2520
+ function applyNetworkConnectionStatus(status) {
2521
+ const registration = networkCaptureRegistration;
2522
+ if (!registration || status.isConnected !== true) {
2523
+ detachNetworkCapture();
2524
+ return;
2525
+ }
2526
+ networkCaptureSubscription ??= installBrowserNetworkCapture((request) => AnsightNative.recordNetworkRequest(request), registration.options);
2527
+ }
2528
+ async function configureNetworkCapture(value) {
2529
+ uninstallNetworkCapture();
2530
+ if (!value)
2531
+ return;
2532
+ networkCaptureRegistration = {
2533
+ options: typeof value === "object" ? value : {},
2534
+ };
2535
+ ensureNetworkConnectionListener();
2536
+ await refreshNetworkCaptureConnection();
2537
+ }
1486
2538
  const recordCrashCandidate = (input) => AnsightNative.recordCrashCandidate(input);
1487
2539
  const screenViewed = (name, details = {}) => AnsightNative.screenViewed({ name, details });
1488
2540
  const trackRoute = screenViewed;
@@ -1538,12 +2590,25 @@
1538
2590
  const captureScreenFrame = (options = {}) => AnsightNative.captureScreenFrame(options);
1539
2591
  const enableTouchCapture = () => AnsightNative.enableTouchCapture();
1540
2592
  const disableTouchCapture = () => AnsightNative.disableTouchCapture();
1541
- const updateSessionProperties = (properties) => AnsightNative.updateSessionProperties({ properties });
2593
+ const updateSessionProperties = (properties) => AnsightNative.updateSessionProperties({
2594
+ properties: mergeSessionProperties(automaticSessionProperties(), properties),
2595
+ });
1542
2596
  const updateCustomProperties = updateSessionProperties;
1543
- const clearSessionProperties = () => AnsightNative.clearSessionProperties();
2597
+ const clearSessionProperties = () => AnsightNative.updateSessionProperties({
2598
+ properties: automaticSessionProperties(),
2599
+ });
1544
2600
  const clearCustomProperties = clearSessionProperties;
1545
2601
  const registerCustomProperty = (group, key, value) => AnsightNative.registerCustomProperty({ group, key, value });
1546
- const removeCustomProperty = (group, key) => AnsightNative.removeCustomProperty({ group, key });
2602
+ const removeCustomProperty = (group, key) => {
2603
+ const automaticValue = automaticSessionPropertyValue(group, key);
2604
+ return automaticValue == null
2605
+ ? AnsightNative.removeCustomProperty({ group, key })
2606
+ : AnsightNative.registerCustomProperty({
2607
+ group,
2608
+ key,
2609
+ value: automaticValue,
2610
+ });
2611
+ };
1547
2612
  function addHostConnectionStatusListener(listener, options = {}) {
1548
2613
  hostConnectionListeners.add(listener);
1549
2614
  if (options.emitCurrent !== false)
@@ -1894,6 +2959,10 @@
1894
2959
  recordMetric,
1895
2960
  event,
1896
2961
  recordEvent,
2962
+ recordNetworkRequest,
2963
+ installNetworkCapture,
2964
+ uninstallNetworkCapture,
2965
+ sanitizeNetworkRequest,
1897
2966
  screenViewed,
1898
2967
  trackRoute,
1899
2968
  setAppLifecycleState,
@@ -1955,10 +3024,9 @@
1955
3024
  platform: Capacitor.getPlatform(),
1956
3025
  };
1957
3026
 
1958
- if (typeof window !== "undefined") {
1959
- const options = Ansight.createOptionsBuilder(globalThis.__ANSIGHT_CAPACITOR_STANDALONE_OPTIONS__ ?? {})
3027
+ function createStandaloneOptions(overrides = {}) {
3028
+ return createOptionsBuilder(overrides)
1960
3029
  .withAnsightDefaults()
1961
- .withAllToolAccess()
1962
3030
  .withVisualTreeTools()
1963
3031
  .withFileSystemTools()
1964
3032
  .withDatabaseTools()
@@ -1966,7 +3034,12 @@
1966
3034
  .withReflectionTools()
1967
3035
  .withDomTools()
1968
3036
  .withErrorCapture()
3037
+ .withToolGuard(overrides.toolGuard ?? "readOnly")
1969
3038
  .build();
3039
+ }
3040
+
3041
+ if (typeof window !== "undefined") {
3042
+ const options = createStandaloneOptions(globalThis.__ANSIGHT_CAPACITOR_STANDALONE_OPTIONS__ ?? {});
1970
3043
  void Ansight.initializeAndActivate(options).catch((error) => {
1971
3044
  console.error("[Ansight Capacitor]", error);
1972
3045
  });