@utk09/ui-observability 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +52 -45
  3. package/dist/bus/bus.d.ts +46 -12
  4. package/dist/bus/links.d.ts +6 -3
  5. package/dist/bus-CtJWf9QN.cjs +2 -0
  6. package/dist/bus-CtJWf9QN.cjs.map +1 -0
  7. package/dist/{bus-DPDrlUBY.js → bus-D8kH58tb.js} +128 -71
  8. package/dist/bus-D8kH58tb.js.map +1 -0
  9. package/dist/capture/interactions.d.ts +7 -6
  10. package/dist/capture/network.d.ts +23 -9
  11. package/dist/capture/types.d.ts +3 -3
  12. package/dist/console-BpHfWstv.cjs +2 -0
  13. package/dist/console-BpHfWstv.cjs.map +1 -0
  14. package/dist/console-DjLbryED.js +82 -0
  15. package/dist/console-DjLbryED.js.map +1 -0
  16. package/dist/constants-Br3b89Wg.cjs +2 -0
  17. package/dist/constants-Br3b89Wg.cjs.map +1 -0
  18. package/dist/constants-DM94FjVX.js +96 -0
  19. package/dist/constants-DM94FjVX.js.map +1 -0
  20. package/dist/constants.d.ts +20 -9
  21. package/dist/core/diagnostics.d.ts +2 -2
  22. package/dist/core/journey.d.ts +16 -4
  23. package/dist/core/logger.d.ts +6 -2
  24. package/dist/core/pipeline.d.ts +18 -9
  25. package/dist/core/record.d.ts +11 -6
  26. package/dist/core/remote-sampling.d.ts +1 -1
  27. package/dist/core/runtime.d.ts +43 -15
  28. package/dist/core/sender.d.ts +15 -10
  29. package/dist/deadline-B5DINjD5.js +111 -0
  30. package/dist/deadline-B5DINjD5.js.map +1 -0
  31. package/dist/deadline-Cbg2cbUw.cjs +2 -0
  32. package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
  33. package/dist/error-like-Ywo5uRHo.js +19 -0
  34. package/dist/error-like-Ywo5uRHo.js.map +1 -0
  35. package/dist/error-like-gGRx2s36.cjs +2 -0
  36. package/dist/error-like-gGRx2s36.cjs.map +1 -0
  37. package/dist/errors-CpGRhhIf.cjs +3 -0
  38. package/dist/errors-CpGRhhIf.cjs.map +1 -0
  39. package/dist/{errors-Dnc-X4Ec.js → errors-DH4QJS0u.js} +39 -20
  40. package/dist/errors-DH4QJS0u.js.map +1 -0
  41. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  42. package/dist/global-scope-dp2jADRl.js.map +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +11 -4
  46. package/dist/index.js +561 -436
  47. package/dist/index.js.map +1 -1
  48. package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
  49. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
  50. package/dist/{indexeddb-storage-uD4oaRMc.js → indexeddb-storage-n1qkFBGA.js} +17 -17
  51. package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
  52. package/dist/interactions-31eHGwEQ.cjs +2 -0
  53. package/dist/interactions-31eHGwEQ.cjs.map +1 -0
  54. package/dist/{interactions-igKTAJvj.js → interactions-OU94MPXs.js} +22 -19
  55. package/dist/interactions-OU94MPXs.js.map +1 -0
  56. package/dist/journey-CE2EcwHW.cjs +2 -0
  57. package/dist/journey-CE2EcwHW.cjs.map +1 -0
  58. package/dist/journey-CeJ1QoT2.js +162 -0
  59. package/dist/journey-CeJ1QoT2.js.map +1 -0
  60. package/dist/{library-request-Br_T09Bn.cjs → library-request-C9uJFlbq.cjs} +2 -2
  61. package/dist/{library-request-Br_T09Bn.cjs.map → library-request-C9uJFlbq.cjs.map} +1 -1
  62. package/dist/{library-request-Dt0fXhcn.js → library-request-DvhuplAB.js} +2 -2
  63. package/dist/{library-request-Dt0fXhcn.js.map → library-request-DvhuplAB.js.map} +1 -1
  64. package/dist/{long-frames-DahhqM6u.cjs → long-frames-B8VdA_ny.cjs} +2 -2
  65. package/dist/{long-frames-DahhqM6u.cjs.map → long-frames-B8VdA_ny.cjs.map} +1 -1
  66. package/dist/{long-frames-6pnjWSSR.js → long-frames-C_7OutLs.js} +3 -3
  67. package/dist/{long-frames-6pnjWSSR.js.map → long-frames-C_7OutLs.js.map} +1 -1
  68. package/dist/models/batch.d.ts +1 -1
  69. package/dist/models/bus.d.ts +7 -4
  70. package/dist/models/config.d.ts +43 -12
  71. package/dist/models/log-record.d.ts +12 -6
  72. package/dist/network-BAV7ipyn.cjs +2 -0
  73. package/dist/network-BAV7ipyn.cjs.map +1 -0
  74. package/dist/network-D_lloS5t.js +174 -0
  75. package/dist/network-D_lloS5t.js.map +1 -0
  76. package/dist/patch-BX8KrPCT.cjs +2 -0
  77. package/dist/patch-BX8KrPCT.cjs.map +1 -0
  78. package/dist/patch-CCWfuEY7.js +9 -0
  79. package/dist/patch-CCWfuEY7.js.map +1 -0
  80. package/dist/{platform-D_XkVIF6.cjs → platform-D4wu1eIF.cjs} +2 -2
  81. package/dist/platform-D4wu1eIF.cjs.map +1 -0
  82. package/dist/platform-IHBZGqUe.js +48 -0
  83. package/dist/platform-IHBZGqUe.js.map +1 -0
  84. package/dist/{remote-rules-5UA23alm.js → remote-rules-Bt1XsdEQ.js} +14 -14
  85. package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
  86. package/dist/{remote-rules-rJJZKVG8.cjs → remote-rules-kuDf5gbe.cjs} +2 -2
  87. package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
  88. package/dist/sampling-BI15ds9D.cjs +2 -0
  89. package/dist/sampling-BI15ds9D.cjs.map +1 -0
  90. package/dist/sampling-o0VY1mqQ.js +63 -0
  91. package/dist/sampling-o0VY1mqQ.js.map +1 -0
  92. package/dist/sanitize-B9UheVKc.js +123 -0
  93. package/dist/sanitize-B9UheVKc.js.map +1 -0
  94. package/dist/sanitize-DSIP7amZ.cjs +2 -0
  95. package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
  96. package/dist/{sender-G6v4Uqi4.js → sender-BnNj9bOX.js} +234 -176
  97. package/dist/sender-BnNj9bOX.js.map +1 -0
  98. package/dist/sender-D0OsyB1c.cjs +3 -0
  99. package/dist/sender-D0OsyB1c.cjs.map +1 -0
  100. package/dist/storage/emergency-queue.d.ts +1 -1
  101. package/dist/storage/factory.d.ts +1 -1
  102. package/dist/storage/idb-driver.d.ts +1 -1
  103. package/dist/storage/local-storage.d.ts +3 -3
  104. package/dist/storage/memory-storage.d.ts +3 -3
  105. package/dist/{storm-DJkEZP_8.js → storm-BTw0J6eE.js} +2 -2
  106. package/dist/{storm-DJkEZP_8.js.map → storm-BTw0J6eE.js.map} +1 -1
  107. package/dist/{storm-BtzgLOCX.cjs → storm-Y-yuBhvv.cjs} +2 -2
  108. package/dist/{storm-BtzgLOCX.cjs.map → storm-Y-yuBhvv.cjs.map} +1 -1
  109. package/dist/transport/compression.d.ts +1 -1
  110. package/dist/transport/exit-flush.d.ts +21 -17
  111. package/dist/transport/http-transport.d.ts +61 -7
  112. package/dist/transport/retry-engine.d.ts +5 -5
  113. package/dist/transport/status-transport.d.ts +4 -2
  114. package/dist/utils/console.d.ts +1 -1
  115. package/dist/utils/error-like.d.ts +25 -0
  116. package/dist/utils/global-scope.d.ts +1 -1
  117. package/dist/utils/identity.d.ts +1 -1
  118. package/dist/utils/library-console.d.ts +1 -1
  119. package/dist/utils/library-request.d.ts +1 -1
  120. package/dist/utils/patch.d.ts +9 -0
  121. package/dist/utils/platform.d.ts +3 -3
  122. package/dist/utils/sequence.d.ts +0 -5
  123. package/dist/utils/timer.d.ts +1 -1
  124. package/dist/utils/tracing.d.ts +3 -3
  125. package/dist/utils/unref.d.ts +2 -2
  126. package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
  127. package/dist/web-vitals-Bflr5jSA.js.map +1 -0
  128. package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
  129. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
  130. package/package.json +2 -2
  131. package/dist/bus-CUXRY0JR.cjs +0 -2
  132. package/dist/bus-CUXRY0JR.cjs.map +0 -1
  133. package/dist/bus-DPDrlUBY.js.map +0 -1
  134. package/dist/console-CNljJict.js +0 -81
  135. package/dist/console-CNljJict.js.map +0 -1
  136. package/dist/console-PKzc-FmR.cjs +0 -2
  137. package/dist/console-PKzc-FmR.cjs.map +0 -1
  138. package/dist/constants-B28fDv2F.cjs +0 -2
  139. package/dist/constants-B28fDv2F.cjs.map +0 -1
  140. package/dist/constants-Bu49bm39.js +0 -93
  141. package/dist/constants-Bu49bm39.js.map +0 -1
  142. package/dist/errors-C78ZTjet.cjs +0 -3
  143. package/dist/errors-C78ZTjet.cjs.map +0 -1
  144. package/dist/errors-Dnc-X4Ec.js.map +0 -1
  145. package/dist/indexeddb-storage-D0p3iMD0.cjs +0 -2
  146. package/dist/indexeddb-storage-D0p3iMD0.cjs.map +0 -1
  147. package/dist/indexeddb-storage-uD4oaRMc.js.map +0 -1
  148. package/dist/interactions-CsE2y_fQ.cjs +0 -2
  149. package/dist/interactions-CsE2y_fQ.cjs.map +0 -1
  150. package/dist/interactions-igKTAJvj.js.map +0 -1
  151. package/dist/network-CZ0aFUsy.cjs +0 -2
  152. package/dist/network-CZ0aFUsy.cjs.map +0 -1
  153. package/dist/network-aSNbwpue.js +0 -112
  154. package/dist/network-aSNbwpue.js.map +0 -1
  155. package/dist/platform-BwbMRwHm.js +0 -48
  156. package/dist/platform-BwbMRwHm.js.map +0 -1
  157. package/dist/platform-D_XkVIF6.cjs.map +0 -1
  158. package/dist/remote-rules-5UA23alm.js.map +0 -1
  159. package/dist/remote-rules-rJJZKVG8.cjs.map +0 -1
  160. package/dist/sampling-E4x92Nn2.cjs +0 -2
  161. package/dist/sampling-E4x92Nn2.cjs.map +0 -1
  162. package/dist/sampling-J1eahbfT.js +0 -160
  163. package/dist/sampling-J1eahbfT.js.map +0 -1
  164. package/dist/sanitize-BMhh8ghJ.cjs +0 -2
  165. package/dist/sanitize-BMhh8ghJ.cjs.map +0 -1
  166. package/dist/sanitize-UJ-4Lb0n.js +0 -114
  167. package/dist/sanitize-UJ-4Lb0n.js.map +0 -1
  168. package/dist/sender-B6ufz26f.cjs +0 -3
  169. package/dist/sender-B6ufz26f.cjs.map +0 -1
  170. package/dist/sender-G6v4Uqi4.js.map +0 -1
  171. package/dist/unref-16maCyKA.js +0 -8
  172. package/dist/unref-16maCyKA.js.map +0 -1
  173. package/dist/unref-CU9Nyz_9.cjs +0 -2
  174. package/dist/unref-CU9Nyz_9.cjs.map +0 -1
  175. package/dist/web-vitals-B2FYsEAU.cjs +0 -2
  176. package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
  177. package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
@@ -0,0 +1,111 @@
1
+ import { Qt as e, un as t } from "./constants-DM94FjVX.js";
2
+ //#region src/utils/identity.ts
3
+ var n = {
4
+ local: () => localStorage,
5
+ session: () => sessionStorage
6
+ };
7
+ function r() {
8
+ let e = (e) => ({
9
+ getItem: (t) => e.get(t) ?? null,
10
+ setItem: (t, n) => {
11
+ e.set(t, n);
12
+ },
13
+ removeItem: (t) => {
14
+ e.delete(t);
15
+ }
16
+ }), t = e(/* @__PURE__ */ new Map()), n = e(/* @__PURE__ */ new Map());
17
+ return {
18
+ local: () => t,
19
+ session: () => n
20
+ };
21
+ }
22
+ function i(e) {
23
+ let t = new Uint8Array(e);
24
+ if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
25
+ else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
26
+ return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
27
+ }
28
+ function a(e) {
29
+ try {
30
+ if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
31
+ } catch {
32
+ e.count("platform.api_blocked");
33
+ }
34
+ return i(16);
35
+ }
36
+ function o(e, t, n, r) {
37
+ return r.guard("storage.unavailable", `The library could not read ${t}Storage.`, () => e[t]().getItem(n)) ?? null;
38
+ }
39
+ function s(e, t, n, r, i) {
40
+ i.guard("storage.unavailable", `The library could not write to ${t}Storage.`, () => {
41
+ e[t]().setItem(n, r);
42
+ });
43
+ }
44
+ function c(r, i = n) {
45
+ let c = a(r), l = Date.now(), u = a(r), d = o(i, "local", e, r);
46
+ if (d) try {
47
+ let e = JSON.parse(d);
48
+ e.id && l - (e.lastSeenAt ?? 0) < 18e5 && (u = e.id);
49
+ } catch {
50
+ r.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
51
+ }
52
+ let f = JSON.stringify({
53
+ id: u,
54
+ lastSeenAt: l
55
+ });
56
+ s(i, "local", e, f, r);
57
+ let p = o(i, "session", "ui-observability.tab", r) ?? "";
58
+ return p || (p = a(r), s(i, "session", t, p, r)), {
59
+ sessionId: u,
60
+ tabId: p,
61
+ contextId: c
62
+ };
63
+ }
64
+ function l(e, n, r) {
65
+ s(r, "session", t, e, n);
66
+ }
67
+ var u = class {
68
+ diagnostics;
69
+ stores;
70
+ lastTouchAt = 0;
71
+ constructor(e, t = n) {
72
+ this.diagnostics = e, this.stores = t;
73
+ }
74
+ touch(t) {
75
+ let n = Date.now();
76
+ if (n - this.lastTouchAt < 6e4) return;
77
+ this.lastTouchAt = n;
78
+ let r = JSON.stringify({
79
+ id: t,
80
+ lastSeenAt: n
81
+ });
82
+ s(this.stores, "local", e, r, this.diagnostics);
83
+ }
84
+ };
85
+ //#endregion
86
+ //#region src/utils/unref.ts
87
+ function d(e) {
88
+ typeof e != "number" && e.unref?.();
89
+ }
90
+ //#endregion
91
+ //#region src/utils/deadline.ts
92
+ var f = class extends Error {
93
+ constructor(e) {
94
+ super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
95
+ }
96
+ };
97
+ function p(e, t) {
98
+ let n, r = new Promise((e, r) => {
99
+ let i = setTimeout(() => {
100
+ r(new f(t));
101
+ }, t);
102
+ n = i, d(i);
103
+ });
104
+ return Promise.race([e, r]).finally(() => {
105
+ clearTimeout(n);
106
+ });
107
+ }
108
+ //#endregion
109
+ export { u as a, l as c, n as i, i as l, p as n, r as o, d as r, a as s, f as t, c as u };
110
+
111
+ //# sourceMappingURL=deadline-B5DINjD5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-B5DINjD5.js","names":["SESSION_ID_KEY","TAB_ID_KEY","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work"],"sources":["../src/utils/identity.ts","../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-Br3b89Wg.cjs");var t={local:()=>localStorage,session:()=>sessionStorage};function n(){let e=e=>({getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}),t=e(new Map),n=e(new Map);return{local:()=>t,session:()=>n}}function r(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{e.count(`platform.api_blocked`)}return r(16)}function a(e,t,n,r){return r.guard(`storage.unavailable`,`The library could not read ${t}Storage.`,()=>e[t]().getItem(n))??null}function o(e,t,n,r,i){i.guard(`storage.unavailable`,`The library could not write to ${t}Storage.`,()=>{e[t]().setItem(n,r)})}function s(n,r=t){let s=i(n),c=Date.now(),l=i(n),u=a(r,`local`,e.Qt,n);if(u)try{let e=JSON.parse(u);e.id&&c-(e.lastSeenAt??0)<18e5&&(l=e.id)}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`)}let d=JSON.stringify({id:l,lastSeenAt:c});o(r,`local`,e.Qt,d,n);let f=a(r,`session`,`ui-observability.tab`,n)??``;return f||(f=i(n),o(r,`session`,e.un,f,n)),{sessionId:l,tabId:f,contextId:s}}function c(t,n,r){o(r,`session`,e.un,t,n)}var l=class{diagnostics;stores;lastTouchAt=0;constructor(e,n=t){this.diagnostics=e,this.stores=n}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.Qt,r,this.diagnostics)}};function u(e){typeof e!=`number`&&e.unref?.()}var d=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function f(e,t){let n,r=new Promise((e,r)=>{let i=setTimeout(()=>{r(new d(t))},t);n=i,u(i)});return Promise.race([e,r]).finally(()=>{clearTimeout(n)})}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return s}});
2
+ //# sourceMappingURL=deadline-Cbg2cbUw.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deadline-Cbg2cbUw.cjs","names":["SESSION_ID_KEY","TAB_ID_KEY","require_constants","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","resolveIdentity","contextId","now","sessionId","rawSession","parsed","session","tabId","persistTabId","SessionTouch","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work"],"sources":["../src/utils/identity.ts","../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/identity.ts\n//\n// Makes and keeps the session, tab, and context correlation identifiers. In a\n// sandboxed iframe and in private mode, Storage throws instead of returning null.\n// An unguarded read breaks the library at import.\n\nimport {\n BYTE_VALUE_COUNT,\n ID_BYTE_LENGTH,\n SESSION_ID_KEY,\n SESSION_IDLE_MS,\n SESSION_TOUCH_MS,\n TAB_ID_KEY,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Correlation identifiers attached to log records across session, tab, and realm scopes. */\nexport interface Identity {\n /** Origin-wide user session identifier surviving across tabs until idle expiration. */\n sessionId: string;\n /** Browser tab or desktop window identifier surviving document reloads. */\n tabId: string;\n /** Unique execution realm identifier regenerated on every document load. */\n contextId: string;\n}\n\n/** The three Storage methods that identity and journey code use. */\nexport interface KeyValueStore {\n /**\n * Reads one value.\n * @param key Storage key.\n * @returns Stored value, or null.\n */\n getItem(key: string): string | null;\n /**\n * Writes one value.\n * @param key Storage key.\n * @param value Value to write.\n */\n setItem(key: string, value: string): void;\n /**\n * Removes one value.\n * @param key Storage key.\n */\n removeItem(key: string): void;\n}\n\n/** Stores for identity and journey keys. A getter can throw in a sandboxed frame. */\nexport interface IdentityStores {\n /** Store that lasts across tabs and reloads. */\n local(): KeyValueStore;\n /** Store that lasts for one tab. */\n session(): KeyValueStore;\n}\n\n/** Stores that write to the browser. The `identity: \"storage\"` option uses them. */\nexport const BROWSER_STORES: IdentityStores = {\n local: () => localStorage,\n session: () => sessionStorage,\n};\n\n/**\n * Creates stores that keep values in memory only. The `identity: \"memory\"` option uses them.\n * @returns Stores that write nothing to the browser.\n */\nexport function memoryStores(): IdentityStores {\n const wrap = (map: Map<string, string>): KeyValueStore => ({\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n });\n\n const localStore = wrap(new Map());\n const sessionStore = wrap(new Map());\n\n return { local: () => localStore, session: () => sessionStore };\n}\n\n/**\n * Generates a random lowercase hexadecimal string of the specified byte length.\n * It uses crypto.getRandomValues when it is available. If not, it uses Math.random.\n * @param byteLength Number of random bytes to generate.\n * @returns Hexadecimal string of length byteLength * 2.\n */\nexport function randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < byteLength; i++) {\n bytes[i] = Math.floor(Math.random() * BYTE_VALUE_COUNT);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Generates a unique identifier string using crypto.randomUUID or randomHex fallback.\n * @param diagnostics Diagnostics reporter. It counts a blocked crypto.randomUUID call.\n * @returns UUID or random hex identifier.\n */\nexport function newId(diagnostics: Diagnostics): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // A sandbox can block crypto.randomUUID with a SecurityError. The method exists,\n // but the call throws. Count the fault. A report on each id is noise.\n diagnostics.count(\"platform.api_blocked\");\n }\n return randomHex(ID_BYTE_LENGTH);\n}\n\n/**\n * Reads a value from the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param diagnostics Diagnostics reporter.\n * @returns Stored string value or null if unreadable or absent.\n */\nfunction safeRead(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n diagnostics: Diagnostics,\n): string | null {\n return (\n diagnostics.guard(\"storage.unavailable\", `The library could not read ${store}Storage.`, () =>\n stores[store]().getItem(key),\n ) ?? null\n );\n}\n\n/**\n * Writes a key-value pair to the local or session store. Reports a storage error to diagnostics.\n * @param stores Identity stores.\n * @param store Storage target (\"local\" or \"session\").\n * @param key Storage key.\n * @param value String value to store.\n * @param diagnostics Diagnostics reporter.\n */\nfunction safeWrite(\n stores: IdentityStores,\n store: \"local\" | \"session\",\n key: string,\n value: string,\n diagnostics: Diagnostics,\n): void {\n diagnostics.guard(\n \"storage.unavailable\",\n `The library could not write to ${store}Storage.`,\n () => {\n stores[store]().setItem(key, value);\n },\n );\n}\n\n/**\n * Resolves or initializes session, tab, and context identifiers for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n * @returns Populated Identity object.\n */\nexport function resolveIdentity(\n diagnostics: Diagnostics,\n stores: IdentityStores = BROWSER_STORES,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n let sessionId = newId(diagnostics);\n const rawSession = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (rawSession) {\n try {\n const parsed = JSON.parse(rawSession) as {\n id?: string;\n lastSeenAt?: number;\n };\n if (parsed.id && now - (parsed.lastSeenAt ?? 0) < SESSION_IDLE_MS) {\n sessionId = parsed.id;\n }\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n }\n }\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(stores, \"local\", SESSION_ID_KEY, session, diagnostics);\n\n let tabId = safeRead(stores, \"session\", TAB_ID_KEY, diagnostics) ?? \"\";\n if (!tabId) {\n tabId = newId(diagnostics);\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n }\n\n return { sessionId, tabId, contextId };\n}\n\n/**\n * Writes a new tab id to the session store.\n * @param tabId New tab identifier.\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\nexport function persistTabId(\n tabId: string,\n diagnostics: Diagnostics,\n stores: IdentityStores,\n): void {\n safeWrite(stores, \"session\", TAB_ID_KEY, tabId, diagnostics);\n}\n\n/**\n * Writes the last-seen timestamp of the session. `SESSION_TOUCH_MS` sets the throttle.\n * The instance keeps the throttle state, not the module. Two runtimes in one document\n * must not block the session writes of each other.\n */\nexport class SessionTouch {\n /** Epoch milliseconds of the last write this instance made. */\n private lastTouchAt = 0;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param stores Identity stores.\n */\n constructor(\n private diagnostics: Diagnostics,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /**\n * Writes the session activity time to the local store. It writes one time in each throttle window.\n * @param sessionId Active session identifier.\n */\n touch(sessionId: string): void {\n const now = Date.now();\n\n if (now - this.lastTouchAt < SESSION_TOUCH_MS) {\n return;\n }\n\n this.lastTouchAt = now;\n const session = JSON.stringify({ id: sessionId, lastSeenAt: now });\n safeWrite(this.stores, \"local\", SESSION_ID_KEY, session, this.diagnostics);\n }\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"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"}
@@ -0,0 +1,19 @@
1
+ //#region src/utils/error-like.ts
2
+ var e = /* @__PURE__ */ new Set([
3
+ "name",
4
+ "message",
5
+ "stack",
6
+ "cause"
7
+ ]);
8
+ function t(e) {
9
+ return typeof e == "string" || typeof e == "number" || typeof e == "boolean";
10
+ }
11
+ function n(e) {
12
+ if (typeof e != "object" || !e) return !1;
13
+ let t = e;
14
+ return typeof t.name == "string" && typeof t.message == "string" && (t.stack === void 0 || typeof t.stack == "string");
15
+ }
16
+ //#endregion
17
+ export { t as n, n as r, e as t };
18
+
19
+ //# sourceMappingURL=error-like-Ywo5uRHo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-like-Ywo5uRHo.js","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/** Standard fields of an error. The library writes the other own fields as error data. */\nexport const ERROR_OWN_KEYS: ReadonlySet<string> = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * Tests if a value is a field that error data keeps. An object field, for example the\n * config of an AxiosError, holds credentials and request bodies.\n * @param value Field value.\n * @returns True for a string, a number or a boolean.\n */\nexport function isDataField(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\n/** The fields of an error that the library reads. */\nexport interface ErrorLike {\n /** Error class name, for example \"TypeError\". */\n name: string;\n /** Error message. */\n message: string;\n /** Stack trace text. */\n stack?: string;\n}\n\n/**\n * Tests if a value has the shape of an error.\n * A getter on a hostile value can throw. Call this function inside a diagnostics guard.\n * @param value Value to test.\n * @returns True for an object with a string name, a string message and a string or no stack.\n */\nexport function isErrorLike(value: unknown): value is ErrorLike {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n return (\n typeof candidate.name === \"string\" &&\n typeof candidate.message === \"string\" &&\n (candidate.stack === undefined || typeof candidate.stack === \"string\")\n );\n}\n"],"mappings":";AAMA,IAAaA,oBAAsC,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAS;AAAO,CAAC;AAQhG,SAAgBC,EAAY,GAAyB;CACnD,OAAO,OAAOC,KAAU,YAAY,OAAOA,KAAU,YAAY,OAAOA,KAAU;AACpF;AAkBA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAGT,IAAME,IAAYF;CAClB,OACE,OAAOE,EAAU,QAAS,YAC1B,OAAOA,EAAU,WAAY,aAC5BA,EAAU,UAAU,KAAA,KAAa,OAAOA,EAAU,SAAU;AAEjE"}
@@ -0,0 +1,2 @@
1
+ var e=new Set([`name`,`message`,`stack`,`cause`]);function t(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function n(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.name==`string`&&typeof t.message==`string`&&(t.stack===void 0||typeof t.stack==`string`)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=error-like-gGRx2s36.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-like-gGRx2s36.cjs","names":["ERROR_OWN_KEYS","isDataField","value","isErrorLike","candidate"],"sources":["../src/utils/error-like.ts"],"sourcesContent":["// src/utils/error-like.ts\n//\n// Detects an error by its shape. An error from another realm, for example an iframe,\n// fails `instanceof Error`.\n\n/** Standard fields of an error. The library writes the other own fields as error data. */\nexport const ERROR_OWN_KEYS: ReadonlySet<string> = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * Tests if a value is a field that error data keeps. An object field, for example the\n * config of an AxiosError, holds credentials and request bodies.\n * @param value Field value.\n * @returns True for a string, a number or a boolean.\n */\nexport function isDataField(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\n/** The fields of an error that the library reads. */\nexport interface ErrorLike {\n /** Error class name, for example \"TypeError\". */\n name: string;\n /** Error message. */\n message: string;\n /** Stack trace text. */\n stack?: string;\n}\n\n/**\n * Tests if a value has the shape of an error.\n * A getter on a hostile value can throw. Call this function inside a diagnostics guard.\n * @param value Value to test.\n * @returns True for an object with a string name, a string message and a string or no stack.\n */\nexport function isErrorLike(value: unknown): value is ErrorLike {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n return (\n typeof candidate.name === \"string\" &&\n typeof candidate.message === \"string\" &&\n (candidate.stack === undefined || typeof candidate.stack === \"string\")\n );\n}\n"],"mappings":"AAMA,IAAaA,EAAsC,IAAI,IAAI,CAAC,OAAQ,UAAW,QAAS,OAAO,CAAC,EAQhG,SAAgBC,EAAY,EAAyB,CACnD,OAAO,OAAOC,GAAU,UAAY,OAAOA,GAAU,UAAY,OAAOA,GAAU,SACpF,CAkBA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAGT,IAAME,EAAYF,EAClB,OACE,OAAOE,EAAU,MAAS,UAC1B,OAAOA,EAAU,SAAY,WAC5BA,EAAU,QAAU,IAAA,IAAa,OAAOA,EAAU,OAAU,SAEjE"}
@@ -0,0 +1,3 @@
1
+ require("./constants-Br3b89Wg.cjs");const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-D4wu1eIF.cjs"),n=require("./storm-Y-yuBhvv.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
2
+ `)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count:0};constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(e,t,i){if(!n.t(this.window,20,this.ctx.diagnostics,`errors`))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<5e3){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
3
+ //# sourceMappingURL=errors-CpGRhhIf.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-CpGRhhIf.cjs","names":["isErrorLike","stripUrlQuery","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"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"}
@@ -1,8 +1,23 @@
1
- import "./constants-Bu49bm39.js";
2
- import { r as e } from "./platform-BwbMRwHm.js";
3
- import { t } from "./storm-DJkEZP_8.js";
1
+ import "./constants-DM94FjVX.js";
2
+ import { r as e } from "./error-like-Ywo5uRHo.js";
3
+ import { r as t } from "./platform-IHBZGqUe.js";
4
+ import { t as n } from "./storm-BTw0J6eE.js";
4
5
  //#region src/capture/errors.ts
5
- var n = class {
6
+ function r(t) {
7
+ if (e(t)) {
8
+ let e = (t.stack ?? "").split("\n")[1] ?? "";
9
+ return {
10
+ message: t.message,
11
+ key: `${t.name}|${t.message}|${e}`
12
+ };
13
+ }
14
+ let n = String(t);
15
+ return {
16
+ message: n,
17
+ key: `${typeof t}|${n}|`
18
+ };
19
+ }
20
+ var i = class {
6
21
  ctx;
7
22
  name = "errors";
8
23
  installed = !1;
@@ -20,24 +35,24 @@ var n = class {
20
35
  uninstall() {
21
36
  this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
22
37
  }
23
- onError = (t) => {
24
- let n = t.target, r = n?.src ?? n?.href ?? "";
38
+ onError = (e) => {
39
+ let n = e.target, r = n?.src ?? n?.href ?? "";
25
40
  if (n !== null && n !== globalThis && r !== "") {
26
41
  if (!this.ctx.config.capture.resourceErrors) return;
27
- let t = this.ctx.config.capture.fullUrls ? r : e(r);
42
+ let e = this.ctx.config.capture.fullUrls ? r : t(r);
28
43
  this.ctx.breadcrumbs.push({
29
44
  t: Date.now(),
30
45
  category: "http",
31
- message: `resource failed: ${t}`
46
+ message: `resource failed: ${e}`
32
47
  }), this.ctx.logger.warn("resource failed to load", {
33
48
  "error.type": "resource",
34
- "resource.url": t,
49
+ "resource.url": e,
35
50
  "resource.tag": n.tagName.toLowerCase()
36
51
  });
37
52
  return;
38
53
  }
39
54
  if (!this.ctx.config.capture.errors) return;
40
- let i = t, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
55
+ let i = e, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
41
56
  this.report("window.onerror", o, {
42
57
  "error.source": i.filename,
43
58
  "error.line": i.lineno,
@@ -47,29 +62,33 @@ var n = class {
47
62
  onRejection = (e) => {
48
63
  this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
49
64
  };
50
- report(e, n, r) {
51
- if (!t(this.window, 20, this.ctx.diagnostics, "errors")) return;
52
- let i = Date.now(), a = n instanceof Error ? n : Error(String(n)), o = (a.stack ?? "").split("\n")[1] ?? "", s = `${a.name}|${a.message}|${o}`, c = this.seen.get(s);
53
- if (c && i - c.at < 5e3) {
54
- c.count++, c.at = i;
65
+ report(e, t, i) {
66
+ if (!n(this.window, 20, this.ctx.diagnostics, "errors")) return;
67
+ let a = Date.now(), { message: o, key: s } = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read the error reason. It records the error without its message.", () => r(t)) ?? {
68
+ message: "",
69
+ key: `${typeof t}||`
70
+ }, c = this.seen.get(s);
71
+ if (c && a - c.at < 5e3) {
72
+ c.count++, c.at = a;
55
73
  return;
56
74
  }
57
75
  let l = c ? c.count - 1 : 0;
58
76
  if (this.seen.delete(s), this.seen.set(s, {
59
- at: i,
77
+ at: a,
60
78
  count: 1
61
79
  }), this.seen.size > 200) {
62
80
  let [e] = this.seen.keys();
63
81
  this.seen.delete(e);
64
82
  }
65
- this.ctx.logger.error(a.message === "" ? e : a.message, a, {
66
- ...r,
83
+ let u = t === void 0 ? Error(o) : t;
84
+ this.ctx.logger.error(o === "" ? e : o, u, {
85
+ ...i,
67
86
  "error.captured_by": e,
68
87
  "error.suppressed_count": l
69
88
  });
70
89
  }
71
90
  };
72
91
  //#endregion
73
- export { n as ErrorCapture };
92
+ export { i as ErrorCapture };
74
93
 
75
- //# sourceMappingURL=errors-Dnc-X4Ec.js.map
94
+ //# sourceMappingURL=errors-DH4QJS0u.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DH4QJS0u.js","names":["isErrorLike","stripUrlQuery","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless you set fullUrls.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n if (!allowInWindow(this.window, ERROR_STORM_MAX_PER_WINDOW, this.ctx.diagnostics, \"errors\")) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests whether a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF"}
1
+ {"version":3,"file":"global-scope-BN-Io_yv.cjs","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests if a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":"AAyBA,SAAgBA,EAAY,EAA0B,CACpD,IAAMC,EAAS,OAAO,IAAIC,CAAG,EACvBC,EAAQ,WACRC,MAAsBD,EAAMF,IAAW,EAE7C,MAAO,CACL,IAAI,EAAI,CAEN,EAAMA,GAAUG,EAAM,EAAI,EAE1B,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAMJ,GAAUG,EAAM,EAAI,CAC5B,CACF,EACA,SAAYA,EAAM,EAAI,CACxB,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"global-scope-dp2jADRl.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests whether a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
1
+ {"version":3,"file":"global-scope-dp2jADRl.js","names":["globalScope","symbol","key","store","depth","fn"],"sources":["../src/utils/global-scope.ts"],"sourcesContent":["// src/utils/global-scope.ts\n//\n// Counts open scopes on a global symbol. Two copies of the library on one page then share the\n// count. Without it, one copy captures the requests and the console lines of the other copy.\n\n/** Scope that a function runs inside. */\nexport interface GlobalScope {\n /**\n * Runs a function inside the scope. The scope covers only the synchronous part of the function.\n * @param fn Function to run.\n * @returns The return value of the function.\n */\n run<T>(fn: () => T): T;\n /**\n * Tests if a scope is open.\n * @returns True while a function runs inside the scope.\n */\n open(): boolean;\n}\n\n/**\n * Makes a scope whose count is on a global symbol.\n * @param key Key of the global symbol.\n * @returns The scope.\n */\nexport function globalScope(key: string): GlobalScope {\n const symbol = Symbol.for(key);\n const store = globalThis as unknown as Record<symbol, number | undefined>;\n const depth = (): number => store[symbol] ?? 0;\n\n return {\n run(fn) {\n // A count stays correct when one scope opens inside another.\n store[symbol] = depth() + 1;\n\n try {\n return fn();\n } finally {\n store[symbol] = depth() - 1;\n }\n },\n open: () => depth() > 0,\n };\n}\n"],"mappings":";AAyBA,SAAgBA,EAAY,GAA0B;CACpD,IAAMC,IAAS,OAAO,IAAIC,CAAG,GACvBC,IAAQ,YACRC,UAAsBD,EAAMF,MAAW;CAE7C,OAAO;EACL,IAAI,GAAI;GAEN,EAAMA,KAAUG,EAAM,IAAI;GAE1B,IAAI;IACF,OAAOC,EAAG;GACZ,UAAU;IACR,EAAMJ,KAAUG,EAAM,IAAI;GAC5B;EACF;EACA,YAAYA,EAAM,IAAI;CACxB;AACF"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-B28fDv2F.cjs"),t=require("./sampling-E4x92Nn2.cjs"),n=require("./sanitize-BMhh8ghJ.cjs"),r=require("./platform-D_XkVIF6.cjs"),i=require("./unref-CU9Nyz_9.cjs");function a(t){return Math.round((performance.now()-t)*e.F)/e.F}function o(e,t,n,r,i){e.logMetric(`${t}.duration`,a(n),`ms`,`histogram`,{status:r,...i})}function s(e,t,n,r,i){e.error(`${t} failed`,r,{"action.duration_ms":a(n),status:`FAILURE`,...i})}function c(e,t,n,r){let i=performance.now();try{let a=n();return o(e,t,i,`SUCCESS`,r),a}catch(n){throw s(e,t,i,n,r),n}}async function l(e,t,n,r){let i=performance.now();try{let a=await n();return o(e,t,i,`SUCCESS`,r),a}catch(n){throw s(e,t,i,n,r),n}}function u(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(n??typeof e)}function d(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var f=class t{bind;namespace;options;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>c(this,e,t,n);timeAsync=(e,t,n)=>l(this,e,t,n);write(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;if(!i.builder.isEnabled(e)){this.mirrors(i,e)&&this.print(i,e,n,r,void 0,null);return}let{record:a,dropped:o}=i.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&o!==`redact`&&i.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.print(i,e,n,r,void 0,a),i.emit(a)}writeError(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;let a=i.builder.isEnabled(e);if(!a&&!this.mirrors(i,e))return;let o=r===void 0&&d(n),s=o?n:r,c=o||n===void 0?void 0:u(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:l}=i.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...s,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:i.breadcrumbs.snapshot()}});this.print(i,e,t,s,c,l),i.emit(l)}print(e,t,n,r,i,a){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},p={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},m=class{settings;diagnostics;constructor(e,t){this.settings=e,this.diagnostics=t}update(e){this.settings=e}accepts(t){return this.settings.level!==null&&e.at[t]>=e.at[this.settings.level]}write(t,r,i,a,o){if(!this.accepts(r)||typeof console>`u`||n.a())return;let s=`%c[%s]%c[${r}]%c`,{styles:c}=this.settings,l=p[r];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${l}.`,()=>{let u=[];o!==void 0&&u.push(o),a!==void 0&&u.push(n.n(a,e.Ct,this.diagnostics)),n.o(()=>{console[l](s,c.namespace,t,c[r],``,i,...u)})})}},h=class{value=0;next(){return++this.value}reset(){this.value=0}},g=/^[0-9a-f]{32}$/,_=/^[0-9a-f]{16}$/,v=/[1-9a-f]/;function y(e){return g.test(e.traceId)&&v.test(e.traceId)&&_.test(e.spanId)&&v.test(e.spanId)}function b(){return t.d(16)}function x(){return t.d(8)}function S(){return{traceId:b(),spanId:x(),traceFlags:1,startedAt:Date.now()}}function C(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var w=class{diagnostics;maxAgeMs;load;ambient=S();otel;constructor(t,n=e.fn,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),C(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(y(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=S(),C(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.dn]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},T=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function E(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function D(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||E(t)?t:(r.report(`config.invalid`,`serializer must be "${e.qt}", "ecs" or an implementation. The library uses "${e.qt}".`),e.qt)}var O=new Set(Object.keys(e.D));function k(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)O.has(e)?typeof i==`string`?n[e]=i:t.report(`config.invalid`,`console.styles.${e} must be a string. The library keeps the style in force.`):t.report(`config.invalid`,`The library ignores the unknown console.styles key "${e}". Check the spelling.`);return n}function A(t,n,r){return t===void 0?n:t===!1?{level:null,styles:n.styles}:t===!0?{level:e.E,styles:n.styles}:typeof t==`string`?{level:t,styles:n.styles}:typeof t!=`object`||!t?(r.report(`config.invalid`,`console must be a boolean, a level or an object. The console settings in force stay.`),n):{level:t.level??n.level??`DEBUG`,styles:{...n.styles,...k(t.styles,r)}}}function j(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:D(t.serializer,r?.serializer,n),console:A(t.console,i.console,n),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(a.transport!==void 0&&typeof a.transport!=`function`&&(n.report(`config.invalid`,`transport must be a function. The library ignores the value.`),a.transport=i.transport),a.transportOnExit!==void 0&&typeof a.transportOnExit!=`function`&&(n.report(`config.invalid`,`transportOnExit must be a function. The library ignores the value.`),a.transportOnExit=i.transportOnExit),a.endpoint===``)a.transport===void 0&&n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}.`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.gn}'.`),e.gn);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(o)}. The library uses 1.`),a.sampling.defaultRate=1);let s=a.sampling.remoteMaxRate;(typeof s!=`number`||!(s>=0&&s<=1))&&(n.report(`config.invalid`,`sampling.remoteMaxRate must be 0..1. The value is ${String(s)}. The library uses 1.`),a.sampling.remoteMaxRate=1);let c=Object.entries(a.sampling.rates);for(let[e,t]of c)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1. The value is ${String(t)}. The library uses 1.`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),M(t,n),a}function M(t,n){let r=new Set([...Object.keys(e.j),...e.mn]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.hn[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function N(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var P=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},ee=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,r,i,a){let o=this.count(t),s=Date.now();if(s-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,s);let c={code:t,message:r,detail:i,cause:a,at:s,count:o},{handler:l}=this;if(l)try{n.o(()=>{l(c)})}catch(t){this.count(`handler.threw`),typeof console<`u`&&n.o(()=>{console.warn(`${e.st} The onDiagnostic handler threw an error.`,t)})}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},te={maxAgeMs:e.nt,endOnOwnerClose:!1,urlParam:e.it};function F(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function I(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function L(e){if(typeof e!=`object`||!e)return null;let t=F(e,`id`),n=F(e,`name`),r=I(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:F(e,`parentId`),ownerContextId:F(e,`ownerContextId`)??``}}function R(e){if(typeof e!=`object`||!e)return null;let t=F(e,`i`),n=F(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:I(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function z(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}var B=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.o){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.rt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.l(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=z(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=L(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return R(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.rt):this.stores.session().setItem(e.rt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=r,i.t(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.rt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.a(r.call(n),e.vt)))?.customData?.[e._t];return typeof i==`string`?i:null}};function V(e){return e}var H=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;if(!n.enabled)return!1;let r=this.deps.remote.sampling?.minLevel()??n.minLevel;return e.at[t]>=e.at[r]}build(i){let{config:a,diagnostics:o,tracing:s,journey:c,sequence:l,limits:u,remote:d}=this.deps;if(!this.isEnabled(i.level))return o.count(`record.dropped_by_level`),{record:null,dropped:`level`};let f=s.resolve(),p=c.current();if(!t.r({level:i.level,type:i.type,namespace:i.namespace,journeyId:p?.id??``,traceId:f.traceId},a,d.sampling?.current()??null))return o.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let m=l.next(),h=r.t(o),g=a.capture.fullUrls?h:r.r(h),_,v=0;try{let e=n.r(this.deps.context.getAll(),u,o),t=n.r(i.scoped??{},u,o),r=n.r(i.payload??{},u,o);v=e.bytes+t.bytes+r.bytes,_={...V(e.value),...V(t.value),...V(r.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),_={[e.d]:!0}}_[e.l]=i.type,_[e.c]=m,_[e.n]=i.namespace,_[e.u]=g,p&&(_[e.a]=p.id,_[e.o]=p.name,p.parentId!==void 0&&(_[e.s]=p.parentId));let y=n.i(i.body,u.maxBodyChars);y!==i.body&&o.count(`record.truncated`);let b={timeUnixNano:t.m(),traceId:f.traceId,spanId:f.spanId,traceFlags:f.traceFlags,severityNumber:e.Zt[i.level],severityText:i.level,body:y,attributes:_,resource:this.resource()},x=a.redact;if(x){let e=o.guard(`record.sanitize_failed`,`The redact hook threw an error.`,()=>x(b));if(e===null)return o.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==b){if(t.p(e)){let t=n.r(e.attributes,u,o);b={...e,attributes:V(t.value)},v=t.bytes}else o.report(`record.sanitize_failed`,`The redact hook returned a value that is not a record. The library keeps the original record.`)}}if(v>u.maxRecordBytes){o.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped them.`,{bytes:v,body:b.body});let t={[e.l]:i.type,[e.c]:m,[e.n]:i.namespace,[e.u]:g,[e.i]:!0,[e.r]:v};p&&(t[e.a]=p.id,t[e.o]=p.name),b.attributes=t}return{record:b}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Pt]:t.serviceName,[e.Ft]:t.serviceVersion,[e.At]:t.environment,[e.zt]:e.ln,[e.Bt]:e.un,[e.Rt]:e.cn,[e.jt]:r.platform,[e.It]:n.sessionId,[e.Lt]:n.tabId,[e.kt]:n.contextId,[e.Ot]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Nt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Mt]:r.openfinName}},this.resourceCache}},U={errors:async()=>(await Promise.resolve().then(()=>require("./errors-C78ZTjet.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-CZ0aFUsy.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-CsE2y_fQ.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-B2FYsEAU.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-DahhqM6u.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-PKzc-FmR.cjs"))).ConsoleCapture},W=Symbol.for(e.Wt),G=Symbol.for(e.Gt),K=class n{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new P;breadcrumbs;tracing;sequence=new h;journey;builder;remote={sampling:null};console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;started=Promise.resolve();ready=!1;destroyed=!1;lastGapAt=0;constructor(n){this.diagnostics=new ee(n.onDiagnostic),this.platform=r.n(this.diagnostics),this.config=j(n,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.c():t.o,this.identity=t.f(this.diagnostics,this.stores),this.sessionTouch=new t.s(this.diagnostics,this.stores),this.breadcrumbs=new T(50),this.tracing=new w(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new m(this.config.console,this.diagnostics),this.journey=new B(te,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new H({remote:this.remote,config:this.config,limits:e.Ct,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{n.acceptDirect(e,t)})})};static current(){return globalThis[W]??null}static stopped(){return globalThis[G]??null}isDestroyed(){return this.destroyed}static configure(e){let t=n.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let r=new n(e);return globalThis[W]=r,Reflect.deleteProperty(globalThis,G),r.init(),r}reconfigure(e){let t=this.keepDestination(e);N(this.config,j(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup. It stays ${e}.`,{requested:this.config.storage}),this.config.storage=e)}keepDestination(e){if(this.senderLoad===void 0)return e;let t=e;return`transport`in e&&e.transport===void 0!=(this.config.transport===void 0)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove transport after the delivery stack loads. The transport in force stays.`),t={...t},delete t.transport),(t.endpoint===null||t.endpoint===``)&&this.config.transport===void 0&&(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),t={...t,endpoint:void 0}),t}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();this.started=this.boot(),await this.started,await e}async boot(){try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-CUXRY0JR.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()},remote:this.remote});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!(this.config.endpoint||this.config.transport!==void 0)||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-B6ufz26f.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,remote:this.remote});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`),n.longFrames&&r.push(`longFrames`),(Array.isArray(n.console)?n.console.length>0:n.console)&&r.push(`console`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new f(()=>this,e.C),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${e.name} capture.`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,U[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,n.current()===this&&(Reflect.deleteProperty(globalThis,W),globalThis[G]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad&&this.pushCapped(this.pendingRecords,e)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let n of e)t.p(n)?t.n(n,this.config,this.remote.sampling?.current()??null)?this.deliver(n):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new f(()=>this,e.tn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.l(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,t.u(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.ready||await this.started,this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}};function q(){let e=[],t=[],n={status:200};return{transport:r=>(e.push(r),n.status>=200&&n.status<300&&t.push(r),Promise.resolve({...n})),records:()=>t.flatMap(e=>[...e.records]),batches:()=>[...e],clear:()=>{e.length=0,t.length=0},respondWith:(e,t)=>{n=t===void 0?{status:e}:{status:e,retryAfterMs:t}}}}var J=new Map;function Y(){return(K.current()??K.stopped())||K.configure({})}function X(e){K.configure(e)}function Z(e,t){if(t)return new f(Y,e,t);let n=J.get(e);return n||(n=new f(Y,e),J.set(e,n)),n}function Q(){return Z(`app`)}function ne(e,t){Q().trace(e,t)}function re(e,t){Q().debug(e,t)}function ie(e,t){Q().info(e,t)}function ae(e,t){Q().warn(e,t)}function oe(e,t,n){Q().error(e,t,n)}function se(e,t){Q().logAction(e,t)}function ce(e,t){Q().logEvent(e,t)}function le(e,t,n,r,i){Q().logMetric(e,t,n,r,i)}function ue(e,t,n){return Q().timeSync(e,t,n)}function de(e,t,n){return Q().timeAsync(e,t,n)}function fe(e,t){Y().context.set(e,t)}function pe(e){Y().context.setMany(e)}function me(e){Y().context.remove(e)}function he(e,t){return Y().journey.start(e,t)}function ge(){Y().journey.end()}function _e(){return Y().journey.current()}function ve(){return Y().journey.getToken()}function ye(e){return Y().journey.adopt(e,`manual`,!0)}function be(e){Y().registerWorker(e)}function $(){Y().tracing.rotate(`explicit`)}function xe(){return Y().tracing.headers()}function Se(){return Y().flush()}function Ce(){return Y().queueDepth()}function we(){return Y().diagnostics.snapshot()}async function Te(){await K.current()?.destroy()}exports.OneLogger=f,exports.adoptJourney=ye,exports.configure=X,exports.createMemoryTransport=q,exports.currentJourney=_e,exports.debug=re,exports.endJourney=ge,exports.error=oe,exports.flush=Se,exports.getDiagnosticCounters=we,exports.getJourneyToken=ve,exports.getLogger=Z,exports.getQueueDepth=Ce,exports.getTraceHeaders=xe,exports.info=ie,exports.logAction=se,exports.logEvent=ce,exports.logMetric=le,exports.registerWorker=be,exports.removeContext=me,exports.setContext=fe,exports.setContextMap=pe,exports.shutdown=Te,exports.startJourney=he,exports.startTrace=$,exports.timeAsync=de,exports.timeSync=ue,exports.trace=ne,exports.warn=ae;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-Br3b89Wg.cjs"),t=require("./error-like-gGRx2s36.cjs"),n=require("./sampling-BI15ds9D.cjs"),r=require("./sanitize-DSIP7amZ.cjs"),i=require("./deadline-Cbg2cbUw.cjs"),a=require("./platform-D4wu1eIF.cjs"),o=require("./journey-CE2EcwHW.cjs");function s(t){return Math.round((performance.now()-t)*e.L)/e.L}function c(e,t,n,r,i){e.logMetric(`${t}.duration`,n,`ms`,`histogram`,{status:r,...i})}function l(e,t,n,r,i){let a=s(n);e.error(`${t} failed`,r,{"action.duration_ms":a,status:`FAILURE`,...i}),c(e,t,a,`FAILURE`,i)}function u(e,t,n,r){let i=performance.now();try{let a=n();return c(e,t,s(i),`SUCCESS`,r),a}catch(n){throw l(e,t,i,n,r),n}}async function d(e,t,n,r){let i=performance.now();try{let a=await n();return c(e,t,s(i),`SUCCESS`,r),a}catch(n){throw l(e,t,i,n,r),n}}var f=[e.T,e.in];function p(e,n){let r=n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>{if(!(e instanceof Error)&&!t.r(e))return;let n=Error(e.message);return n.name=e.name,n.stack=e.stack,n});if(r)return r;let i=n.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(i??typeof e)}function m(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function h(e,n){if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return e;if(typeof e==`object`&&e)return n.guard(`record.sanitize_failed`,`The library could not read the properties of the error reason.`,()=>{let n=e,r=t.r(e),i={},a=0;for(let e of Object.keys(n)){let o=n[e];(!r||!t.t.has(e))&&t.n(o)&&(i[e]=o,a++)}return a===0?void 0:i})}function g(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function _(e){return f.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function v(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var y=class t{bind;namespace;options;levelType;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n,this.levelType=_(t)}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,this.levelType,e,t)};debug=(e,t)=>{this.write(`DEBUG`,this.levelType,e,t)};info=(e,t)=>{this.write(`INFO`,this.levelType,e,t)};warn=(e,t)=>{this.write(`WARN`,this.levelType,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.P,i=`gauge`,a)=>{if(!Number.isFinite(n)){this.bind().diagnostics.report(`record.dropped_malformed`,`The metric value is not a finite number. The library dropped the metric.`,{"metric.name":t});return}let o={...v(a,this.bind().diagnostics),"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i};this.write(`INFO`,`metric`,t,o,!0)};timeSync=(e,t,n)=>u(this,e,t,n);timeAsync=(e,t,n)=>d(this,e,t,n);write(e,t,n,r,i=!1){let a=this.bind();if(a.isDestroyed())return;if(!a.builder.isEnabled(e,t)){this.mirrors(a,e)&&this.print(a,e,n,r,void 0,null);return}let{record:o,dropped:s}=a.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:i?r:v(r,a.diagnostics)}),c=o?o.body:s===`sampling`?n:void 0;t!==`metric`&&c!==void 0&&a.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:c}),this.print(a,e,n,r,void 0,o,s),a.emit(o)}writeError(t,n,r,i){let a=this.bind();if(a.isDestroyed())return;let o=a.builder.isEnabled(t);if(!o&&!this.mirrors(a,t))return;let s=i===void 0&&(a.diagnostics.guard(`record.sanitize_failed`,`The library could not read the error slot.`,()=>g(r))??!1),c=s?r:i,l=s?void 0:r,u=l===void 0?void 0:p(l,a.diagnostics),d=u===void 0?void 0:m(l,u,a.diagnostics);if(!o){this.print(a,t,n,c,d,null);return}let f=u?h(l,a.diagnostics):void 0,{record:_,dropped:y}=a.builder.build({level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...v(c,a.diagnostics),...u?{"error.type":u.name,"error.message":u.message,"error.stack_trace":u.stack}:{},...f===void 0?{}:{[e.o]:f},[e.a]:a.breadcrumbs.snapshot()}});this.print(a,t,n,c,d,_,y),a.emit(_)}print(e,t,n,r,i,a,o){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):o!==`redact`&&o!==`malformed`&&e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},b={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},x=class{settings;diagnostics;constructor(e,t){this.settings=e,this.diagnostics=t}update(e){this.settings=e}accepts(t){return this.settings.level===null||!Object.hasOwn(e.ct,this.settings.level)?!1:e.ct[t]>=e.ct[this.settings.level]}write(t,n,i,a,o){if(!this.accepts(n)||typeof console>`u`||r.a())return;let s=`%c[%s]%c[${n}]%c`,{styles:c}=this.settings,l=b[n];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${l}.`,()=>{let u=[];o!==void 0&&u.push(o),a!==void 0&&u.push(r.n(a,e.Et,this.diagnostics)),r.o(()=>{console[l](s,c.namespace,t,c[n],``,i,...u)})})}},S=class{value=0;next(){return++this.value}},ee=/^[0-9a-f]{32}$/,C=/^[0-9a-f]{16}$/,w=/[1-9a-f]/;function te(e){return ee.test(e.traceId)&&w.test(e.traceId)&&C.test(e.spanId)&&w.test(e.spanId)}function ne(){return i.l(16)}function re(){return i.l(8)}function T(){return{traceId:ne(),spanId:re(),traceFlags:1,startedAt:Date.now()}}function E(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var D=class{diagnostics;maxAgeMs;load;ambient=T();otel;constructor(t,n=e.hn,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),E(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(te(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=T(),E(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.mn]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},O=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}},k=Object.keys(e.ct),ie=[`gzip`,`none`],ae=[`omit`,`same-origin`,`include`],oe=[`auto`,`indexeddb`,`localstorage`,`memory`,`none`],se=[`storage`,`memory`],ce=[`auto`,`sender`,`forwarder`,`off`],le=[`auto`,`provider`,`client`],ue=[`auto`,`context`,`tab`,`origin`],A=[`error`,`warn`,`info`,`log`],de=[`errors`,`rejections`,`resourceErrors`,`fetch`,`xhr`,`interactions`,`navigation`,`webVitals`,`longFrames`,`fullUrls`],fe=`null`,j=`a level name: ${N(k)}`,M=`true, false or a list of ${N(A)}`,pe=`a list of strings and RegExp patterns`,me=`a list of origin URLs such as "https://api.example" and RegExp patterns`,he=`a list of origin URLs such as "https://app.example". For a sandboxed frame, set bus.mode: "sender" in the frame`,ge=`a list of strings`;function N(e){let t=e.map(e=>`"${e}"`);return`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}function P(e){return typeof e==`string`?`"${e}"`:typeof e==`function`?`a function`:typeof e==`object`&&e?`an object`:String(e)}function F(e,t,n,r,i){e.report(`config.invalid`,`${t} must be ${n}. The value is ${P(r)}. The library keeps ${i}.`)}function I(e,t,n,r,i){if(t===void 0)return r;let a=n.find(e=>e===t);return a===void 0?(F(i,e,N(n),t,`"${r}"`),r):a}function L(e,t,n,r){return t===void 0?n:typeof t==`boolean`?t:(F(r,e,`true or false`,t,String(n)),n)}function _e(e,t,n,r){return t===void 0?n:typeof t==`number`&&Number.isFinite(t)&&t>=0?t:(F(r,e,`a finite number of 0 or more`,t,String(n)),n)}function R(e){if(typeof e!=`string`)return;let t=e.toUpperCase();return k.find(e=>e===t)}function ve(e,t,n,r){if(t===void 0)return n;let i=R(t);return i===void 0?(F(r,e,j,t,`"${n}"`),n):i}function z(e,t,n,r,i,a){if(t===void 0)return n;if(!Array.isArray(t))return F(a,e,r,t,`the list in force`),n;let o=[],s=t;for(let t of s){let n=i(t);n===void 0?a.report(`config.invalid`,`The library ignores the ${e} entry ${P(t)}. ${e} must be ${r}.`):o.push(n)}return o}function ye(e){return typeof e==`string`?e:void 0}function be(e){return typeof e==`string`||e instanceof RegExp?e:void 0}function xe(e){return A.find(t=>t===e)}function B(e){if(typeof e==`string`)try{let{origin:t}=new URL(e);return t===fe?void 0:t}catch{return}}function Se(e){return e instanceof RegExp?e:B(e)}function Ce(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function we(e,t,n){if(e!==void 0)return typeof e==`function`||Ce(e)?e:(F(n,`headers`,`an object of strings or a function`,e,`the headers in force`),t)}function Te(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function Ee(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||Te(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Xt}", "ecs" or an implementation. The library uses "${e.Xt}".`),e.Xt)}var De=new Set(Object.keys(e.k));function Oe(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)De.has(e)?typeof i==`string`?n[e]=i:t.report(`config.invalid`,`console.styles.${e} must be a string. The library keeps the style in force.`):t.report(`config.invalid`,`The library ignores the unknown console.styles key "${e}". Check the spelling.`);return n}function ke(e,t,n){if(e===void 0)return t??`DEBUG`;let r=R(e);return r===void 0?(F(n,`console.level`,j,e,`the console level in force`),t):r}function Ae(t,n,r){if(t===void 0)return n;if(t===!1)return{level:null,styles:n.styles};if(t===!0)return{level:e.O,styles:n.styles};if(typeof t==`string`){let e=R(t);return e===void 0?(F(r,`console`,j,t,`the console level in force`),n):{level:e,styles:n.styles}}return typeof t!=`object`||!t?(r.report(`config.invalid`,`console must be a boolean, a level or an object. The console settings in force stay.`),n):{level:ke(t.level,n.level,r),styles:{...n.styles,...Oe(t.styles,r)}}}function je(e,t,n){let r=e??{};return{...t,...r,rates:{...t.rates,...r.rates},alwaysSampleTypes:z(`sampling.alwaysSampleTypes`,r.alwaysSampleTypes,t.alwaysSampleTypes,ge,ye,n),remote:L(`sampling.remote`,r.remote,t.remote,n)}}function Me(e,t,n){let r=e??{};return{mode:I(`bus.mode`,r.mode,ce,t.mode,n),trustedOrigins:z(`bus.trustedOrigins`,r.trustedOrigins,t.trustedOrigins,he,B,n),openFinRole:I(`bus.openFinRole`,r.openFinRole,le,t.openFinRole,n)}}function Ne(e,t,n){return{scope:I(`journey.scope`,(e??{}).scope,ue,t.scope,n)}}function Pe(e,t,n){return e===void 0?t:typeof e==`boolean`?e:Array.isArray(e)?z(`capture.console`,e,[],M,xe,n):(F(n,`capture.console`,M,e,`the value in force`),t)}function Fe(e,t,n){let r=e??{},i={...t,...r,console:Pe(r.console,t.console,n),longFrameThresholdMs:_e(`capture.longFrameThresholdMs`,r.longFrameThresholdMs,t.longFrameThresholdMs,n),ignoreUrls:z(`capture.ignoreUrls`,r.ignoreUrls,t.ignoreUrls,pe,be,n),propagateTraceHeaderTo:z(`capture.propagateTraceHeaderTo`,r.propagateTraceHeaderTo,t.propagateTraceHeaderTo,me,Se,n)};for(let e of de)i[e]=L(`capture.${e}`,r[e],t[e],n);return i}function V(t,n,r){let i=r??e.N,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,enabled:L(`enabled`,t.enabled,i.enabled,n),minLevel:ve(`minLevel`,t.minLevel,i.minLevel,n),compression:I(`compression`,t.compression,ie,i.compression,n),credentials:I(`credentials`,t.credentials,ae,i.credentials,n),headers:`headers`in t?we(t.headers,i.headers,n):i.headers,storage:I(`storage`,t.storage,oe,i.storage,n),identity:I(`identity`,t.identity,se,i.identity,n),serializer:Ee(t.serializer,r?.serializer,n),console:Ae(t.console,i.console,n),sampling:je(t.sampling,i.sampling,n),bus:Me(t.bus,i.bus,n),journey:Ne(t.journey,i.journey,n),capture:Fe(t.capture,i.capture,n)};if(a.transport!==void 0&&typeof a.transport!=`function`&&(n.report(`config.invalid`,`transport must be a function. The library ignores the value.`),a.transport=i.transport),a.transportOnExit!==void 0&&typeof a.transportOnExit!=`function`&&(n.report(`config.invalid`,`transportOnExit must be a function. The library ignores the value.`),a.transportOnExit=i.transportOnExit),a.endpoint===``)a.transport===void 0&&n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}.`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.yn}'.`),e.yn);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(o)}. The library uses 1.`),a.sampling.defaultRate=1);let s=a.sampling.remoteMaxRate;(typeof s!=`number`||!(s>=0&&s<=1))&&(n.report(`config.invalid`,`sampling.remoteMaxRate must be 0..1. The value is ${String(s)}. The library uses 1.`),a.sampling.remoteMaxRate=1);let c=Object.entries(a.sampling.rates);for(let[e,t]of c)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1. The value is ${String(t)}. The library uses 1.`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),Ie(t,n),a}function Ie(t,n){let r=new Set([...Object.keys(e.N),...e._n]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.D){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.N[r]),...e.vn[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function Le(t,n){for(let r of Object.keys(n))e.D.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.D)Object.assign(t[r],n[r])}var Re=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},ze=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.F){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,i,a){let o=this.count(t),s=Date.now();if(s-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,s);let c={code:t,message:n,detail:i,cause:a,at:s,count:o},{handler:l}=this;if(l)try{r.o(()=>{l(c)})}catch(t){this.count(`handler.threw`),typeof console<`u`&&r.o(()=>{console.warn(`${e.ut} The onDiagnostic handler threw an error.`,t)})}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},Be=`error.`,Ve=[e.f,e.s,e.c];function H(e){return e}var He=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t,n){let{config:r}=this.deps;if(!r.enabled)return!1;if(n!==void 0&&e.st.includes(n))return!0;let i=this.deps.remote.sampling?.minLevel()??r.minLevel;return e.ct[t]>=e.ct[i]}build(t){let{config:i,diagnostics:o,tracing:s,journey:c,sequence:l,limits:u,remote:d}=this.deps;if(!this.isEnabled(t.level,t.type))return o.count(`record.dropped_by_level`),{record:null,dropped:`level`};let f=s.resolve(),p=c.current();if(!n.r({level:t.level,type:t.type,namespace:t.namespace,journeyId:p?.id??``,traceId:f.traceId},i,d.sampling?.current()??null))return o.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let m=l.next(),h=a.t(o),g=i.capture.fullUrls?h:a.r(h),_,v=0;try{let e=r.r(this.deps.context.getAll(),u,o),n=r.r(t.scoped??{},u,o),i=r.r(t.payload??{},u,o);v=e.bytes+n.bytes+i.bytes,_={...H(e.value),...H(n.value),...H(i.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),_={[e.p]:!0}}_[e.d]=t.type,_[e.u]=m,_[e.n]=t.namespace,_[e.f]=g,p&&(_[e.s]=p.id,_[e.c]=p.name,p.parentId!==void 0&&(_[e.l]=p.parentId));let y=r.i(t.body,u.maxBodyChars);y!==t.body&&o.count(`record.truncated`);let b={timeUnixNano:n.o(),traceId:f.traceId,spanId:f.spanId,traceFlags:f.traceFlags,severityNumber:e.en[t.level],severityText:t.level,body:y,attributes:_,resource:this.resource()},x=i.redact;if(x){let t;try{t=x(b)}catch(e){return o.report(`record.dropped_by_redact`,`The redact hook threw an error. The library dropped the record.`,void 0,e),{record:null,dropped:`redact`}}if(t===null)return o.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};let i=t??b;if(!n.a(i))return i===b?(o.report(`record.dropped_malformed`,`The redact hook changed the record to a shape that is not a record. The library dropped it.`),{record:null,dropped:`malformed`}):(o.report(`record.dropped_by_redact`,`The redact hook returned a value that is not a record. The library dropped the record.`),{record:null,dropped:`redact`});if(n.i(i.severityText)){if(i!==b){let e=r.r(i.attributes,u,o);b={...i,attributes:H(e.value)},v=e.bytes}b.severityNumber=e.en[b.severityText]}else return o.report(`record.dropped_malformed`,`The redact hook set a severityText that is not a log level. The library dropped the record.`),{record:null,dropped:`malformed`}}if(v>u.maxRecordBytes){o.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped the caller attributes.`,{bytes:v,body:b.body});let n={[e.d]:t.type,[e.u]:m,[e.n]:t.namespace,[e.i]:!0,[e.r]:v};for(let e of Ve)e in b.attributes&&(n[e]=b.attributes[e]);for(let[e,t]of Object.entries(b.attributes))e.startsWith(Be)&&(n[e]=t);let i=r.r(n,u,o).bytes;i>u.maxRecordBytes&&`error.data`in n&&(Reflect.deleteProperty(n,e.o),i=r.r(n,u,o).bytes);let a=b.attributes[e.a];if(a!==void 0){let t=r.r(a,u,o).bytes;i+t<=u.maxRecordBytes&&(n[e.a]=a)}b.attributes=n}return{record:b}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Lt]:t.serviceName,[e.Rt]:t.serviceVersion,[e.Nt]:t.environment,[e.Ht]:e.fn,[e.Ut]:e.pn,[e.Vt]:e.dn,[e.Pt]:r.platform,[e.zt]:n.sessionId,[e.Bt]:n.tabId,[e.Mt]:n.contextId,[e.jt]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.It]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Ft]:r.openfinName}},this.resourceCache}},Ue={errors:async()=>(await Promise.resolve().then(()=>require("./errors-CpGRhhIf.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-BAV7ipyn.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-31eHGwEQ.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-DFuoTQbZ.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-B8VdA_ny.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-BpHfWstv.cjs"))).ConsoleCapture},U=Symbol.for(e.qt),W=Symbol.for(e.Jt);function G(e){return JSON.stringify({...e,webVitalsLoader:e.webVitalsLoader!==void 0,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String)})}function K(e){return{...e,endpoint:null,transport:void 0,transportOnExit:void 0,bus:{...e.bus,mode:`off`}}}function q(t){return t.sdkVersion===e.pn}var J=class t{degraded;static local=null;sdkVersion=e.pn;diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new Re;breadcrumbs;tracing;sequence=new S;journey;builder;remote={sampling:null};console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;started=Promise.resolve();ready=!1;destroyed=!1;lastGapAt=0;constructor(t,n=!1){this.degraded=n,this.diagnostics=new ze(t.onDiagnostic),this.platform=a.n(this.diagnostics),this.config=V(t,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?i.o():i.i,this.identity=i.u(this.diagnostics,this.stores),this.sessionTouch=new i.a(this.diagnostics,this.stores),this.breadcrumbs=new O(50),this.tracing=new D(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new x(this.config.console,this.diagnostics),this.journey=new o.n(o.t,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new He({remote:this.remote,config:this.config,limits:e.Et,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{n.acceptDirect(e,t)})})};static pinned(){return globalThis[U]??null}static current(){let e=t.local;if(e)return e.destroyed?null:e;let n=t.pinned();return n&&q(n)?n:null}static stopped(){let e=t.local;if(e?.destroyed)return e;let n=globalThis[W];return n&&q(n)?n:null}isDestroyed(){return this.destroyed}static configure(e){let n=t.local;if(n&&!n.destroyed)return n.reconfigure(K(e)),n;t.local=null;let r=t.pinned();if(r){if(!q(r))return t.startDegraded(e,r.sdkVersion);if(!r.destroyed)return r.reconfigure(e),r}let i=new t(e);return globalThis[U]=i,Reflect.deleteProperty(globalThis,W),i.init(),i}static startDegraded(n,r){let i=new t(K(n),!0);t.local=i;let a=typeof r==`string`?r:`before 0.9.0`;return i.diagnostics.report(`runtime.version_mismatch`,`Another copy of the library, version ${a}, owns the page runtime. This copy, version ${e.pn}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:a,own:e.pn}),i.init(),i}reconfigure(e){let t=this.keepDestination(e),n=G(this.config.capture);Le(this.config,V(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),G(this.config.capture)!==n&&this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup. It stays ${e}.`,{requested:this.config.storage}),this.config.storage=e)}keepDestination(e){if(this.senderLoad===void 0)return e;let t=e;return`transport`in e&&e.transport===void 0!=(this.config.transport===void 0)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove transport after the delivery stack loads. The transport in force stays.`),t={...t},delete t.transport),(t.endpoint===null||t.endpoint===``)&&this.config.transport===void 0&&(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),t={...t,endpoint:void 0}),t}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();this.started=this.boot(),await this.started,await e}async boot(){try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-CtJWf9QN.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()},remote:this.remote});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!(this.config.endpoint||this.config.transport!==void 0)||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-D0OsyB1c.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,remote:this.remote});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){if(this.degraded)return;let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`),n.longFrames&&r.push(`longFrames`),(Array.isArray(n.console)?n.console.length>0:n.console)&&r.push(`console`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new y(()=>this,e.T),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${e.name} capture.`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,Ue[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,t.pinned()===this&&(Reflect.deleteProperty(globalThis,U),globalThis[W]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad?this.pushCapped(this.pendingRecords,e):this.diagnostics.count(`record.dropped_no_destination`)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let t of e)n.a(t)?n.n(t,this.config,this.remote.sampling?.current()??null)?this.deliver(t):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new y(()=>this,e.in).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=i.s(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,i.c(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.ready||await this.started,this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}};function We(){let e=[],t=[],n={status:200};return{transport:r=>(e.push(r),n.status>=200&&n.status<300&&t.push(r),Promise.resolve({...n})),records:()=>t.flatMap(e=>[...e.records]),batches:()=>[...e],clear:()=>{e.length=0,t.length=0},respondWith:(e,t)=>{n=t===void 0?{status:e}:{status:e,retryAfterMs:t}}}}var Y=new Map;function X(){return(J.current()??J.stopped())||J.configure({})}function Ge(e){J.configure(e)}function Z(e,t){if(t)return new y(X,e,t);let n=Y.get(e);return n||(n=new y(X,e),Y.set(e,n)),n}function Q(){return Z(`app`)}function Ke(e,t){Q().trace(e,t)}function qe(e,t){Q().debug(e,t)}function Je(e,t){Q().info(e,t)}function Ye(e,t){Q().warn(e,t)}function Xe(e,t,n){Q().error(e,t,n)}function Ze(e,t,n){Q().fatal(e,t,n)}function Qe(e,t){Q().logAction(e,t)}function $e(e,t){Q().logEvent(e,t)}function et(e,t,n,r,i){Q().logMetric(e,t,n,r,i)}function tt(e,t,n){return Q().timeSync(e,t,n)}function $(e,t,n){return Q().timeAsync(e,t,n)}function nt(e,t){X().context.set(e,t)}function rt(e){X().context.setMany(e)}function it(e){X().context.remove(e)}function at(e,t){return X().journey.start(e,t)}function ot(){X().journey.end()}function st(){return X().journey.current()}function ct(){return X().journey.getToken()}function lt(e){return X().journey.adopt(e,`manual`,!0)}function ut(e){X().registerWorker(e)}function dt(){X().tracing.rotate(`explicit`)}function ft(){return X().tracing.headers()}function pt(){return X().flush()}function mt(){return X().queueDepth()}function ht(){return X().diagnostics.snapshot()}async function gt(){await J.current()?.destroy()}exports.OneLogger=y,exports.adoptJourney=lt,exports.configure=Ge,exports.createMemoryTransport=We,exports.currentJourney=st,exports.debug=qe,exports.endJourney=ot,exports.error=Xe,exports.fatal=Ze,exports.flush=pt,exports.getDiagnosticCounters=ht,exports.getJourneyToken=ct,exports.getLogger=Z,exports.getQueueDepth=mt,exports.getTraceHeaders=ft,exports.info=Je,exports.logAction=Qe,exports.logEvent=$e,exports.logMetric=et,exports.registerWorker=ut,exports.removeContext=it,exports.setContext=nt,exports.setContextMap=rt,exports.shutdown=gt,exports.startJourney=at,exports.startTrace=dt,exports.timeAsync=$,exports.timeSync=tt,exports.trace=Ke,exports.warn=Ye;
2
2
  //# sourceMappingURL=index.cjs.map