@utk09/ui-observability 0.9.3 → 0.9.5

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 (227) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +199 -96
  3. package/dist/batch-BQFtb3i5.cjs +2 -0
  4. package/dist/batch-BQFtb3i5.cjs.map +1 -0
  5. package/dist/{batch-DDgxg16_.js → batch-BUJh-1jZ.js} +6 -4
  6. package/dist/batch-BUJh-1jZ.js.map +1 -0
  7. package/dist/bus/bus.d.ts +76 -2
  8. package/dist/bus/links.d.ts +9 -2
  9. package/dist/bus/validation.d.ts +7 -0
  10. package/dist/bus-BW6N-pY8.cjs +2 -0
  11. package/dist/bus-BW6N-pY8.cjs.map +1 -0
  12. package/dist/bus-DeOPHWaD.js +647 -0
  13. package/dist/bus-DeOPHWaD.js.map +1 -0
  14. package/dist/capture/network.d.ts +1 -0
  15. package/dist/capture/storm.d.ts +2 -1
  16. package/dist/capture/types.d.ts +5 -0
  17. package/dist/capture/web-socket.d.ts +40 -0
  18. package/dist/{console-BSusX_M-.cjs → console-Ce6heqZZ.cjs} +2 -2
  19. package/dist/console-Ce6heqZZ.cjs.map +1 -0
  20. package/dist/{console-Dv5GfaNn.js → console-DbAZYJuy.js} +4 -4
  21. package/dist/console-DbAZYJuy.js.map +1 -0
  22. package/dist/constants-CN7GE1Lt.js +246 -0
  23. package/dist/constants-CN7GE1Lt.js.map +1 -0
  24. package/dist/constants-CW-MlHdY.cjs +2 -0
  25. package/dist/constants-CW-MlHdY.cjs.map +1 -0
  26. package/dist/constants.d.ts +63 -11
  27. package/dist/context-storage-BjzeBSxH.cjs +2 -0
  28. package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
  29. package/dist/context-storage-DxZf4Gfh.js +52 -0
  30. package/dist/context-storage-DxZf4Gfh.js.map +1 -0
  31. package/dist/core/breadcrumbs.d.ts +10 -3
  32. package/dist/core/context.d.ts +2 -0
  33. package/dist/core/diagnostics.d.ts +11 -3
  34. package/dist/core/journey.d.ts +7 -0
  35. package/dist/core/meter.d.ts +25 -2
  36. package/dist/core/pipeline.d.ts +41 -6
  37. package/dist/core/record.d.ts +42 -9
  38. package/dist/core/remote-sampling.d.ts +7 -3
  39. package/dist/core/runtime.d.ts +153 -6
  40. package/dist/core/sampling.d.ts +35 -2
  41. package/dist/core/sender.d.ts +43 -1
  42. package/dist/core/spans.d.ts +34 -0
  43. package/dist/deadline-5_PecIl5.js +26 -0
  44. package/dist/deadline-5_PecIl5.js.map +1 -0
  45. package/dist/deadline-XSnm95pg.cjs +2 -0
  46. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  47. package/dist/emergency-queue-BYUyDHGD.js +69 -0
  48. package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
  49. package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
  50. package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
  51. package/dist/{errors-DCZWcHkd.js → errors-BhC7HTSt.js} +8 -9
  52. package/dist/errors-BhC7HTSt.js.map +1 -0
  53. package/dist/errors-CgY633cG.cjs +3 -0
  54. package/dist/errors-CgY633cG.cjs.map +1 -0
  55. package/dist/factory-C5TujXlU.js +280 -0
  56. package/dist/factory-C5TujXlU.js.map +1 -0
  57. package/dist/factory-CNj4DH3n.cjs +2 -0
  58. package/dist/factory-CNj4DH3n.cjs.map +1 -0
  59. package/dist/fixed-window-CtaFHanJ.js +12 -0
  60. package/dist/fixed-window-CtaFHanJ.js.map +1 -0
  61. package/dist/fixed-window-CvESpFYV.cjs +2 -0
  62. package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
  63. package/dist/identity-8vKkyAWm.js +103 -0
  64. package/dist/identity-8vKkyAWm.js.map +1 -0
  65. package/dist/identity-Da9TkuKd.cjs +2 -0
  66. package/dist/identity-Da9TkuKd.cjs.map +1 -0
  67. package/dist/index.cjs +1 -1
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.ts +66 -6
  70. package/dist/index.js +1253 -595
  71. package/dist/index.js.map +1 -1
  72. package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
  73. package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
  74. package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-CCA1LvtO.js} +45 -30
  75. package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
  76. package/dist/{interactions-BLH_tX87.js → interactions-BUDLxbv1.js} +16 -12
  77. package/dist/interactions-BUDLxbv1.js.map +1 -0
  78. package/dist/interactions-NHbLKrqe.cjs +2 -0
  79. package/dist/interactions-NHbLKrqe.cjs.map +1 -0
  80. package/dist/{journey-yALMEWF7.js → journey-BUJ4WJxP.js} +37 -34
  81. package/dist/journey-BUJ4WJxP.js.map +1 -0
  82. package/dist/journey-B_tTnvac.cjs +2 -0
  83. package/dist/journey-B_tTnvac.cjs.map +1 -0
  84. package/dist/keys-BHhw_0Wh.cjs +2 -0
  85. package/dist/keys-BHhw_0Wh.cjs.map +1 -0
  86. package/dist/keys-D5r_GH9q.js +17 -0
  87. package/dist/keys-D5r_GH9q.js.map +1 -0
  88. package/dist/{library-request-CQD4HUiP.js → library-request-BKOcaKtQ.js} +3 -3
  89. package/dist/{library-request-CQD4HUiP.js.map → library-request-BKOcaKtQ.js.map} +1 -1
  90. package/dist/{library-request-BcAxuwsf.cjs → library-request-BaZOi4eg.cjs} +2 -2
  91. package/dist/{library-request-BcAxuwsf.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
  92. package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-CF3qiSAX.cjs} +2 -2
  93. package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
  94. package/dist/{long-frames-DD_Um9_4.js → long-frames-DI5ypfAF.js} +5 -5
  95. package/dist/long-frames-DI5ypfAF.js.map +1 -0
  96. package/dist/models/batch.d.ts +4 -0
  97. package/dist/models/bus.d.ts +32 -9
  98. package/dist/models/config.d.ts +401 -12
  99. package/dist/models/drop.d.ts +1 -1
  100. package/dist/models/health.d.ts +27 -0
  101. package/dist/models/log-record.d.ts +1 -1
  102. package/dist/models/plugin.d.ts +47 -0
  103. package/dist/models/stats.d.ts +11 -0
  104. package/dist/models/storage.d.ts +13 -0
  105. package/dist/network-CF8UO5PK.cjs +2 -0
  106. package/dist/network-CF8UO5PK.cjs.map +1 -0
  107. package/dist/{network--GoE7_Or.js → network-DdzXDI3J.js} +47 -31
  108. package/dist/network-DdzXDI3J.js.map +1 -0
  109. package/dist/openfin-BwEN0uj4.js.map +1 -1
  110. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  111. package/dist/{platform-GaM6h7XM.js → platform-Bw1btWCT.js} +21 -10
  112. package/dist/platform-Bw1btWCT.js.map +1 -0
  113. package/dist/platform-DBSKTvFn.cjs +2 -0
  114. package/dist/platform-DBSKTvFn.cjs.map +1 -0
  115. package/dist/remote-rules-DIcC5vVC.js +91 -0
  116. package/dist/remote-rules-DIcC5vVC.js.map +1 -0
  117. package/dist/remote-rules-DpFmOef2.cjs +2 -0
  118. package/dist/remote-rules-DpFmOef2.cjs.map +1 -0
  119. package/dist/sampling-BVjspJWu.cjs +2 -0
  120. package/dist/sampling-BVjspJWu.cjs.map +1 -0
  121. package/dist/sampling-Cm3WhI0a.js +76 -0
  122. package/dist/sampling-Cm3WhI0a.js.map +1 -0
  123. package/dist/{sanitize-DP0xDPrt.js → sanitize-C-ahCFsG.js} +2 -2
  124. package/dist/{sanitize-DP0xDPrt.js.map → sanitize-C-ahCFsG.js.map} +1 -1
  125. package/dist/{sanitize--_e4oOPX.cjs → sanitize-DHucKGdi.cjs} +2 -2
  126. package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
  127. package/dist/sender-D3fRCR8d.cjs +3 -0
  128. package/dist/sender-D3fRCR8d.cjs.map +1 -0
  129. package/dist/sender-DUUmSglb.js +1163 -0
  130. package/dist/sender-DUUmSglb.js.map +1 -0
  131. package/dist/storage/context-storage.d.ts +89 -0
  132. package/dist/storage/emergency-queue.d.ts +9 -1
  133. package/dist/storage/factory.d.ts +7 -1
  134. package/dist/storage/idb-driver.d.ts +13 -0
  135. package/dist/storage/indexeddb-storage.d.ts +13 -0
  136. package/dist/storage/local-storage.d.ts +21 -1
  137. package/dist/storage/memory-storage.d.ts +13 -0
  138. package/dist/storage-BA9RqRO-.cjs +2 -0
  139. package/dist/storage-BA9RqRO-.cjs.map +1 -0
  140. package/dist/storage-w7Tslvlq.js +17 -0
  141. package/dist/storage-w7Tslvlq.js.map +1 -0
  142. package/dist/storm-CNZjsw4T.cjs +2 -0
  143. package/dist/storm-CNZjsw4T.cjs.map +1 -0
  144. package/dist/storm-Daq2jGHU.js +10 -0
  145. package/dist/storm-Daq2jGHU.js.map +1 -0
  146. package/dist/transport/exit-flush.d.ts +6 -0
  147. package/dist/transport/http-transport.d.ts +2 -1
  148. package/dist/transport/retry-engine.d.ts +7 -2
  149. package/dist/transport/serializers/otlp-traces.d.ts +3 -0
  150. package/dist/transport/serializers/select.d.ts +8 -5
  151. package/dist/transport/status-transport.d.ts +24 -0
  152. package/dist/types-BR9t_w28.js +8 -0
  153. package/dist/types-BR9t_w28.js.map +1 -0
  154. package/dist/types-C7WNpnG1.cjs +2 -0
  155. package/dist/types-C7WNpnG1.cjs.map +1 -0
  156. package/dist/utils/fixed-window.d.ts +9 -0
  157. package/dist/utils/identity.d.ts +20 -2
  158. package/dist/utils/lock.d.ts +8 -0
  159. package/dist/utils/openfin.d.ts +1 -1
  160. package/dist/utils/platform.d.ts +10 -0
  161. package/dist/utils/tracing.d.ts +82 -4
  162. package/dist/web-socket-BacvKOvD.cjs +2 -0
  163. package/dist/web-socket-BacvKOvD.cjs.map +1 -0
  164. package/dist/web-socket-CpsD8WAa.js +105 -0
  165. package/dist/web-socket-CpsD8WAa.js.map +1 -0
  166. package/package.json +1 -1
  167. package/dist/batch-D5qvsMQ_.cjs +0 -2
  168. package/dist/batch-D5qvsMQ_.cjs.map +0 -1
  169. package/dist/batch-DDgxg16_.js.map +0 -1
  170. package/dist/bus-C6RwKzPW.js +0 -478
  171. package/dist/bus-C6RwKzPW.js.map +0 -1
  172. package/dist/bus-WPVDFw2y.cjs +0 -2
  173. package/dist/bus-WPVDFw2y.cjs.map +0 -1
  174. package/dist/console-BSusX_M-.cjs.map +0 -1
  175. package/dist/console-Dv5GfaNn.js.map +0 -1
  176. package/dist/constants-Cb92egPS.cjs +0 -2
  177. package/dist/constants-Cb92egPS.cjs.map +0 -1
  178. package/dist/constants-DhH6VI5a.js +0 -144
  179. package/dist/constants-DhH6VI5a.js.map +0 -1
  180. package/dist/deadline-CUrH0Hd8.cjs +0 -2
  181. package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
  182. package/dist/deadline-DeqXEliN.js +0 -31
  183. package/dist/deadline-DeqXEliN.js.map +0 -1
  184. package/dist/errors-DCZWcHkd.js.map +0 -1
  185. package/dist/errors-ERu-su8m.cjs +0 -3
  186. package/dist/errors-ERu-su8m.cjs.map +0 -1
  187. package/dist/fixed-window-BR0bu32Y.cjs +0 -2
  188. package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
  189. package/dist/fixed-window-Re7jIRJH.js +0 -9
  190. package/dist/fixed-window-Re7jIRJH.js.map +0 -1
  191. package/dist/identity-C1WLItSl.cjs +0 -2
  192. package/dist/identity-C1WLItSl.cjs.map +0 -1
  193. package/dist/identity-Di-QXGCC.js +0 -88
  194. package/dist/identity-Di-QXGCC.js.map +0 -1
  195. package/dist/indexeddb-storage-DX18p39D.cjs +0 -2
  196. package/dist/indexeddb-storage-DX18p39D.cjs.map +0 -1
  197. package/dist/indexeddb-storage-T9YIYVYC.js.map +0 -1
  198. package/dist/interactions-BLH_tX87.js.map +0 -1
  199. package/dist/interactions-_hfOerfC.cjs +0 -2
  200. package/dist/interactions-_hfOerfC.cjs.map +0 -1
  201. package/dist/journey-BRUj0hqD.cjs +0 -2
  202. package/dist/journey-BRUj0hqD.cjs.map +0 -1
  203. package/dist/journey-yALMEWF7.js.map +0 -1
  204. package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
  205. package/dist/long-frames-DD_Um9_4.js.map +0 -1
  206. package/dist/network--GoE7_Or.js.map +0 -1
  207. package/dist/network-DcuS2H1P.cjs +0 -2
  208. package/dist/network-DcuS2H1P.cjs.map +0 -1
  209. package/dist/platform-GaM6h7XM.js.map +0 -1
  210. package/dist/platform-kIL5AZB7.cjs +0 -2
  211. package/dist/platform-kIL5AZB7.cjs.map +0 -1
  212. package/dist/remote-rules-6ePq8CrI.js +0 -84
  213. package/dist/remote-rules-6ePq8CrI.js.map +0 -1
  214. package/dist/remote-rules-CI3gbRCL.cjs +0 -2
  215. package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
  216. package/dist/sampling-C-M8p3FK.cjs +0 -2
  217. package/dist/sampling-C-M8p3FK.cjs.map +0 -1
  218. package/dist/sampling-Ud_WiuU9.js +0 -65
  219. package/dist/sampling-Ud_WiuU9.js.map +0 -1
  220. package/dist/sender-BESHz6my.cjs +0 -3
  221. package/dist/sender-BESHz6my.cjs.map +0 -1
  222. package/dist/sender-BUBWLn5i.js +0 -1244
  223. package/dist/sender-BUBWLn5i.js.map +0 -1
  224. package/dist/storm-DhHGHhOc.cjs +0 -2
  225. package/dist/storm-DhHGHhOc.cjs.map +0 -1
  226. package/dist/storm-OD5J6Ylm.js +0 -10
  227. package/dist/storm-OD5J6Ylm.js.map +0 -1
@@ -0,0 +1,103 @@
1
+ import { hn as e, in as t, nn as n, rn as r } from "./constants-CN7GE1Lt.js";
2
+ //#region src/utils/identity.ts
3
+ var i = {
4
+ local: () => localStorage,
5
+ session: () => sessionStorage
6
+ };
7
+ function a() {
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 o(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 s(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 o(16);
35
+ }
36
+ function c(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 l(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 u(e, t, n, i) {
45
+ let a = c(e, "local", r, t);
46
+ if (a) try {
47
+ let e = JSON.parse(a);
48
+ return e.id && (i === 0 || n - (e.lastSeenAt ?? 0) < i) ? e.id : void 0;
49
+ } catch {
50
+ t.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
51
+ return;
52
+ }
53
+ }
54
+ function d(t, a = i, o = n) {
55
+ let d = s(t), f = Date.now(), p = s(t), m = u(a, t, f, o) ?? p, h = JSON.stringify({
56
+ id: m,
57
+ lastSeenAt: f
58
+ });
59
+ l(a, "local", r, h, t);
60
+ let g = c(a, "session", "ui-observability.tab", t) ?? "";
61
+ return g || (g = s(t), l(a, "session", e, g, t)), {
62
+ sessionId: m,
63
+ tabId: g,
64
+ contextId: d
65
+ };
66
+ }
67
+ function f(t, n, r) {
68
+ l(r, "session", e, t, n);
69
+ }
70
+ var p = class {
71
+ diagnostics;
72
+ stores;
73
+ touchMs;
74
+ idleMs;
75
+ lastTouchAt = 0;
76
+ constructor(e, r = i, a = t, o = n) {
77
+ this.diagnostics = e, this.stores = r, this.touchMs = a, this.idleMs = o;
78
+ }
79
+ touch(e) {
80
+ let t = Date.now();
81
+ if (t - this.lastTouchAt < this.touchMs) return;
82
+ let n = u(this.stores, this.diagnostics, t, this.idleMs);
83
+ n !== void 0 && n !== e ? this.lastTouchAt = t : this.write(e, t);
84
+ }
85
+ stored() {
86
+ return u(this.stores, this.diagnostics, Date.now(), this.idleMs);
87
+ }
88
+ restart(e) {
89
+ this.write(e, Date.now());
90
+ }
91
+ write(e, t) {
92
+ this.lastTouchAt = t;
93
+ let n = JSON.stringify({
94
+ id: e,
95
+ lastSeenAt: t
96
+ });
97
+ l(this.stores, "local", r, n, this.diagnostics);
98
+ }
99
+ };
100
+ //#endregion
101
+ export { f as a, s as i, p as n, o, a as r, d as s, i as t };
102
+
103
+ //# sourceMappingURL=identity-8vKkyAWm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-8vKkyAWm.js","names":["TAB_ID_KEY","SESSION_TOUCH_MS","SESSION_IDLE_MS","SESSION_ID_KEY","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","safeRead","diagnostics","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","touchMs","stored"],"sources":["../src/utils/identity.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 * Reads the session id in the local store. It reports a record that is not valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === 0 || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\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 idleMs = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\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 private readonly touchMs = SESSION_TOUCH_MS,\n private readonly idleMs = SESSION_IDLE_MS,\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 < this.touchMs) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Do not write the old\n // id back. A reload would then resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id in the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store now. The throttle does not apply.\n * @param sessionId New session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\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"],"mappings":";;AAwDA,IAAaI,IAAiC;CAC5C,aAAa;CACb,eAAe;AACjB;AAMA,SAAgBC,IAA+B;CAC7C,IAAMC,KAAQ,OAA6C;EACzD,UAAU,MAAQC,EAAI,IAAIC,CAAG,KAAK;EAClC,UAAU,GAAK,MAAU;GACvB,EAAI,IAAIA,GAAKC,CAAK;EACpB;EACA,aAAa,MAAQ;GACnB,EAAI,OAAOD,CAAG;EAChB;CACF,IAEME,IAAaJ,kBAAK,IAAI,IAAI,CAAC,GAC3BK,IAAeL,kBAAK,IAAI,IAAI,CAAC;CAEnC,OAAO;EAAE,aAAaI;EAAY,eAAeC;CAAa;AAChE;AAQA,SAAgBC,EAAU,GAA4B;CACpD,IAAMC,IAAQ,IAAI,WAAWC,CAAU;CACvC,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,mBAAoB,YACrE,OAAO,gBAAgBD,CAAK;MAE5B,KAAK,IAAIE,IAAI,GAAGA,IAAID,GAAY,KAC9B,EAAMC,KAAK,KAAK,MAAM,KAAK,OAAO,IAAA,GAAoB;CAG1D,OAAO,MAAM,KAAKF,IAAQ,MAAMG,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAC1E;AAOA,SAAgBC,EAAM,GAAkC;CACtD,IAAI;EACF,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,cAAe,YAChE,OAAO,OAAO,WAAW;CAE7B,QAAQ;EAGN,EAAY,MAAM,sBAAsB;CAC1C;CACA,OAAOL,EAAA,EAAwB;AACjC;AAUA,SAASM,EACP,GACA,GACA,GACA,GACe;CACf,OACEC,EAAY,MAAM,uBAAuB,8BAA8BC,EAAM,iBAC3EC,EAAOD,EAAM,CAAC,CAAC,CAAC,QAAQZ,CAAG,CAC7B,KAAK;AAET;AAUA,SAASc,EACP,GACA,GACA,GACA,GACA,GACM;CACN,EAAY,MACV,uBACA,kCAAkCF,EAAM,iBAClC;EACJ,EAAOA,EAAM,CAAC,CAAC,CAAC,QAAQZ,GAAKC,CAAK;CACpC,CACF;AACF;AASA,SAASc,EACP,GACA,GACA,GACA,GACoB;CACpB,IAAMC,IAAMN,EAASG,GAAQ,SAASlB,GAAgBgB,CAAW;CACjE,IAAKK,GAIL,IAAI;EACF,IAAMC,IAAS,KAAK,MAAMD,CAAG;EAC7B,OAAOC,EAAO,OAAOC,MAAW,KAAKC,KAAOF,EAAO,cAAc,KAAKC,KAClED,EAAO,KACP,KAAA;CACN,QAAQ;EACN,EAAY,OACV,oBACA,yEACF;EACA;CACF;AACF;AAQA,SAAgBG,EACd,GACA,IAAyBxB,GACzB,IAASF,GACC;CACV,IAAM2B,IAAYZ,EAAME,CAAW,GAC7BQ,IAAM,KAAK,IAAI,GAEfG,IAASb,EAAME,CAAW,GAC1BY,IAAYR,EAAYF,GAAQF,GAAaQ,GAAKD,CAAM,KAAKI,GAC7DE,IAAU,KAAK,UAAU;EAAE,IAAID;EAAW,YAAYJ;CAAI,CAAC;CACjE,EAAUN,GAAQ,SAASlB,GAAgB6B,GAASb,CAAW;CAE/D,IAAIc,IAAQf,EAASG,GAAQ,WAAA,wBAAuBF,CAAW,KAAK;CAMpE,OALKc,MACH,IAAQhB,EAAME,CAAW,GACzBG,EAAUD,GAAQ,WAAWrB,GAAYiC,GAAOd,CAAW,IAGtD;EAAE;EAAW;EAAO;CAAU;AACvC;AAQA,SAAgBe,EACd,GACA,GACA,GACM;CACN,EAAUb,GAAQ,WAAWrB,GAAYiC,GAAOd,CAAW;AAC7D;AAOA,IAAagB,IAAb,MAA0B;CASd;CACS;CACA;CACA;CAVnB,cAAsB;CAMtB,YACE,GACA,IAA0C/B,GAC1C,IAA2BH,GAC3B,IAA0BC,GAC1B;EADiB,AAHT,KAAA,cAAAiB,GACS,KAAA,SAAAE,GACA,KAAA,UAAAe,GACA,KAAA,SAAAV;CAChB;CAMH,MAAM,GAAyB;EAC7B,IAAMC,IAAM,KAAK,IAAI;EAErB,IAAIA,IAAM,KAAK,cAAc,KAAK,SAChC;EAKF,IAAMU,IAASd,EAAY,KAAK,QAAQ,KAAK,aAAaI,GAAK,KAAK,MAAM;EAC1E,AAAIU,MAAW,KAAA,KAAaA,MAAWN,IACrC,KAAK,cAAcJ,IAIrB,KAAK,MAAMI,GAAWJ,CAAG;CAC3B;CAMA,SAA6B;EAC3B,OAAOJ,EAAY,KAAK,QAAQ,KAAK,aAAa,KAAK,IAAI,GAAG,KAAK,MAAM;CAC3E;CAMA,QAAQ,GAAyB;EAC/B,KAAK,MAAMQ,GAAW,KAAK,IAAI,CAAC;CAClC;CAOA,MAAc,GAAmB,GAAmB;EAClD,KAAK,cAAcJ;EACnB,IAAMK,IAAU,KAAK,UAAU;GAAE,IAAID;GAAW,YAAYJ;EAAI,CAAC;EACjE,EAAU,KAAK,QAAQ,SAASxB,GAAgB6B,GAAS,KAAK,WAAW;CAC3E;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-CW-MlHdY.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(t,n,r,i){let o=a(t,`local`,e.rn,n);if(o)try{let e=JSON.parse(o);return e.id&&(i===0||r-(e.lastSeenAt??0)<i)?e.id:void 0}catch{n.report(`storage.degraded`,`The session record is not valid JSON. The library starts a new session.`);return}}function c(n,r=t,c=e.nn){let l=i(n),u=Date.now(),d=i(n),f=s(r,n,u,c)??d,p=JSON.stringify({id:f,lastSeenAt:u});o(r,`local`,e.rn,p,n);let m=a(r,`session`,`ui-observability.tab`,n)??``;return m||(m=i(n),o(r,`session`,e.hn,m,n)),{sessionId:f,tabId:m,contextId:l}}function l(t,n,r){o(r,`session`,e.hn,t,n)}var u=class{diagnostics;stores;touchMs;idleMs;lastTouchAt=0;constructor(n,r=t,i=e.in,a=e.nn){this.diagnostics=n,this.stores=r,this.touchMs=i,this.idleMs=a}touch(e){let t=Date.now();if(t-this.lastTouchAt<this.touchMs)return;let n=s(this.stores,this.diagnostics,t,this.idleMs);n!==void 0&&n!==e?this.lastTouchAt=t:this.write(e,t)}stored(){return s(this.stores,this.diagnostics,Date.now(),this.idleMs)}restart(e){this.write(e,Date.now())}write(t,n){this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});o(this.stores,`local`,e.rn,r,this.diagnostics)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
2
+ //# sourceMappingURL=identity-Da9TkuKd.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-Da9TkuKd.cjs","names":["SESSION_ID_KEY","SESSION_IDLE_MS","TAB_ID_KEY","SESSION_TOUCH_MS","require_constants","BROWSER_STORES","memoryStores","wrap","map","key","value","localStore","sessionStore","randomHex","bytes","byteLength","i","b","newId","diagnostics","safeRead","store","stores","safeWrite","liveSession","raw","parsed","idleMs","now","resolveIdentity","contextId","minted","sessionId","session","tabId","persistTabId","SessionTouch","touchMs","stored"],"sources":["../src/utils/identity.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 * Reads the session id in the local store. It reports a record that is not valid JSON.\n * @param stores Identity stores.\n * @param diagnostics Diagnostics reporter.\n * @param now Epoch time in milliseconds.\n * @returns The stored id, or undefined when it is absent or expired.\n */\nfunction liveSession(\n stores: IdentityStores,\n diagnostics: Diagnostics,\n now: number,\n idleMs: number,\n): string | undefined {\n const raw = safeRead(stores, \"local\", SESSION_ID_KEY, diagnostics);\n if (!raw) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(raw) as { id?: string; lastSeenAt?: number };\n return parsed.id && (idleMs === 0 || now - (parsed.lastSeenAt ?? 0) < idleMs)\n ? parsed.id\n : undefined;\n } catch {\n diagnostics.report(\n \"storage.degraded\",\n \"The session record is not valid JSON. The library starts a new session.\",\n );\n return undefined;\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 idleMs = SESSION_IDLE_MS,\n): Identity {\n const contextId = newId(diagnostics);\n const now = Date.now();\n\n const minted = newId(diagnostics);\n const sessionId = liveSession(stores, diagnostics, now, idleMs) ?? minted;\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 private readonly touchMs = SESSION_TOUCH_MS,\n private readonly idleMs = SESSION_IDLE_MS,\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 < this.touchMs) {\n return;\n }\n\n // Another tab can hold a newer session, for example after newSession(). Do not write the old\n // id back. A reload would then resume the old session.\n const stored = liveSession(this.stores, this.diagnostics, now, this.idleMs);\n if (stored !== undefined && stored !== sessionId) {\n this.lastTouchAt = now;\n return;\n }\n\n this.write(sessionId, now);\n }\n\n /**\n * Reads the live session id in the local store.\n * @returns The stored session id, or undefined if no session is live.\n */\n stored(): string | undefined {\n return liveSession(this.stores, this.diagnostics, Date.now(), this.idleMs);\n }\n\n /**\n * Writes a new session id to the local store now. The throttle does not apply.\n * @param sessionId New session identifier.\n */\n restart(sessionId: string): void {\n this.write(sessionId, Date.now());\n }\n\n /**\n * Writes the session record and starts a new throttle window.\n * @param sessionId Session identifier.\n * @param now Epoch time in milliseconds.\n */\n private write(sessionId: string, now: number): void {\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"],"mappings":"4CAwDA,IAAaK,EAAiC,CAC5C,UAAa,aACb,YAAe,cACjB,EAMA,SAAgBC,GAA+B,CAC7C,IAAMC,EAAQ,IAA6C,CACzD,QAAU,GAAQC,EAAI,IAAIC,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvBD,EAAI,IAAIC,EAAKC,CAAK,CACpB,EACA,WAAa,GAAQ,CACnBF,EAAI,OAAOC,CAAG,CAChB,CACF,GAEME,EAAaJ,EAAK,IAAI,GAAK,EAC3BK,EAAeL,EAAK,IAAI,GAAK,EAEnC,MAAO,CAAE,UAAaI,EAAY,YAAeC,CAAa,CAChE,CAQA,SAAgBC,EAAU,EAA4B,CACpD,IAAMC,EAAQ,IAAI,WAAWC,CAAU,EACvC,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,iBAAoB,WACrE,OAAO,gBAAgBD,CAAK,OAE5B,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAY,IAC9B,EAAMC,GAAK,KAAK,MAAM,KAAK,OAAO,EAAA,GAAoB,EAG1D,OAAO,MAAM,KAAKF,EAAQ,GAAMG,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAC1E,CAOA,SAAgBC,EAAM,EAAkC,CACtD,GAAI,CACF,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,CAE7B,MAAQ,CAGNC,EAAY,MAAM,sBAAsB,CAC1C,CACA,OAAON,EAAA,EAAwB,CACjC,CAUA,SAASO,EACP,EACA,EACA,EACA,EACe,CACf,OACED,EAAY,MAAM,sBAAuB,8BAA8BE,EAAM,cAC3EC,EAAOD,EAAM,CAAC,CAAC,CAAC,QAAQZ,CAAG,CAC7B,GAAK,IAET,CAUA,SAASc,EACP,EACA,EACA,EACA,EACA,EACM,CACNJ,EAAY,MACV,sBACA,kCAAkCE,EAAM,cAClC,CACJC,EAAOD,EAAM,CAAC,CAAC,CAAC,QAAQZ,EAAKC,CAAK,CACpC,CACF,CACF,CASA,SAASc,EACP,EACA,EACA,EACA,EACoB,CACpB,IAAMC,EAAML,EAASE,EAAQ,QAAStB,EAAAA,GAAgBmB,CAAW,EACjE,GAAKM,EAIL,GAAI,CACF,IAAMC,EAAS,KAAK,MAAMD,CAAG,EAC7B,OAAOC,EAAO,KAAOC,IAAW,GAAKC,GAAOF,EAAO,YAAc,GAAKC,GAClED,EAAO,GACP,IAAA,EACN,MAAQ,CACNP,EAAY,OACV,mBACA,yEACF,EACA,MACF,CACF,CAQA,SAAgBU,EACd,EACA,EAAyBxB,EACzB,EAASJ,EAAAA,GACC,CACV,IAAM6B,EAAYZ,EAAMC,CAAW,EAC7BS,EAAM,KAAK,IAAI,EAEfG,EAASb,EAAMC,CAAW,EAC1Ba,EAAYR,EAAYF,EAAQH,EAAaS,EAAKD,CAAM,GAAKI,EAC7DE,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYJ,CAAI,CAAC,EACjEL,EAAUD,EAAQ,QAAStB,EAAAA,GAAgBiC,EAASd,CAAW,EAE/D,IAAIe,EAAQd,EAASE,EAAQ,UAAA,uBAAuBH,CAAW,GAAK,GAMpE,OALKe,IACH,EAAQhB,EAAMC,CAAW,EACzBI,EAAUD,EAAQ,UAAWpB,EAAAA,GAAYgC,EAAOf,CAAW,GAGtD,CAAE,YAAW,QAAO,WAAU,CACvC,CAQA,SAAgBgB,EACd,EACA,EACA,EACM,CACNZ,EAAUD,EAAQ,UAAWpB,EAAAA,GAAYgC,EAAOf,CAAW,CAC7D,CAOA,IAAaiB,EAAb,KAA0B,CASd,YACS,OACA,QACA,OAVnB,YAAsB,EAMtB,YACE,EACA,EAA0C/B,EAC1C,EAA2BF,EAAAA,GAC3B,EAA0BF,EAAAA,GAC1B,CAJQ,KAAA,YAAAkB,EACS,KAAA,OAAAG,EACA,KAAA,QAAAe,EACA,KAAA,OAAAV,CAChB,CAMH,MAAM,EAAyB,CAC7B,IAAMC,EAAM,KAAK,IAAI,EAErB,GAAIA,EAAM,KAAK,YAAc,KAAK,QAChC,OAKF,IAAMU,EAASd,EAAY,KAAK,OAAQ,KAAK,YAAaI,EAAK,KAAK,MAAM,EACtEU,IAAW,IAAA,IAAaA,IAAWN,EACrC,KAAK,YAAcJ,EAIrB,KAAK,MAAMI,EAAWJ,CAAG,CAC3B,CAMA,QAA6B,CAC3B,OAAOJ,EAAY,KAAK,OAAQ,KAAK,YAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAC3E,CAMA,QAAQ,EAAyB,CAC/B,KAAK,MAAMQ,EAAW,KAAK,IAAI,CAAC,CAClC,CAOA,MAAc,EAAmB,EAAmB,CAClD,KAAK,YAAcJ,EACnB,IAAMK,EAAU,KAAK,UAAU,CAAE,GAAID,EAAW,WAAYJ,CAAI,CAAC,EACjEL,EAAU,KAAK,OAAQ,QAASvB,EAAAA,GAAgBiC,EAAS,KAAK,WAAW,CAC3E,CACF"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-Cb92egPS.cjs"),t=require("./error-like-gGRx2s36.cjs"),n=require("./deadline-CUrH0Hd8.cjs"),r=require("./sampling-C-M8p3FK.cjs"),i=require("./sanitize--_e4oOPX.cjs"),a=require("./identity-C1WLItSl.cjs"),o=require("./platform-kIL5AZB7.cjs"),s=require("./batch-D5qvsMQ_.cjs"),c=require("./library-request-BcAxuwsf.cjs"),l=require("./journey-BRUj0hqD.cjs");function u(t){return Math.round((performance.now()-t)*e.z)/e.z}function d(e,t,n,r,i){e.logMetric(`${t}.duration`,n,`ms`,`histogram`,{status:r,...i})}function f(e,t,n,r,i){let a=u(n);e.error(`${t} failed`,r,{"action.duration_ms":a,status:`FAILURE`,...i}),d(e,t,a,`FAILURE`,i)}function p(e,t,n,r){let i=performance.now();try{let a=n();return d(e,t,u(i),`SUCCESS`,r),a}catch(n){throw f(e,t,i,n,r),n}}async function m(e,t,n,r){let i=performance.now();try{let a=await n();return d(e,t,u(i),`SUCCESS`,r),a}catch(n){throw f(e,t,i,n,r),n}}var h=[e.D,e.sn];function g(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 _(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function v(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 y(e){if(!n.i(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function b(e){return h.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function x(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var S=class t{bind;namespace;options;levelType;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n,this.levelType=b(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.I,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=x(a,this.bind().diagnostics),s={...o,"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,[e.vt.attributeKeys]:Object.keys(o)};this.write(`INFO`,`metric`,t,s,!0)};timeSync=(e,t,n)=>p(this,e,t,n);timeAsync=(e,t,n)=>m(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:x(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.`,()=>y(r))??!1),c=s?r:i,l=s?void 0:r,u=l===void 0?void 0:g(l,a.diagnostics),d=u===void 0?void 0:_(l,u,a.diagnostics);if(!o){this.print(a,t,n,c,d,null);return}let f=u?v(l,a.diagnostics):void 0,{record:p,dropped:m}=a.builder.build({level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...x(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,p,m),a.emit(p)}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)}},ee={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},te=class{settings;diagnostics;limits;constructor(t,n,r=e.At){this.settings=t,this.diagnostics=n,this.limits=r}update(e){this.settings=e}accepts(t){return this.settings.level===null||!Object.hasOwn(e.ut,this.settings.level)?!1:e.ut[t]>=e.ut[this.settings.level]}write(e,t,n,r,a){if(!this.accepts(t)||typeof console>`u`||i.a())return;let o=`%c[%s]%c[${t}]%c`,{styles:s}=this.settings,c=ee[t];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${c}.`,()=>{let l=[];a!==void 0&&l.push(a),r!==void 0&&l.push(i.n(r,this.limits,this.diagnostics)),i.o(()=>{console[c](o,s.namespace,e,s[t],``,n,...l)})})}},ne=class{value=0;next(){return++this.value}},re=/^[0-9a-f]{32}$/,ie=/^[0-9a-f]{16}$/,C=/[1-9a-f]/;function ae(e){return re.test(e.traceId)&&C.test(e.traceId)&&ie.test(e.spanId)&&C.test(e.spanId)}function oe(){return a.o(16)}function se(){return a.o(8)}function w(){return{traceId:oe(),spanId:se(),traceFlags:1,startedAt:Date.now()}}function T(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var ce=class{diagnostics;maxAgeMs;load;ambient=w();otel;constructor(t,n=e.vn,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`),T(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(ae(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=w(),T(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._n]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},le=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)}},E=Object.keys(e.ut),ue=[`gzip`,`none`],de=[`omit`,`same-origin`,`include`],fe=[`auto`,`indexeddb`,`localstorage`,`memory`,`none`],pe=[`storage`,`memory`],me=[`auto`,`sender`,`forwarder`,`off`],he=[`auto`,`provider`,`client`],ge=[`auto`,`context`,`tab`,`origin`],D=[`error`,`warn`,`info`,`log`],_e=[`limited`,`until-delivered`],ve={logFlushIntervalMs:[100,6e4],logBatchSize:[1,1e3],metricFlushIntervalMs:[100,6e4],metricBatchSize:[1,1e3]},ye={maxBatches:[1,5e3],maxAgeMs:[6e4,6048e5],maxAttempts:[1,20]},be={maxBodyChars:[256,65536],maxAttributeChars:[256,65536],maxAttributeCount:[1,1024],maxStackChars:[256,65536],maxDepth:[1,16],maxArrayLength:[1,1e4],maxNodes:[100,1e5],maxRecordBytes:[1024,e.S]},xe=[6e4,864e5],Se=[`errors`,`rejections`,`resourceErrors`,`fetch`,`xhr`,`httpMetrics`,`interactions`,`navigation`,`webVitals`,`longFrames`,`fullUrls`],Ce=`null`,O=`a level name: ${A(E)}`,k=`true, false or a list of ${A(D)}`,we=`a list of strings and RegExp patterns`,Te=`a list of origin URLs such as "https://api.example" and RegExp patterns`,Ee=`a list of origin URLs such as "https://app.example". For a sandboxed frame, set bus.mode: "sender" in the frame`,De=`a list of strings`;function A(e){let t=e.map(e=>`"${e}"`);return`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}function j(e){return typeof e==`string`?`"${e}"`:typeof e==`function`?`a function`:typeof e==`object`&&e?`an object`:String(e)}function M(e,t,n,r,i){e.report(`config.invalid`,`${t} must be ${n}. The value is ${j(r)}. The library keeps ${i}.`)}function N(e,t,n,r,i){if(t===void 0)return r;let a=n.find(e=>e===t);return a===void 0?(M(i,e,A(n),t,`"${r}"`),r):a}function P(e,t,n,r){return t===void 0?n:typeof t==`boolean`?t:(M(r,e,`true or false`,t,String(n)),n)}function Oe(e,t,n,r){return t===void 0?n:typeof t==`number`&&Number.isFinite(t)&&t>=0?t:(M(r,e,`a finite number of 0 or more`,t,String(n)),n)}function F(e,t,n,r,i){if(t===void 0)return r;let[a,o]=n;return typeof t==`number`&&Number.isInteger(t)&&t>=a&&t<=o?t:(M(i,e,`an integer from ${String(a)} to ${String(o)}`,t,String(r)),r)}function I(e,t,n,r,i){let a=t??{},o=Object.keys(r);return Object.fromEntries(o.map(t=>[t,F(`${e}.${t}`,a[t],r[t],n[t],i)]))}function L(e){if(typeof e!=`string`)return;let t=e.toUpperCase();return E.find(e=>e===t)}function ke(e,t,n,r){if(t===void 0)return n;let i=L(t);return i===void 0?(M(r,e,O,t,`"${n}"`),n):i}function R(e,t,n,r,i,a){if(t===void 0)return n;if(!Array.isArray(t))return M(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 ${j(t)}. ${e} must be ${r}.`):o.push(n)}return o}function Ae(e){return typeof e==`string`?e:void 0}function je(e){return typeof e==`string`||e instanceof RegExp?e:void 0}function Me(e){return D.find(t=>t===e)}function z(e){if(typeof e==`string`)try{let{origin:t}=new URL(e);return t===Ce?void 0:t}catch{return}}function Ne(e){return e instanceof RegExp?e:z(e)}function Pe(e){return n.i(e)?Object.values(e).every(e=>typeof e==`string`):!1}function Fe(e,t,n){if(e!==void 0)return typeof e==`function`||Pe(e)?e:(M(n,`headers`,`an object of strings or a function`,e,`the headers in force`),t)}function Ie(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function Le(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||Ie(t)?t:(r.report(`config.invalid`,`serializer must be "${e.en}", "ecs" or an implementation. The library uses "${e.en}".`),e.en)}var Re=new Set(Object.keys(e.j));function ze(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)Re.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 Be(e,t,n){if(e===void 0)return t??`DEBUG`;let r=L(e);return r===void 0?(M(n,`console.level`,O,e,`the console level in force`),t):r}function Ve(t,n,r){if(t===void 0)return n;if(t===!1)return{level:null,styles:n.styles};if(t===!0)return{level:e.A,styles:n.styles};if(typeof t==`string`){let e=L(t);return e===void 0?(M(r,`console`,O,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:Be(t.level,n.level,r),styles:{...n.styles,...ze(t.styles,r)}}}function He(e,t,n){let r=e??{};return{...t,...r,rates:{...t.rates,...r.rates},alwaysSampleTypes:R(`sampling.alwaysSampleTypes`,r.alwaysSampleTypes,t.alwaysSampleTypes,De,Ae,n),remote:P(`sampling.remote`,r.remote,t.remote,n)}}function Ue(e,t,n){let r=e??{};return{mode:N(`bus.mode`,r.mode,me,t.mode,n),trustedOrigins:R(`bus.trustedOrigins`,r.trustedOrigins,t.trustedOrigins,Ee,z,n),openFinRole:N(`bus.openFinRole`,r.openFinRole,he,t.openFinRole,n)}}function We(e,t,n){let r=e??{};return{scope:N(`journey.scope`,r.scope,ge,t.scope,n),maxAgeMs:F(`journey.maxAgeMs`,r.maxAgeMs,xe,t.maxAgeMs,n)}}function Ge(e,t,n){let r=e??{};return{mode:N(`retention.mode`,r.mode,_e,t.mode,n),...I(`retention`,r,t,ye,n)}}function Ke(e,t,n){return e===void 0?t:typeof e==`boolean`?e:Array.isArray(e)?R(`capture.console`,e,[],k,Me,n):(M(n,`capture.console`,k,e,`the value in force`),t)}function qe(e,t,n){let r=e??{},i={...t,...r,console:Ke(r.console,t.console,n),longFrameThresholdMs:Oe(`capture.longFrameThresholdMs`,r.longFrameThresholdMs,t.longFrameThresholdMs,n),ignoreUrls:R(`capture.ignoreUrls`,r.ignoreUrls,t.ignoreUrls,we,je,n),propagateTraceHeaderTo:R(`capture.propagateTraceHeaderTo`,r.propagateTraceHeaderTo,t.propagateTraceHeaderTo,Te,Ne,n)};for(let e of Se)i[e]=P(`capture.${e}`,r[e],t[e],n);return i}function Je(t,n,r,i){let a=n;if(typeof t==`string`&&t!==``)try{new URL(t),a=t}catch(e){i.report(`config.invalid`,`metricsEndpoint is not a valid absolute URL: ${t}. The library keeps the value in force.`,void 0,e)}else t===``?a=``:t!==void 0&&M(i,`metricsEndpoint`,`a URL string`,t,`the value in force`);return a!==``&&r!==`otlp`?(i.report(`config.invalid`,`metricsEndpoint needs serializer "${e.en}". The library sends metric records as log records.`),``):a}function B(t,n,r){let i=r??e.F,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,enabled:P(`enabled`,t.enabled,i.enabled,n),minLevel:ke(`minLevel`,t.minLevel,i.minLevel,n),compression:N(`compression`,t.compression,ue,i.compression,n),credentials:N(`credentials`,t.credentials,de,i.credentials,n),headers:`headers`in t?Fe(t.headers,i.headers,n):i.headers,storage:N(`storage`,t.storage,fe,i.storage,n),identity:N(`identity`,t.identity,pe,i.identity,n),serializer:Le(t.serializer,r?.serializer,n),console:Ve(t.console,i.console,n),sampling:He(t.sampling,i.sampling,n),bus:Ue(t.bus,i.bus,n),batching:I(`batching`,t.batching,i.batching,ve,n),retention:Ge(t.retention,i.retention,n),limits:I(`limits`,t.limits,i.limits,be,n),journey:We(t.journey,i.journey,n),capture:qe(t.capture,i.capture,n)};if(a.metricsEndpoint=Je(t.metricsEndpoint,i.metricsEndpoint,a.serializer,n),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.onDrop!==void 0&&typeof a.onDrop!=`function`&&(n.report(`config.invalid`,`onDrop must be a function. The library ignores the value.`),a.onDrop=i.onDrop),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.metricsEndpoint!==``&&a.endpoint===null&&!a.transport&&n.report(`config.invalid`,`metricsEndpoint needs endpoint or transport. The library sends nothing to metricsEndpoint.`),a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.Cn}'.`),e.Cn);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);a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint&&e!==r?.metricsEndpoint);for(let e of[a.endpoint,a.metricsEndpoint])e&&!a.capture.ignoreUrls.includes(e)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,e]);return Ye(t,n),a}function Ye(t,n){let r=new Set([...Object.keys(e.F),...e.xn]);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.k){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.F[r]),...e.Sn[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 Xe(t,n){for(let r of Object.keys(n))e.k.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.k)Object.assign(t[r],n[r])}var Ze=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)}remove(e){this.map.delete(e)}getAll(){return Object.fromEntries(this.map)}},Qe=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.L){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,r,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:r,cause:a,at:s,count:o},{handler:l}=this;if(l)try{i.o(()=>{l(c)})}catch(t){this.count(`handler.threw`),typeof console<`u`&&i.o(()=>{console.warn(`${e.ft} 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)}};function V(e,t){e.length<20&&!e.includes(t)&&e.push(t)}var $e=class{config;diagnostics;pending=new Map;scheduled=!1;reporting=!1;constructor(e,t){this.config=e,this.diagnostics=t}add(t,n,r=[]){if(!this.config.onDrop||this.reporting||n.length===0&&r.length===0)return;let i=this.pending.get(t);i||(i={reason:t,records:0,batchIds:[],journeyIds:[],actions:[]},this.pending.set(t,i)),i.records+=n.length;for(let e of r)V(i.batchIds,e);for(let t of n){let n=s.t(t,e.s);typeof n==`string`&&V(i.journeyIds,n);let r=s.r(t)?t.body:void 0;typeof r==`string`&&V(i.actions,r)}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.flush()}))}flush(){this.scheduled=!1;let e=[...this.pending.values()];this.pending.clear();let t=this.config.onDrop;if(t){this.reporting=!0;for(let n of e)this.diagnostics.guard(`handler.threw`,`The onDrop hook threw an error.`,()=>{c.r(()=>{i.o(()=>{t(n)})})});this.reporting=!1}}},H=class{onDrop;held=[];actions=0;constructor(e){this.onDrop=e}get records(){return this.held}get length(){return this.held.length}push(e){let t=s.r(e);if((t?this.actions:this.held.length-this.actions)<(t?2e3:500))this.actions+=+!!t;else{let e=this.held.findIndex(e=>s.r(e)===t),[n]=this.held.splice(e,1);this.onDrop(n)}this.held.push(e)}take(){let e=this.held;return this.held=[],this.actions=0,e}},et=`overflow`,tt=new Set([e.d,e.u,e.n,e.p,e.s,e.c,e.l]);function nt(e={}){let t={};for(let n of Object.keys(e).sort()){if(n.startsWith(`metric.`)||tt.has(n))continue;let r=e[n];(typeof r==`string`||typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r)}return t}function rt(e){if(!Array.isArray(e))return null;let t=Math.min(e.length,51);return Array.from({length:t},(t,n)=>e[n])}function it(e){return Array.isArray(e)&&e.length<=50&&e.every((t,n)=>typeof t==`number`&&Number.isFinite(t)&&(n===0||t>e[n-1]))}function at(t,n,r){let i={"metric.name":t.name,"metric.unit":t.unit,"metric.type":t.kind,[e.vt.start]:r,[e.vt.attributeKeys]:Object.keys(n.attributes)};return t.kind===`counter`?(i[`metric.value`]=n.sum,i):{...i,[e.vt.count]:n.count,[e.vt.sum]:n.sum,[e.vt.min]:n.min,[e.vt.max]:n.max,[e.vt.bounds]:t.boundaries,[e.vt.buckets]:n.buckets}}var ot=class{intervalMs;emit;diagnostics;instruments=new Map;timer=null;startedAt=0;constructor(e,t,n){this.intervalMs=e,this.emit=t,this.diagnostics=n}record(e,t,n){!Number.isFinite(t)||e.kind===`counter`&&t<0?this.diagnostics.report(`record.dropped_malformed`,`The value of the metric ${e.name} is not valid. The library dropped it.`,{"metric.name":e.name}):this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the metric ${e.name}.`,()=>{let r=this.instrumentOf(e);r&&(this.add(r,t,nt(n)),this.arm())})}collect(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let e=`${String(this.startedAt)}000000`,t=[...this.instruments.values()];this.instruments.clear();for(let{def:n,series:r}of t)for(let t of r.values())this.emit(n.name,t.attributes,at(n,t,e))}instrumentOf(t){let n=this.instruments.get(t.name);if(n)return n.def.kind===t.kind?n:(this.diagnostics.report(`record.dropped_malformed`,`The metric ${t.name} is a counter and a histogram. The library dropped the value.`,{"metric.name":t.name}),null);let r=rt(t.boundaries),i=it(r);t.kind===`histogram`&&!i&&this.diagnostics.report(`config.invalid`,`The boundaries of the metric ${t.name} must be at most 50 finite numbers in ascending order. The library uses the default boundaries.`);let a={def:{...t,boundaries:i?r:[...e._t]},series:new Map};return this.instruments.set(t.name,a),a}add(t,n,r){let i=JSON.stringify(r),a=t.series.get(i),o=r;if(!a&&t.series.size>=100&&(i=et,a=t.series.get(i),o={[e.f]:!0}),!a){let e=t.def.kind===`histogram`?t.def.boundaries.length+1:0,r=Array(e).fill(0);a={attributes:o,count:0,sum:0,min:n,max:n,buckets:r},t.series.set(i,a)}if(a.count+=1,a.sum+=n,a.min=Math.min(a.min,n),a.max=Math.max(a.max,n),a.buckets.length>0){let e=t.def.boundaries.findIndex(e=>n<=e);a.buckets[e===-1?a.buckets.length-1:e]+=1}}arm(){this.timer===null&&(this.startedAt=Date.now(),this.timer=setTimeout(()=>{this.collect()},this.intervalMs()),n.r(this.timer))}},st=`error.`,ct=[e.p,e.s,e.c];function U(e){return e}var lt=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.lt.includes(n))return!0;let i=this.deps.remote.sampling?.minLevel()??r.minLevel;return e.ut[t]>=e.ut[i]}build(t){let{config:n,diagnostics:a,tracing:s,journey:c,sequence:l,limits:u,remote:d}=this.deps;if(!this.isEnabled(t.level,t.type))return a.count(`record.dropped_by_level`),{record:null,dropped:`level`};let f=s.resolve(),p=c.current();if(!r.r({level:t.level,type:t.type,namespace:t.namespace,journeyId:p?.id??``,traceId:f.traceId,aggregated:t.aggregated},n,d.sampling?.current()??null))return a.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let m=l.next(),h=o.t(a),g=n.capture.fullUrls?h:o.i(h),_,v=0;try{let e=i.r(this.deps.context.getAll(),u,a),n=i.r(t.scoped??{},u,a),r=i.r(t.payload??{},u,a);v=e.bytes+n.bytes+r.bytes,_={...U(e.value),...U(n.value),...U(r.value)}}catch(t){a.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),_={[e.m]:!0}}Object.assign(_,t.fixed),_[e.d]=t.type,_[e.u]=m,_[e.n]=t.namespace,_[e.p]=g,p&&(_[e.s]=p.id,_[e.c]=p.name,p.parentId!==void 0&&(_[e.l]=p.parentId));let y=i.i(t.body,u.maxBodyChars);y!==t.body&&a.count(`record.truncated`);let b={timeUnixNano:r.o(),traceId:f.traceId,spanId:f.spanId,traceFlags:f.traceFlags,severityNumber:e.in[t.level],severityText:t.level,body:y,attributes:_,resource:this.resource()},x=n.redact;if(x){let n;try{n=x(b)}catch(e){return a.report(`record.dropped_by_redact`,`The redact hook threw an error. The library dropped the record.`,void 0,e),{record:null,dropped:`redact`}}if(n===null)return a.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};let o=n??b;if(!r.a(o))return o===b?(a.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`}):(a.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(r.i(o.severityText)){if(o!==b){let e=i.r(o.attributes,u,a);b={...o,attributes:U(e.value)},v=e.bytes,Object.assign(b.attributes,t.fixed)}b.severityNumber=e.in[b.severityText]}else return a.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){a.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 ct)e in b.attributes&&(n[e]=b.attributes[e]);for(let[e,t]of Object.entries(b.attributes))e.startsWith(st)&&(n[e]=t);let r=i.r(n,u,a).bytes;r>u.maxRecordBytes&&`error.data`in n&&(Reflect.deleteProperty(n,e.o),r=i.r(n,u,a).bytes);let o=b.attributes[e.a];if(o!==void 0){let t=i.r(o,u,a).bytes;r+t<=u.maxRecordBytes&&(n[e.a]=o)}Object.assign(n,t.fixed),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.Vt]:t.serviceName,[e.Ht]:t.serviceVersion,[e.Lt]:t.environment,[e.Kt]:e.hn,[e.qt]:e.gn,[e.Gt]:e.mn,[e.Rt]:r.platform,[e.Ut]:n.sessionId,[e.Wt]:n.tabId,[e.It]:n.contextId,[e.Ft]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Bt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.zt]:r.openfinName}},this.resourceCache}},ut={errors:async()=>(await Promise.resolve().then(()=>require("./errors-ERu-su8m.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-DcuS2H1P.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-_hfOerfC.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-DFuoTQbZ.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-D4Bm3Zkz.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-BSusX_M-.cjs"))).ConsoleCapture},W=Symbol.for(e.Zt),G=Symbol.for(e.Qt),dt=[`batching`,`retention`];function K(e){return JSON.stringify({...e,webVitalsLoader:e.webVitalsLoader!==void 0,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String)})}function q(e){return{...e,endpoint:null,transport:void 0,transportOnExit:void 0,bus:{...e.bus,mode:`off`}}}function J(t){return t.sdkVersion===e.gn}var Y=class t{degraded;static local=null;sdkVersion=e.gn;diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new Ze;breadcrumbs;tracing;sequence=new ne;journey;builder;remote={sampling:null};console;drops;meter;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=new H(e=>{this.dropHeld(e)});captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1};bootBuffer=new H(e=>{this.dropHeld(e)});forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;started=Promise.resolve();ready=!1;destroyed=!1;lastGapAt=0;limits;journeyOptions;tunablesLocked=!0;constructor(e,t=!1){this.degraded=t,this.diagnostics=new Qe(e.onDiagnostic),this.platform=o.n(this.diagnostics),this.config=B(e,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?a.r():a.t,this.identity=a.s(this.diagnostics,this.stores),this.sessionTouch=new a.n(this.diagnostics,this.stores),this.breadcrumbs=new le(50),this.tracing=new ce(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.limits={...this.config.limits},this.console=new te(this.config.console,this.diagnostics,this.limits),this.drops=new $e(this.config,this.diagnostics),this.journeyOptions={...l.t,maxAgeMs:this.config.journey.maxAgeMs},this.journey=new l.n(this.journeyOptions,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new lt({remote:this.remote,config:this.config,limits:this.limits,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform}),this.meter=new ot(()=>this.config.batching.metricFlushIntervalMs,(e,t,n)=>{this.emitPoint(e,t,n)},this.diagnostics)}recordMetric(e,t,n){this.destroyed||this.meter.record(e,t,n)}emitPoint(t,n,r){let{record:i}=this.builder.build({level:`INFO`,type:`metric`,body:t,namespace:e.yt,payload:n,fixed:r,aggregated:!0});this.emit(i)}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[W]??null}static current(){let e=t.local;if(e)return e.destroyed?null:e;let n=t.pinned();return n&&J(n)?n:null}static stopped(){let e=t.local;if(e?.destroyed)return e;let n=globalThis[G];return n&&J(n)?n:null}isDestroyed(){return this.destroyed}static configure(e,n=!1){let r=t.local;if(r&&!r.destroyed)return r.reconfigure(q(e)),r;t.local=null;let i=t.pinned();if(i){if(!J(i))return t.startDegraded(e,i.sdkVersion);if(!i.destroyed)return i.reconfigure(e),i}let a=new t(e);return a.tunablesLocked=!n,globalThis[W]=a,Reflect.deleteProperty(globalThis,G),a.init(),a}static startDegraded(n,r){let i=new t(q(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.gn}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:a,own:e.gn}),i.init(),i}reconfigure(e){let t=this.keepDestination(e),n=K(this.config.capture),r=B(t,this.diagnostics,this.config);this.keepStartupTunables(r),Xe(this.config,r),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),K(this.config.capture)!==n&&this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepStartupTunables(e){if(this.senderLoad!==void 0&&this.keepSections(e,dt),!this.tunablesLocked){this.tunablesLocked=!0,Object.assign(this.limits,e.limits),this.journeyOptions.maxAgeMs=e.journey.maxAgeMs;return}this.keepSections(e,[`limits`]);let{maxAgeMs:t}=this.config.journey;e.journey.maxAgeMs!==t&&(this.diagnostics.report(`config.invalid`,`journey.maxAgeMs cannot change after startup. It stays ${String(t)}.`,{requested:e.journey.maxAgeMs}),e.journey.maxAgeMs=t)}keepSections(e,t){for(let n of t)JSON.stringify(e[n])!==JSON.stringify(this.config[n])&&(this.diagnostics.report(`config.invalid`,`${n} cannot change after startup. The values in force stay.`,{requested:e[n]}),Object.assign(e,{[n]:this.config[n]}))}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-WPVDFw2y.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.hasDestination()||this.role()!==`sender`?Promise.resolve():this.loadSender()}hasDestination(){return!!this.config.endpoint||this.config.transport!==void 0}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-BESHz6my.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,onLoss:this.reportLoss,remote:this.remote,beforeExit:()=>{this.meter.collect()}});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),this.drops.add(`load_failed`,this.pendingRecords.records)}for(let e of this.pendingRecords.take())this.sender?.push(e)}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 S(()=>this,e.D),once:this.captureOnce,recordMetric:(e,t,n)=>{this.recordMetric(e,t,n)}};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.`,ut[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.meter.collect(),this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.sendForwarded(),this.bus?.destroy(),this.drops.add(`load_failed`,this.pendingRecords.take()),await e,await this.senderLoad,t.pinned()===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.bootBuffer.push(e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad?this.pendingRecords.push(e):(this.diagnostics.count(`record.dropped_no_destination`),this.hasDestination()&&this.drops.add(`load_failed`,[e]))}dropHeld(e){this.diagnostics.count(`record.dropped_boot_buffer_full`),this.drops.add(`buffer_full`,[e])}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1,this.sendForwarded()}))}sendForwarded(){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)r.a(t)?r.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.take(),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)}reportLoss=(e,t,n)=>{this.drops.add(e,t,n)};reportGap=(t,n)=>{this.drops.add(t.reason,n.flatMap(e=>e.records),n.map(e=>e.id));let r=Date.now();r-this.lastGapAt<6e4||(this.lastGapAt=r,new S(()=>this,e.sn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=a.i(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,a.a(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){this.meter.collect(),this.ready||await this.started,this.role()===`forwarder`?this.sendForwarded():(await this.senderLoad,await this.sender?.flush())}};function ft(){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 X=new Map;function Z(){return(Y.current()??Y.stopped())||Y.configure({},!0)}function pt(e){Y.configure(e)}function Q(e,t){if(t)return new S(Z,e,t);let n=X.get(e);return n||(n=new S(Z,e),X.set(e,n)),n}function $(){return Q(`app`)}function mt(e,t){$().trace(e,t)}function ht(e,t){$().debug(e,t)}function gt(e,t){$().info(e,t)}function _t(e,t){$().warn(e,t)}function vt(e,t,n){$().error(e,t,n)}function yt(e,t,n){$().fatal(e,t,n)}function bt(e,t){$().logAction(e,t)}function xt(e,t){$().logEvent(e,t)}function St(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function Ct(e,t={}){let n={name:e,kind:`counter`,unit:t.unit??`count`,boundaries:[]};return{add:(e,t)=>{Z().recordMetric(n,e,t)}}}function wt(t,n={}){let r={name:t,kind:`histogram`,unit:n.unit??`count`,boundaries:n.boundaries??e._t};return{record:(e,t)=>{Z().recordMetric(r,e,t)}}}function Tt(e,t,n){return $().timeSync(e,t,n)}function Et(e,t,n){return $().timeAsync(e,t,n)}function Dt(e,t){Z().context.set(e,t)}function Ot(e){Z().context.setMany(e)}function kt(e){Z().context.remove(e)}function At(e,t){return Z().journey.start(e,t)}function jt(){Z().journey.end()}function Mt(){return Z().journey.current()}function Nt(){return Z().journey.getToken()}function Pt(e){return Z().journey.adopt(e,`manual`,!0)}function Ft(e){Z().registerWorker(e)}function It(){Z().tracing.rotate(`explicit`)}function Lt(){return Z().tracing.headers()}function Rt(){return Z().flush()}function zt(){return Z().queueDepth()}function Bt(){return Z().diagnostics.snapshot()}async function Vt(){await Y.current()?.destroy()}exports.OneLogger=S,exports.adoptJourney=Pt,exports.configure=pt,exports.counter=Ct,exports.createMemoryTransport=ft,exports.currentJourney=Mt,exports.debug=ht,exports.endJourney=jt,exports.error=vt,exports.fatal=yt,exports.flush=Rt,exports.getDiagnosticCounters=Bt,exports.getJourneyToken=Nt,exports.getLogger=Q,exports.getQueueDepth=zt,exports.getTraceHeaders=Lt,exports.histogram=wt,exports.info=gt,exports.logAction=bt,exports.logEvent=xt,exports.logMetric=St,exports.registerWorker=Ft,exports.removeContext=kt,exports.setContext=Dt,exports.setContextMap=Ot,exports.shutdown=Vt,exports.startJourney=At,exports.startTrace=It,exports.timeAsync=Et,exports.timeSync=Tt,exports.trace=mt,exports.warn=_t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-CW-MlHdY.cjs"),t=require("./error-like-gGRx2s36.cjs"),n=require("./sampling-BVjspJWu.cjs"),r=require("./deadline-XSnm95pg.cjs"),i=require("./sanitize-DHucKGdi.cjs"),a=require("./identity-Da9TkuKd.cjs"),o=require("./library-request-BaZOi4eg.cjs"),s=require("./platform-DBSKTvFn.cjs"),c=require("./batch-BQFtb3i5.cjs"),l=require("./journey-B_tTnvac.cjs");function u(t){return Math.round((performance.now()-t)*e.V)/e.V}function d(e,t,n,r,i){e.logMetric(`${t}.duration`,n,`ms`,`histogram`,{status:r,...i})}function f(e,t,n,r,i){let a=u(n);e.error(`${t} failed`,r,{"action.duration_ms":a,status:`FAILURE`,...i}),d(e,t,a,`FAILURE`,i)}function p(e,t,n,r){let i=performance.now();try{let a=n();return d(e,t,u(i),`SUCCESS`,r),a}catch(n){throw f(e,t,i,n,r),n}}async function m(e,t,n,r){let i=performance.now();try{let a=await n();return d(e,t,u(i),`SUCCESS`,r),a}catch(n){throw f(e,t,i,n,r),n}}var h=[e.k,e.ln];function g(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 ee(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function _(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 v(e){if(!n.u(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function y(e){return h.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function b(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var x=class t{bind;namespace;options;levelType;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n,this.levelType=y(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.R,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=b(a,this.bind().diagnostics),s={...o,"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,[e.Ct.attributeKeys]:Object.keys(o)};this.write(`INFO`,`metric`,t,s,!0)};timeSync=(e,t,n)=>p(this,e,t,n);timeAsync=(e,t,n)=>m(this,e,t,n);write(e,t,n,r,i=!1){let a=this.bind();if(a.isDestroyed())return;if(a.isRotating()){a.diagnostics.count(`record.dropped_during_rotation`);return}if(!a.builder.isEnabled(e,this.namespace,t)){this.mirrors(a,e)&&this.print(a,e,n,r,void 0,null);return}let o={level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:i?r:b(r,a.diagnostics)},{record:s,dropped:c}=a.builder.build(o),l=!!a.config.redact||a.config.processors.length>0,u=t!==`metric`&&a.config.capturePolicy.breadcrumbs>0,d=c===`sampling`&&l&&u?a.builder.build(o,!0):void 0,f=s??d?.record??null,p=f?f.body:c===`sampling`&&!l?n:void 0;u&&p!==void 0&&a.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:p}),this.print(a,e,n,r,void 0,f,d?.dropped??c),a.emit(s)}writeError(t,n,r,i){let a=this.bind();if(a.isDestroyed())return;if(a.isRotating()){a.diagnostics.count(`record.dropped_during_rotation`);return}let o=a.builder.isEnabled(t,this.namespace);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.`,()=>v(r))??!1),c=s?r:i,l=s?void 0:r,u=l===void 0?void 0:g(l,a.diagnostics),d=u===void 0?void 0:ee(l,u,a.diagnostics);if(!o){this.print(a,t,n,c,d,null);return}let f=u?_(l,a.diagnostics):void 0,{record:p,dropped:m}=a.builder.build({level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...b(c,a.diagnostics),...u?{"error.type":u.name,"error.message":u.message,"error.stack_trace":u.stack}:{},...f===void 0?{}:{[e.s]:f},[e.o]:a.breadcrumbs.snapshot()}});this.print(a,t,n,c,d,p,m),a.emit(p)}print(e,t,n,r,i,a,o){if(!e.config.redact&&e.config.processors.length===0){e.console.write(this.namespace,t,n,r,i);return}if(a){e.console.write(this.namespace,t,a.body,a.attributes);return}if(o===`processor`||o===`redact`||o===`malformed`||!e.config.enabled||!e.console.accepts(t))return;let s=e.builder.build({level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...b(r,e.diagnostics),...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{}}},!0).record;s&&e.console.write(this.namespace,t,s.body,s.attributes)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},S=`overflow`,te=new Set([e.f,e.d,e.r,e.m,e.c,e.l,e.u]);function ne(e={}){let t={};for(let n of Object.keys(e).sort()){if(n.startsWith(`metric.`)||te.has(n))continue;let r=e[n];(typeof r==`string`||typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r)}return t}function re(e,t){if(!Array.isArray(e))return null;let n=t===0?e.length:Math.min(e.length,t+1);return Array.from({length:n},(t,n)=>e[n])}function ie(e,t){return Array.isArray(e)&&(t===0||e.length<=t)&&e.every((t,n)=>typeof t==`number`&&Number.isFinite(t)&&(n===0||t>e[n-1]))}function ae(t,n,r){let i={"metric.name":t.name,"metric.unit":t.unit,"metric.type":t.kind,[e.Ct.start]:r,[e.Ct.attributeKeys]:Object.keys(n.attributes)};return t.kind===`counter`?(i[`metric.value`]=n.sum,i):{...i,[e.Ct.count]:n.count,[e.Ct.sum]:n.sum,[e.Ct.min]:n.min,[e.Ct.max]:n.max,[e.Ct.bounds]:t.boundaries,[e.Ct.buckets]:n.buckets}}function oe(e,t,n){let r={name:e,kind:`counter`,unit:t.unit??`count`,boundaries:[]};return{add:(e,t)=>{n(r,e,t)}}}function se(t,n,r){let i={name:t,kind:`histogram`,unit:n.unit??`count`,boundaries:n.boundaries??e.St};return{record:(e,t)=>{r(i,e,t)}}}var ce=class{intervalMs;emit;diagnostics;policy;instruments=new Map;timer=null;startedAt=0;constructor(e,t,n,r={maxSeries:100,maxInstruments:1e3,maxHistogramBoundaries:50}){this.intervalMs=e,this.emit=t,this.diagnostics=n,this.policy=r}record(e,t,n){!Number.isFinite(t)||e.kind===`counter`&&t<0?this.diagnostics.report(`record.dropped_malformed`,`The value of the metric ${e.name} is not valid. The library dropped it.`,{"metric.name":e.name}):this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the metric ${e.name}.`,()=>{let r=this.instrumentOf(e);r&&(this.add(r,t,ne(n)),this.arm())})}collect(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let e=`${String(this.startedAt)}000000`,t=[...this.instruments.values()];this.instruments.clear();for(let{def:n,series:r}of t)for(let t of r.values())this.emit(n.name,t.attributes,ae(n,t,e))}instrumentOf(t){let n=this.instruments.get(t.name);if(n)return n.def.kind===t.kind?n:(this.diagnostics.report(`record.dropped_malformed`,`The metric ${t.name} is a counter and a histogram. The library dropped the value.`,{"metric.name":t.name}),null);if(this.policy.maxInstruments&&this.instruments.size>=this.policy.maxInstruments)return this.diagnostics.count(`record.dropped_by_ceiling`),null;let r=re(t.boundaries,this.policy.maxHistogramBoundaries),i=ie(r,this.policy.maxHistogramBoundaries);t.kind===`histogram`&&!i&&this.diagnostics.report(`config.invalid`,`The boundaries of the metric ${t.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`);let a={def:{...t,boundaries:i?r:[...e.St]},series:new Map};return this.instruments.set(t.name,a),a}add(t,n,r){let i=JSON.stringify(r),a=t.series.get(i),o=r;if(!a&&this.policy.maxSeries>0&&t.series.size>=this.policy.maxSeries&&(i=S,a=t.series.get(i),o={[e.p]:!0}),!a){let e=t.def.kind===`histogram`?t.def.boundaries.length+1:0,r=Array(e).fill(0);a={attributes:o,count:0,sum:0,min:n,max:n,buckets:r},t.series.set(i,a)}if(a.count+=1,a.sum+=n,a.min=Math.min(a.min,n),a.max=Math.max(a.max,n),a.buckets.length>0){let e=t.def.boundaries.findIndex(e=>n<=e);a.buckets[e===-1?a.buckets.length-1:e]+=1}}arm(){this.timer===null&&(this.startedAt=Date.now(),this.timer=setTimeout(()=>{this.collect()},this.intervalMs()),r.r(this.timer))}},le={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},ue=class{settings;diagnostics;limits;constructor(t,n,r=e.Ft){this.settings=t,this.diagnostics=n,this.limits=r}update(e){this.settings=e}accepts(t){return this.settings.level===null||!Object.hasOwn(e.mt,this.settings.level)?!1:e.mt[t]>=e.mt[this.settings.level]}write(e,t,n,r,a){if(!this.accepts(t)||typeof console>`u`||i.a())return;let o=`%c[%s]%c[${t}]%c`,{styles:s}=this.settings,c=le[t];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${c}.`,()=>{let l=[];a!==void 0&&l.push(a),r!==void 0&&l.push(i.n(r,this.limits,this.diagnostics)),i.o(()=>{console[c](o,s.namespace,e,s[t],``,n,...l)})})}},de=class{value=0;next(){return++this.value}},fe=/^[0-9a-f]{32}$/,pe=/^[0-9a-f]{16}$/,me=/[1-9a-f]/;function he(e){return fe.test(e.traceId)&&me.test(e.traceId)&&pe.test(e.spanId)&&me.test(e.spanId)}function ge(){return a.o(16)}function C(){return a.o(8)}function w(e){return{traceId:ge(),spanId:C(),traceFlags:1,startedAt:Date.now(),reason:e,ended:!1}}function _e(e,t,n){return`00-${e}-${t}-${(n&255).toString(16).padStart(2,`0`)}`}function ve(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var ye=class{diagnostics;maxAgeMs;load;spans;ambient=w(`start`);otel;constructor(t,n=e.bn,r,i){this.diagnostics=t,this.maxAgeMs=n,this.load=r,this.spans=i}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(){return this.activeSpanContext()??this.ambientContext()}ambientContext(){return Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),ve(this.ambient)}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(he(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){let t=this.ambient;this.ambient=w(e);let n=ve(this.ambient);return this.finish(t),n}end(){this.finish(this.ambient)}finish(e){e.ended||(e.ended=!0,this.spans?.onEnd({traceId:e.traceId,spanId:e.spanId,reason:e.reason,startedAt:e.startedAt,endedAt:Date.now()}))}headers(){return this.trace(!1).headers}request(){return this.trace(!0)}trace(t){let n={},r=this.otel;if(r&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{r.propagation.inject(r.context.active(),n)}),n.traceparent)return{headers:n};let i=this.activeSpanContext(),a=i??this.ambientContext(),o=i?void 0:this.spans;if(!o?.enabled())return n[e.yn]=_e(a.traceId,a.spanId,a.traceFlags),{headers:n};let s=o.keeps(a.traceId),c=s?a.traceFlags:a.traceFlags&-2,l=t?C():a.spanId;return n[e.yn]=_e(a.traceId,l,c),!t||!s?{headers:n}:{headers:n,span:{traceId:a.traceId,spanId:l,parentSpanId:a.spanId}}}},be=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=e===0?0:Math.max(e,1),this.buffer=Array(this.capacity)}resize(e){let t=this.snapshot().slice(-e);if(this.capacity=e,this.buffer=Array(e),this.pointer=0,this.filled=!1,e)for(let e of t)this.push(e)}push(e){this.capacity!==0&&(this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0))}clear(){this.buffer.fill(void 0),this.pointer=0,this.filled=!1}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)}},xe=Object.keys(e.mt),Se=[`gzip`,`none`],Ce=[`omit`,`same-origin`,`include`],we=[`auto`,`indexeddb`,`localstorage`,`memory`,`none`],Te=[`storage`,`memory`],Ee=[`auto`,`sender`,`forwarder`,`off`],De=[`auto`,`provider`,`client`],Oe=[`auto`,`context`,`tab`,`origin`],ke=[`error`,`warn`,`info`,`log`],Ae=[`limited`,`until-delivered`],je={logFlushIntervalMs:[100,6e4],logBatchSize:[1,1e3],metricFlushIntervalMs:[100,6e4],metricBatchSize:[1,1e3]},Me={maxBatches:[1,5e3],maxAgeMs:[6e4,6048e5],maxAttempts:[1,20]},Ne={maxBodyChars:[256,65536],maxAttributeChars:[256,65536],maxAttributeCount:[1,1024],maxStackChars:[256,65536],maxDepth:[1,16],maxArrayLength:[1,1e4],maxNodes:[100,1e5],maxRecordBytes:[1024,e.C]},Pe=[6e4,864e5],T=[0,2147483647],E=[0,2**53-1],D=[1,2**53-1],O={capturePolicy:{ranges:{breadcrumbs:[0,1e6],errorDedupeMs:T,maxErrorSignatures:E,errorsPerWindow:E,consolePerWindow:E,longFramesPerWindow:E,webSocketPerWindow:E,windowMs:T,errorCeiling:E}},metadata:{ranges:{}},persistence:{ranges:{}},diagnostics:{ranges:{throttleMs:T}},correlation:{ranges:{sessionIdleMs:T,sessionTouchMs:T,traceMaxAgeMs:T}},metrics:{ranges:{maxSeries:E,maxInstruments:E,maxHistogramBoundaries:E}},buffering:{ranges:{maxPendingRecords:E,maxPendingBytes:E},choices:{overflow:[`drop-oldest`,`drop-newest`,`persist`]}},delivery:{ranges:{requestTimeoutMs:[1,T[1]],maxConcurrentRequests:D,retryBaseDelayMs:T,retryMaxDelayMs:T,retryIdleDelayMs:T,batchesPerDrain:D}}},Fe=[`errors`,`rejections`,`resourceErrors`,`fetch`,`xhr`,`httpMetrics`,`navigation`,`webVitals`,`longFrames`,`fullUrls`,`webSocket`],Ie=`null`,k=`a level name: ${A(xe)}`,Le=`true, false or a list of ${A(ke)}`,Re=`a list of strings and RegExp patterns`,ze=`a list of origin URLs such as "https://api.example" and RegExp patterns`,Be=`a list of origin URLs such as "https://app.example". For a sandboxed frame, set bus.mode: "sender" in the frame`,Ve=`a list of strings`;function A(e){let t=e.map(e=>`"${e}"`);return`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}function He(e){return typeof e==`string`?`"${e}"`:typeof e==`function`?`a function`:typeof e==`object`&&e?`an object`:String(e)}function j(e,t,n,r,i){e.report(`config.invalid`,`${t} must be ${n}. The value is ${He(r)}. The library keeps ${i}.`)}function M(e,t,n,r,i){if(t===void 0)return r;let a=n.find(e=>e===t);return a===void 0?(j(i,e,A(n),t,`"${r}"`),r):a}function N(e,t,n,r){return t===void 0?n:typeof t==`boolean`?t:(j(r,e,`true or false`,t,String(n)),n)}function Ue(e,t,n,r){return t===void 0?n:typeof t==`number`&&Number.isFinite(t)&&t>=0?t:(j(r,e,`a finite number of 0 or more`,t,String(n)),n)}function P(e,t,n,r,i){if(t===void 0)return r;let[a,o]=n;return typeof t==`number`&&Number.isInteger(t)&&t>=a&&t<=o?t:(j(i,e,`an integer from ${String(a)} to ${String(o)}`,t,String(r)),r)}function We(e,t,n){return e===void 0?t:e===null?null:typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:(j(n,`loggerCache.maxEntries`,`a nonnegative safe integer or null`,e,String(t)),t)}function F(e,t,n,r,i){let a=t??{},o=Object.keys(r);return Object.fromEntries(o.map(t=>[t,P(`${e}.${t}`,a[t],r[t],n[t],i)]))}function I(e){if(typeof e!=`string`)return;let t=e.toUpperCase();return xe.find(e=>e===t)}function Ge(e,t,n,r){if(t===void 0)return n;let i=I(t);return i===void 0?(j(r,e,k,t,`"${n}"`),n):i}function Ke(e,t,r){if(e===void 0)return t;if(!n.u(e))return j(r,`minLevels`,`an object of level names`,e,`the value in force`),t;let i=[];for(let[t,n]of Object.entries(e)){let e=I(n);t!==``&&e!==void 0?i.push([t,e]):j(r,`minLevels["${t}"]`,k,n,`minLevel for it`)}return Object.fromEntries(i)}function L(e,t,n,r,i,a){if(t===void 0)return n;if(!Array.isArray(t))return j(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 ${He(t)}. ${e} must be ${r}.`):o.push(n)}return o}function qe(e){return typeof e==`function`?e:void 0}function Je(e){return n.u(e)&&typeof e.name==`string`&&e.name!==``&&typeof e.install==`function`&&typeof e.uninstall==`function`?e:void 0}function Ye(e){return typeof e==`string`?e:void 0}function Xe(e){return typeof e==`string`||e instanceof RegExp?e:void 0}function Ze(e){return ke.find(t=>t===e)}function Qe(e){if(typeof e==`string`)try{let{origin:t}=new URL(e);return t===Ie?void 0:t}catch{return}}function $e(e){return e instanceof RegExp?e:Qe(e)}function et(e){return n.u(e)?Object.values(e).every(e=>typeof e==`string`):!1}function tt(e,t,n){if(e!==void 0)return typeof e==`function`||et(e)?e:(j(n,`headers`,`an object of strings or a function`,e,`the headers in force`),t)}function nt(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function rt(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||nt(t)?t:(r.report(`config.invalid`,`serializer must be "${e.tn}", "ecs" or an implementation. The library uses "${e.tn}".`),e.tn)}var it=new Set(Object.keys(e.N));function at(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)it.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 ot(e,t,n){if(e===void 0)return t??`DEBUG`;let r=I(e);return r===void 0?(j(n,`console.level`,k,e,`the console level in force`),t):r}function st(t,n,r){if(t===void 0)return n;if(t===!1)return{level:null,styles:n.styles};if(t===!0)return{level:e.M,styles:n.styles};if(typeof t==`string`){let e=I(t);return e===void 0?(j(r,`console`,k,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:ot(t.level,n.level,r),styles:{...n.styles,...at(t.styles,r)}}}function ct(e,t,n){let r=e??{};return{...t,...r,rates:{...t.rates,...r.rates},alwaysSampleTypes:L(`sampling.alwaysSampleTypes`,r.alwaysSampleTypes,t.alwaysSampleTypes,Ve,Ye,n),remote:N(`sampling.remote`,r.remote,t.remote,n)}}function lt(e,t,n){let r=e??{};return{maxTrackedSources:P(`bus.maxTrackedSources`,r.maxTrackedSources,[0,2**53-1],t.maxTrackedSources,n),sourcePolicy:M(`bus.sourcePolicy`,r.sourcePolicy,[`registered`,`trusted-origin`],t.sourcePolicy,n),validation:M(`bus.validation`,r.validation,[`strict`,`envelope`],t.validation,n),maxMessageBytes:P(`bus.maxMessageBytes`,r.maxMessageBytes,[0,2**53-1],t.maxMessageBytes,n),maxRecordsPerMessage:P(`bus.maxRecordsPerMessage`,r.maxRecordsPerMessage,[0,2**53-1],t.maxRecordsPerMessage,n),maxMessagesPerSecond:P(`bus.maxMessagesPerSecond`,r.maxMessagesPerSecond,[0,2**53-1],t.maxMessagesPerSecond,n),mode:M(`bus.mode`,r.mode,Ee,t.mode,n),trustedOrigins:L(`bus.trustedOrigins`,r.trustedOrigins,t.trustedOrigins,Be,Qe,n),openFinRole:M(`bus.openFinRole`,r.openFinRole,De,t.openFinRole,n)}}function ut(e,t,n){let r=e??{};return{scope:M(`journey.scope`,r.scope,Oe,t.scope,n),maxAgeMs:P(`journey.maxAgeMs`,r.maxAgeMs,Pe,t.maxAgeMs,n)}}function dt(e,t,n){let r=e??{};return{mode:M(`retention.mode`,r.mode,Ae,t.mode,n),...F(`retention`,r,t,Me,n)}}function ft(e,t,n){return e===void 0?t:typeof e==`boolean`?e:Array.isArray(e)?L(`capture.console`,e,[],Le,Ze,n):(j(n,`capture.console`,Le,e,`the value in force`),t)}function pt(e,t,n){let r=e??{},i={...t,...r,interactions:mt(r.interactions,t.interactions,n),console:ft(r.console,t.console,n),longFrameThresholdMs:Ue(`capture.longFrameThresholdMs`,r.longFrameThresholdMs,t.longFrameThresholdMs,n),ignoreUrls:L(`capture.ignoreUrls`,r.ignoreUrls,t.ignoreUrls,Re,Xe,n),propagateTraceHeaderTo:L(`capture.propagateTraceHeaderTo`,r.propagateTraceHeaderTo,t.propagateTraceHeaderTo,ze,$e,n),plugins:L(`capture.plugins`,r.plugins,t.plugins,`a list of objects with a name, install() and uninstall()`,Je,n)};for(let e of Fe)i[e]=N(`capture.${e}`,r[e],t[e],n);return i}function mt(e,t,r){if(e===void 0)return t;if(typeof e==`boolean`)return e;if(!n.u(e))return r.report(`config.invalid`,`capture.interactions must be a boolean or an options object.`),t;let i=typeof t==`object`?t:{},a=e.ignoreSelector,o=a===void 0?i.ignoreSelector:a;if(o!=null)try{if(typeof o!=`string`)throw Error(`Invalid selector`);typeof document<`u`&&document.createElement(`div`).matches(o)}catch{r.report(`config.invalid`,`capture.interactions.ignoreSelector must be a valid CSS selector or null.`),o=i.ignoreSelector}let s=i.actionAttribute??`data-observability-action`;return e.actionAttribute!==void 0&&(typeof e.actionAttribute==`string`&&/^[a-z][\w-]*$/i.test(e.actionAttribute)?s=e.actionAttribute:j(r,`capture.interactions.actionAttribute`,`an attribute name of letters, digits, hyphens and underscores`,e.actionAttribute,`"${s}"`)),{actionAttribute:s,text:N(`capture.interactions.text`,e.text,i.text??!1,r),selector:N(`capture.interactions.selector`,e.selector,i.selector??!1,r),ignoreSelector:typeof o==`string`||o===null?o:void 0,maxTextChars:P(`capture.interactions.maxTextChars`,e.maxTextChars,[0,2**53-1],i.maxTextChars??50,r)}}var ht={metricsEndpoint:`The library sends metric records as log records.`,tracesEndpoint:`The library sends no span.`};function gt(t,n,r,i,a){let o=r;if(typeof n==`string`&&n!==``)try{new URL(n),o=n}catch(e){a.report(`config.invalid`,`${t} is not a valid absolute URL: ${n}. The library keeps the value in force.`,void 0,e)}else n===``?o=``:n!==void 0&&j(a,t,`a URL string`,n,`the value in force`);return o!==``&&i!==`otlp`?(a.report(`config.invalid`,`${t} needs serializer "${e.tn}". ${ht[t]}`),``):o}function _t(e,t,n,r,i){let a={...n};for(let o of Object.keys(n)){let s=t?.[o],c=n[o],l=r.ranges[o],u=r.choices?.[o],d=c;typeof c==`number`&&l?d=P(`${e}.${o}`,s,l,c,i):typeof c==`boolean`?d=N(`${e}.${o}`,s,c,i):u?d=M(`${e}.${o}`,s,u,String(c),i):s===void 0||typeof s==`string`?d=s??c:j(i,`${e}.${o}`,`a string`,s,String(c)),Object.assign(a,{[o]:d})}return a}function R(t,n,r){let i=r??e.L,a=Object.fromEntries(Object.keys(O).map(e=>[e,_t(e,t[e],i[e],O[e],n)])),o={...i,...t,...a,lockConfiguration:N(`lockConfiguration`,t.lockConfiguration,i.lockConfiguration,n),loggerCache:{maxEntries:We(t.loggerCache?.maxEntries,i.loggerCache.maxEntries,n)},securityContext:{id:typeof t.securityContext?.id==`string`&&t.securityContext.id||i.securityContext.id,isolation:N(`securityContext.isolation`,t.securityContext?.isolation,i.securityContext.isolation,n)},endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,enabled:N(`enabled`,t.enabled,i.enabled,n),minLevel:Ge(`minLevel`,t.minLevel,i.minLevel,n),minLevels:Ke(t.minLevels,i.minLevels,n),processors:L(`processors`,t.processors,i.processors,`a list of functions`,qe,n),compression:M(`compression`,t.compression,Se,i.compression,n),credentials:M(`credentials`,t.credentials,Ce,i.credentials,n),headers:`headers`in t?tt(t.headers,i.headers,n):i.headers,storage:M(`storage`,t.storage,we,i.storage,n),identity:M(`identity`,t.identity,Te,i.identity,n),serializer:rt(t.serializer,r?.serializer,n),console:st(t.console,i.console,n),sampling:ct(t.sampling,i.sampling,n),bus:lt(t.bus,i.bus,n),batching:F(`batching`,t.batching,i.batching,je,n),retention:dt(t.retention,i.retention,n),limits:F(`limits`,t.limits,i.limits,Ne,n),journey:ut(t.journey,i.journey,n),capture:pt(t.capture,i.capture,n)};for(let e of[`metricsEndpoint`,`tracesEndpoint`])o[e]=gt(e,t[e],i[e],o.serializer,n);if(o.transport!==void 0&&typeof o.transport!=`function`&&(n.report(`config.invalid`,`transport must be a function. The library ignores the value.`),o.transport=i.transport),o.onDrop!==void 0&&typeof o.onDrop!=`function`&&(n.report(`config.invalid`,`onDrop must be a function. The library ignores the value.`),o.onDrop=i.onDrop),o.contextProvider!==void 0&&typeof o.contextProvider!=`function`&&(n.report(`config.invalid`,`contextProvider must be a function. The library ignores the value.`),o.contextProvider=i.contextProvider),o.transportOnExit!==void 0&&typeof o.transportOnExit!=`function`&&(n.report(`config.invalid`,`transportOnExit must be a function. The library ignores the value.`),o.transportOnExit=i.transportOnExit),o.endpoint===``)o.transport===void 0&&n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(o.endpoint!==null)try{new URL(o.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${o.endpoint}.`,void 0,e)}for(let e of[`metricsEndpoint`,`tracesEndpoint`])o[e]!==``&&o.endpoint===null&&!o.transport&&n.report(`config.invalid`,`${e} needs endpoint or transport. The library sends nothing to ${e}.`);o.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.En}'.`),e.En);let s=o.sampling.defaultRate;(typeof s!=`number`||s<0||s>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(s)}. The library uses 1.`),o.sampling.defaultRate=1);let c=o.sampling.remoteMaxRate;(typeof c!=`number`||!(c>=0&&c<=1))&&(n.report(`config.invalid`,`sampling.remoteMaxRate must be 0..1. The value is ${String(c)}. The library uses 1.`),o.sampling.remoteMaxRate=1);let l=Object.entries(o.sampling.rates);for(let[e,t]of l)(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.`),o.sampling.rates[e]=1);o.capture.ignoreUrls=o.capture.ignoreUrls.filter(e=>e!==r?.endpoint&&e!==r?.metricsEndpoint&&e!==r?.tracesEndpoint);for(let e of[o.endpoint,o.metricsEndpoint,o.tracesEndpoint])e&&!o.capture.ignoreUrls.includes(e)&&(o.capture.ignoreUrls=[...o.capture.ignoreUrls,e]);return o.delivery.retryMaxDelayMs<o.delivery.retryBaseDelayMs&&(n.report(`config.invalid`,`delivery.retryMaxDelayMs must be at least retryBaseDelayMs.`),o.delivery.retryBaseDelayMs=i.delivery.retryBaseDelayMs,o.delivery.retryMaxDelayMs=i.delivery.retryMaxDelayMs),o.capture.urlTransform!==void 0&&typeof o.capture.urlTransform!=`function`&&(n.report(`config.invalid`,`capture.urlTransform must be a function.`),o.capture.urlTransform=i.capture.urlTransform),vt(t,n),o}function vt(t,n){let r=new Set([...Object.keys(e.L),...e.wn]);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.j){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.L[r]),...e.Tn[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 z(t,n){for(let r of Object.keys(n))e.j.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.j)Object.assign(t[r],n[r])}var yt=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)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},B=class{handler;throttleMs;consoleFallback;counters=new Map;lastEmitted=new Map;constructor(t,n=e.z,r=!1){this.handler=t,this.throttleMs=n,this.consoleFallback=r}setPolicy(e,t){this.throttleMs=e,this.consoleFallback=t}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,r,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:r,cause:a,at:s,count:o},{handler:l}=this;if(l)try{i.o(()=>{l(c)})}catch{this.count(`handler.threw`),this.consoleFallback&&typeof console<`u`&&i.o(()=>{console.warn(`${e.gt} The onDiagnostic handler threw an error.`)})}}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)}};function V(e,t){e.length<20&&!e.includes(t)&&e.push(t)}var bt=class{config;diagnostics;pending=new Map;scheduled=!1;reporting=!1;constructor(e,t){this.config=e,this.diagnostics=t}add(t,n,r=[]){if(!this.config.onDrop||this.reporting||n.length===0&&r.length===0)return;let i=this.pending.get(t);i||(i={reason:t,records:0,batchIds:[],journeyIds:[],actions:[]},this.pending.set(t,i)),i.records+=n.length;for(let e of r)V(i.batchIds,e);for(let t of n){let n=c.t(t,e.c);typeof n==`string`&&V(i.journeyIds,n);let r=c.r(t)?t.body:void 0;typeof r==`string`&&V(i.actions,r)}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.flush()}))}flush(){this.scheduled=!1;let e=[...this.pending.values()];this.pending.clear();let t=this.config.onDrop;if(t){this.reporting=!0;for(let n of e)this.diagnostics.guard(`handler.threw`,`The onDrop hook threw an error.`,()=>{o.r(()=>{i.o(()=>{t(n)})})});this.reporting=!1}}},H=class{onDrop;held=[];actions=0;constructor(e){this.onDrop=e}get records(){return this.held}get length(){return this.held.length}push(e){let t=c.r(e);if((t?this.actions:this.held.length-this.actions)<(t?2e3:500))this.actions+=+!!t;else{let e=this.held.findIndex(e=>c.r(e)===t),[n]=this.held.splice(e,1);this.onDrop(n)}this.held.push(e)}take(){let e=this.held;return this.held=[],this.actions=0,e}},xt=`error.`,St=[e.m,e.c,e.l],Ct={processor:{label:`A processor`,code:`record.dropped_by_processor`},redact:{label:`The redact hook`,code:`record.dropped_by_redact`}},wt=[`metric.name`,`metric.unit`,`metric.type`,`metric.value`,...Object.values(e.Ct),...Object.values(e.on)];function Tt(e){return Object.fromEntries(wt.filter(t=>t in e).map(t=>[t,e[t]]))}function U(e){return e}var Et=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t,r,i){let{config:a}=this.deps;if(!a.enabled)return!1;if(i!==void 0&&e.pt.includes(i))return!0;let o=this.deps.remote.sampling?.minLevelFor(r)??n.n(r,a);return e.mt[t]>=e.mt[o]}build(t,r=!1){let{config:a,diagnostics:o,tracing:c,journey:l,sequence:u,limits:d,remote:f}=this.deps;if(!r&&!this.isEnabled(t.level,t.namespace,t.type))return o.count(`record.dropped_by_level`),{record:null,dropped:`level`};let p=t.trace??c.resolve(),m=l.current(),h=n.o({level:t.level,type:t.type,namespace:t.namespace,journeyId:m?.id??``,traceId:p.traceId,aggregated:t.aggregated},a,f.sampling?.current()??null);if(!r&&!h)return o.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let g=u.next(),ee=s.t(o),_=a.metadata.pageUrl?s.i(ee,a.capture.fullUrls,a.capture.urlTransform,o):``,v,y=0;try{let e=i.r(this.deps.context.getAll(),d,o),n=i.r(this.provided(),d,o),r=i.r(t.scoped??{},d,o),a=i.r(t.payload??{},d,o);y=e.bytes+n.bytes+r.bytes+a.bytes,v={...U(e.value),...U(n.value),...U(r.value),...U(a.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),v={[e.h]:!0}}Object.assign(v,t.fixed),v[e.f]=t.type,v[e.d]=g,v[e.r]=t.namespace,v[e.m]=_,m&&(v[e.c]=m.id,v[e.l]=m.name,m.parentId!==void 0&&(v[e.u]=m.parentId));let b=i.i(t.body,d.maxBodyChars);b!==t.body&&o.count(`record.truncated`);let x={timeUnixNano:n.l(),traceId:p.traceId,spanId:p.spanId,traceFlags:p.traceFlags,severityNumber:e.an[t.level],severityText:t.level,body:b,attributes:v,resource:this.resource()},S=a.processors.map(e=>[e,`processor`]);if(a.redact&&S.push([a.redact,`redact`]),S.length>0){let e=this.applyHooks(x,S,t.fixed);if(typeof e==`string`)return{record:null,dropped:e};({record:x,bytes:y}=e)}if(y>d.maxRecordBytes){o.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped the caller attributes.`,{bytes:y,body:x.body});let n={[e.f]:t.type,[e.d]:g,[e.r]:t.namespace,[e.a]:!0,[e.i]:y};for(let e of St)e in x.attributes&&(n[e]=x.attributes[e]);for(let[e,t]of Object.entries(x.attributes))e.startsWith(xt)&&(n[e]=t);let r=i.r(n,d,o).bytes;r>d.maxRecordBytes&&`error.data`in n&&(Reflect.deleteProperty(n,e.s),r=i.r(n,d,o).bytes);let a=x.attributes[e.o];if(a!==void 0){let t=i.r(a,d,o).bytes;r+t<=d.maxRecordBytes&&(n[e.o]=a)}Object.assign(n,t.fixed),x.attributes=n}return{record:x}}redactForwarded(e){let{redact:t}=this.deps.config;if(!t)return e;let n=[[t,`redact`]],r=this.applyHooks(e,n,Tt(e.attributes));return typeof r==`string`?null:r.record}applyHooks(e,t,n){let r=e;for(let[e,n]of t){let t=this.runHook(e,n,r);if(typeof t==`string`)return t;r=t}let{diagnostics:a,limits:o}=this.deps,s=i.r(r.attributes,o,a),c=U(s.value);return Object.assign(c,n),{record:{...r,attributes:c},bytes:s.bytes}}runHook(t,r,i){let{diagnostics:a}=this.deps,{label:o,code:s}=Ct[r],c;try{c=t(i)}catch(e){return a.report(s,`${o} threw an error. The library dropped the record.`,void 0,e),r}if(c===null)return a.count(s),r;let l=c??i;return n.c(l)?n.s(l.severityText)?{...l,severityNumber:e.an[l.severityText]}:(a.report(`record.dropped_malformed`,`${o} set a severityText that is not a log level. The library dropped the record.`),`malformed`):l===i?(a.report(`record.dropped_malformed`,`${o} changed the record to a shape that is not a record. The library dropped it.`),`malformed`):(a.report(s,`${o} returned a value that is not a record. The library dropped the record.`),r)}provided(){let e=this.deps.config.contextProvider;if(!e)return{};let{diagnostics:t}=this.deps,r=t.guard(`handler.threw`,`The contextProvider threw an error. The record has no attributes from it.`,()=>{let t=e();return t===void 0?{}:n.u(t)&&typeof t.then!=`function`?t:null});return r===null&&t.report(`config.invalid`,`contextProvider must return an object of attributes. The library ignores the value.`),r??{}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Gt]:t.serviceName,[e.Kt]:t.serviceVersion,[e.Vt]:t.environment,[e.Xt]:e._n,[e.Zt]:e.vn,[e.Yt]:e.gn,[e.Ht]:r.platform,[e.qt]:n.sessionId,[e.Jt]:n.tabId,[e.Bt]:n.contextId,...t.metadata.userAgent?{[e.zt]:r.userAgent}:{},...!t.metadata.openfin||r.openfinUuid===void 0?{}:{[e.Wt]:r.openfinUuid},...!t.metadata.openfin||r.openfinName===void 0?{}:{[e.Ut]:r.openfinName}},this.resourceCache}},Dt=1e3,Ot={start:`ui.start`,interaction:`ui.interaction`,navigation:`ui.navigation`,explicit:`ui.trace`,maxAge:`ui.trace`};function kt(e){return`${String(Math.round(e*Dt))}000`}function At(e){return{name:Ot[e.reason],kind:`internal`,traceId:e.traceId,spanId:e.spanId,parentSpanId:``,startMs:e.startedAt,endMs:e.endedAt,error:!1,attributes:{}}}function jt(t){return{[e.on.kind]:t.kind,[e.on.parentId]:t.parentSpanId,[e.on.start]:kt(t.startMs),[e.on.end]:kt(t.endMs),[e.on.status]:t.error?`error`:`unset`}}var Mt={errors:async()=>(await Promise.resolve().then(()=>require("./errors-CgY633cG.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-CF8UO5PK.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-NHbLKrqe.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-DFuoTQbZ.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-CF3qiSAX.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-Ce6heqZZ.cjs"))).ConsoleCapture},Nt=new WeakMap,Pt=0;function Ft(e){let t=Nt.get(e);return t===void 0&&(t=++Pt,Nt.set(e,t)),t}var W=Symbol.for(e.Qt),G=Symbol.for(e.$t),It=[`batching`,`retention`],K={endpoint:null,metricsEndpoint:``,tracesEndpoint:``,headers:void 0,credentials:`omit`,transport:void 0,transportOnExit:void 0},Lt=Object.keys(K);function Rt(e){return JSON.stringify({...e,urlTransform:e.urlTransform?Ft(e.urlTransform):void 0,webVitalsLoader:e.webVitalsLoader!==void 0,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String),plugins:e.plugins.map(Ft)})}function zt(e){return{...e,endpoint:null,metricsEndpoint:``,tracesEndpoint:``,transport:void 0,transportOnExit:void 0,bus:{...e.bus,mode:`off`}}}function Bt(e){return!!e.endpoint||!!e.metricsEndpoint||!!e.tracesEndpoint||e.transport!==void 0}function q(t){return t.sdkVersion===e.vn}var J=class t{rotating=!1;closingContext=!1;mismatchVersion=null;contextMismatch=!1;rotation;memoryStorage;explicitSecurityContext;ownerAdopted=!1;isRotating(){return this.rotating}setConfigurationLocked(e){typeof e==`boolean`&&(this.config.lockConfiguration=e)}static local=null;sdkVersion=e.vn;diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new yt;breadcrumbs;tracing;sequence=new de;journey;builder;remote={sampling:null};console;drops;meter;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=new H(e=>{this.dropHeld(e)});captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1};bootBuffer=new H(e=>{this.dropHeld(e)});forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;started=Promise.resolve();ready=!1;destroyed=!1;lastGapAt=0;limits;journeyOptions;tunablesLocked=!0;degraded;serverReported=!1;onPageHide=()=>{this.role()===`forwarder`&&(this.tracing.end(),this.sendForwarded())};constructor(e,t=!1){this.diagnostics=new B(e.onDiagnostic),this.platform=s.n(this.diagnostics),this.degraded=t||this.onServer(),this.config=R(this.allowed(e),this.diagnostics),this.explicitSecurityContext=!!e.securityContext?.id,this.config.securityContext.id||=a.i(this.diagnostics),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`||this.onServer()?a.r():a.t,this.identity=a.s(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.sessionTouch=new a.n(this.diagnostics,this.stores,this.config.correlation.sessionTouchMs,this.config.correlation.sessionIdleMs),this.breadcrumbs=new be(this.config.capturePolicy.breadcrumbs);let r=e=>n.i(e,this.config.sampling.defaultRate);this.tracing=new ye(this.diagnostics,this.config.correlation.traceMaxAgeMs||1/0,this.config.otelLoader,{enabled:()=>this.config.tracesEndpoint!==``,keeps:r,onEnd:e=>{r(e.traceId)&&this.recordSpan(At(e))}}),this.tracing.loadOtel(),this.limits={...this.config.limits},this.console=new ue(this.config.console,this.diagnostics,this.limits),this.drops=new bt(this.config,this.diagnostics),this.journeyOptions={...l.t,maxAgeMs:this.config.journey.maxAgeMs},this.journey=new l.n(this.journeyOptions,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new Et({remote:this.remote,config:this.config,limits:this.limits,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform}),this.meter=new ce(()=>this.config.batching.metricFlushIntervalMs,(e,t,n)=>{this.emitPoint(e,t,n)},this.diagnostics,this.config.metrics)}addBreadcrumb(e,t){this.rotating||this.destroyed||this.diagnostics.guard(`record.sanitize_failed`,`The library could not add the breadcrumb.`,()=>{let r={t:Date.now(),category:`custom`,message:i.i(String(e),this.limits.maxBodyChars)};if(t!==void 0){let e=i.n(t,this.limits,this.diagnostics);r.data=n.u(e)?e:{value:e}}this.breadcrumbs.push(r)})}recordMetric(e,t,n){!this.destroyed&&!this.rotating&&this.meter.record(e,t,n)}recordSpan(t){if(this.config.tracesEndpoint===``)return;let{record:n}=this.builder.build({level:`INFO`,type:`span`,body:t.name,namespace:e.xn,payload:t.attributes,fixed:jt(t),trace:{traceId:t.traceId,spanId:t.spanId,traceFlags:1}});this.emit(n)}emitPoint(t,n,r){let{record:i}=this.builder.build({level:`INFO`,type:`metric`,body:t,namespace:e.wt,payload:n,fixed:r,aggregated:!0});this.emit(i)}busCanAccept=(e,t)=>this.bus?.isRegistered(e,t)??!1;busAccept=(e,t,n)=>{this.destroyed||this.ensureBus().then(r=>{r&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{r.acceptDirect(e,t,n)})})};static pinned(){return globalThis[W]??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[G];return n&&q(n)?n:null}isDestroyed(){return this.destroyed}static configure(e,n=!1){let r=t.local;if(r&&!r.destroyed)return r.reconfigure(e),r;t.local=null;let i=t.pinned();if(i){if(!q(i))return t.startDegraded(e,i.sdkVersion);if(!i.destroyed)return i.reconfigure(e),i}let a=new t(e);return a.tunablesLocked=!n,globalThis[W]=a,Reflect.deleteProperty(globalThis,G),a.init(),a}static startDegraded(n,r){let i=new t(n,!0);t.local=i;let a=typeof r==`string`?r:`before 0.9.0`;return i.mismatchVersion=a,i.diagnostics.report(`runtime.version_mismatch`,`Another copy of the library, version ${a}, owns the page runtime. This copy, version ${e.vn}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:a,own:e.vn}),i.init(),i}reconfigure(e){if(this.rotating){this.diagnostics.report(`config.locked`,`Configuration cannot change during security-context rotation.`);return}if(this.config.lockConfiguration){let t=R(e,this.diagnostics,this.config);Y(this.config,t)||this.diagnostics.report(`config.locked`,`Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.`);return}let t=this.keepDestination(this.keepRouting(this.allowed(e)));!this.tunablesLocked&&t.securityContext?.id&&(this.explicitSecurityContext=!0);for(let e of[`correlation`,`persistence`])(e!==`persistence`||this.tunablesLocked||this.senderLoad!==void 0)&&t[e]&&!Y({...this.config[e],...t[e]},this.config[e])&&(this.diagnostics.report(`config.invalid`,`${e} cannot change after startup.`),Object.assign(t,{[e]:this.config[e]}));let n=Rt(this.config.capture),r=R(t,this.diagnostics,this.config);this.keepStartupTunables(r),z(this.config,r),this.breadcrumbs.resize(this.config.capturePolicy.breadcrumbs),this.diagnostics.setHandler(this.config.onDiagnostic),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),Rt(this.config.capture)!==n&&this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}onServer(){return this.platform.platform===`node`}allowed(e){return this.degraded?(this.onServer()&&!this.serverReported&&Bt(e)&&(this.serverReported=!0,this.diagnostics.report(`config.invalid`,`The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint and transport.`)),zt(e)):e}keepRouting(e){if(!this.tunablesLocked||this.degraded||!this.config.securityContext.isolation)return e;let t=R(e,new B,this.config),n=Lt.filter(e=>!Y(t[e],this.config[e]));if(t.securityContext.id!==this.config.securityContext.id&&n.push(`securityContext.id`),n.length===0)return e;let r={...e};for(let e of Lt)n.includes(e)&&Reflect.deleteProperty(r,e);if(n.includes(`securityContext.id`)){let t={...e.securityContext};Reflect.deleteProperty(t,`id`),r.securityContext=t}return this.diagnostics.report(`config.invalid`,`Isolation refuses changes to ${n.join(`, `)}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`),r}keepStartupTunables(e){if(this.senderLoad!==void 0&&this.keepSections(e,It),!this.tunablesLocked){this.tunablesLocked=!0,Object.assign(this.limits,e.limits),this.journeyOptions.maxAgeMs=e.journey.maxAgeMs;return}this.keepSections(e,[`limits`]);let{maxAgeMs:t}=this.config.journey;e.journey.maxAgeMs!==t&&(this.diagnostics.report(`config.invalid`,`journey.maxAgeMs cannot change after startup. It stays ${String(t)}.`,{requested:e.journey.maxAgeMs}),e.journey.maxAgeMs=t)}keepSections(e,t){for(let n of t)Y(e[n],this.config[n])||(this.diagnostics.report(`config.invalid`,`${n} cannot change after startup. The values in force stay.`,{requested:e[n]}),Object.assign(e,{[n]:this.config[n]}))}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(){this.degraded||addEventListener(`pagehide`,this.onPageHide);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-BW6N-pY8.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onSecurityContext:e=>{if(this.explicitSecurityContext&&this.config.securityContext.id!==e)return this.contextMismatch=!0,this.diagnostics.report(`security.context_mismatch`,`The configured security context differs from the upstream owner.`),!1;if(this.contextMismatch=!1,this.config.securityContext.id!==e){if(this.ownerAdopted){this.drops.add(`security_context`,[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer]),this.forwardBuffer=[],this.context.clear(),this.breadcrumbs.clear();let e=this.rotating;this.rotating=!0,this.meter.collect();let t=this.sessionTouch.stored();this.resetSession(t!==void 0&&t!==this.identity.sessionId?t:a.i(this.diagnostics)),this.rotating=e}this.config.securityContext.id=e}return this.ownerAdopted=!0,!0},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.hasDestination()||this.role()!==`sender`?Promise.resolve():this.loadSender()}hasDestination(){return!!this.config.endpoint||this.config.transport!==void 0}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-D3fRCR8d.cjs")),t=this.destroyed?null:await e.create({storage:this.memoryStorage,onStorage:e=>{e.name===`memory`&&(this.memoryStorage=e)},config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,onLoss:this.reportLoss,remote:this.remote,beforeExit:()=>{this.meter.collect(),this.tracing.end()}});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),this.drops.add(`load_failed`,this.pendingRecords.records)}for(let e of this.pendingRecords.take())this.sender?.push(e)}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,a]=await Promise.all([Promise.all(r.map(e=>this.loadCapture(e))),n.webSocket?this.loadWebSocket():void 0]);if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let o={isActive:()=>!this.destroyed&&!this.rotating,config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new x(()=>this,e.k),once:this.captureOnce,recordMetric:(e,t,n)=>{this.recordMetric(e,t,n)},recordSpan:e=>{this.recordSpan(e)}};for(let e of i)e&&this.captures.push(new e(o));let s=a?[...n.plugins,new a(this.diagnostics,this.config)]:n.plugins;for(let e of s)this.captures.push(this.pluginCapture(e));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}loadWebSocket(){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the webSocket capture.`,async()=>(await Promise.resolve().then(()=>require("./web-socket-BacvKOvD.cjs"))).WebSocketCapture)}pluginCapture(t){let{name:n}=t,r=(e,t,n)=>{this.recordMetric(e,t,n)},i={logger:new x(()=>this,`${e.k}.${n}`),counter:(e,t={})=>oe(e,t,r),histogram:(e,t={})=>se(e,t,r),addBreadcrumb:(e,t)=>{this.addBreadcrumb(e,t)},ownRequest:o.r};return{name:n,install:()=>{t.install(i)},uninstall:()=>{t.uninstall()}}}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,Mt[e])}registerWorker(e,t={}){let n=!1,r;return this.destroyed?()=>void 0:(this.constructBus().then(i=>{!i||this.destroyed||n||(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{r=i.attachWorker(e,t)}),this.ensureBus())}),()=>{n=!0,r?.()})}registerFrame(e,t){let n=!1,r;return this.constructBus().then(i=>{!i||this.destroyed||n||(r=this.diagnostics.guard(`bus.send_failed`,`The frame could not be registered.`,()=>i.registerFrame(e,t)),this.ensureBus())}),()=>{n=!0,r?.()}}async destroy(){if(this.destroyed)return;this.meter.collect(),this.tracing.end(),this.destroyed=!0,this.degraded||removeEventListener(`pagehide`,this.onPageHide),this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.sendForwarded(),this.bus?.destroy(),this.drops.add(`load_failed`,this.pendingRecords.take()),await e,await this.senderLoad,await this.rotation?.catch(()=>void 0),await this.memoryStorage?.close(),t.pinned()===this&&(Reflect.deleteProperty(globalThis,W),globalThis[G]=this)}emit(e){!e||this.destroyed||this.rotating&&!this.closingContext||(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.bootBuffer.push(e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad?this.pendingRecords.push(e):(this.diagnostics.count(`record.dropped_no_destination`),this.hasDestination()&&this.drops.add(`load_failed`,[e]))}dropHeld(e){this.diagnostics.count(`record.dropped_boot_buffer_full`),this.drops.add(`buffer_full`,[e])}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1,this.sendForwarded()}))}sendForwarded(){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}ingestForwarded(e){if(this.destroyed)return;if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}let t=[];for(let r of e){if(!n.c(r)){this.diagnostics.count(`record.dropped_malformed`);continue}if(!n.a(r,this.config,this.remote.sampling?.current()??null)){this.diagnostics.count(`record.dropped_by_sampling`);continue}let e=this.builder.redactForwarded(r);e&&t.push(e)}if(this.rotating)this.drops.add(`security_context`,t);else for(let e of t)this.deliver(e)}releaseBootBuffer(){let e=this.bootBuffer.take(),{processors:t,redact:n}=this.config,r=t.length===0&&n===void 0?this.journey.current():null;for(let t of e)r&&!t.attributes[`journey.id`]&&(t.attributes[`journey.id`]=r.id,t.attributes[`journey.name`]=r.name),this.route(t)}reportLoss=(e,t,n)=>{this.drops.add(e,t,n)};reportGap=(t,n)=>{this.drops.add(t.reason,n.flatMap(e=>e.records),n.map(e=>e.id));let r=Date.now();r-this.lastGapAt<6e4||(this.lastGapAt=r,new x(()=>this,e.ln).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=a.i(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,a.a(e,this.diagnostics,this.stores),this.builder.invalidateResource()}newSession(){this.destroyed||this.resetSession(a.i(this.diagnostics))}resetSession(e){this.meter.collect(),this.tracing.rotate(`explicit`),this.journey.end(),this.breadcrumbs.clear(),this.identity.sessionId=e,this.sessionTouch.restart(e),this.builder.invalidateResource()}rotateSecurityContext(e,t={}){if(this.rotation)return Promise.reject(Error(`A security-context rotation is already running.`));let r=t.pending??`discard`,i=t.timeoutMs??5e3;return!n.u(e)||!n.u(e.delivery)||![`discard`,`flush`,`retain`,`carry`].includes(r)||!Number.isFinite(i)||i<0||e.id!==void 0&&(typeof e.id!=`string`||e.id.length===0)?Promise.reject(Error(`Invalid security-context rotation options.`)):this.destroyed?Promise.reject(Error(`The runtime has stopped.`)):(this.rotating=!0,this.rotation=this.rotateContext(e,r,i).finally(()=>{this.rotating=!1,this.rotation=void 0}),this.rotation)}async rotateContext(e,t,n){if(await this.started,this.role()===`forwarder`)throw Error(`Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.`);await this.senderLoad;let r=this.config.securityContext.id,i=e.id??a.i(this.diagnostics);if(i===r)throw Error(`A rotation requires a different security-context id.`);let o={...K,...e.delivery},s=this.diagnostics.snapshot()[`config.invalid`]??0,c=R(this.allowed({...o,securityContext:{id:i}}),this.diagnostics,{...this.config,...K});if((this.diagnostics.snapshot()[`config.invalid`]??0)!==s)throw Error(`Invalid delivery settings for the next security context.`);let l=e.context?Object.fromEntries(Object.entries(e.context)):void 0,u=new Set([this.config.endpoint,this.config.metricsEndpoint,this.config.tracesEndpoint]),d=new Set([c.endpoint,c.metricsEndpoint,c.tracesEndpoint]);c.capture.ignoreUrls=c.capture.ignoreUrls.filter(e=>!u.has(e)||d.has(e)),this.closingContext=!0;try{this.meter.collect(),this.tracing.end(),this.journey.end()}finally{this.closingContext=!1}let f=[...this.bootBuffer.take(),...this.pendingRecords.take(),...this.forwardBuffer];this.forwardBuffer=[];let p=this.sender;this.sender=void 0,this.senderLoad=void 0;let m=await p?.retire(t,n,r)??{buffered:[],stored:[]};if(this.destroyed)return;let h=[...f,...m.buffered],g=m.stored.flatMap(e=>e.records);t!==`retain`&&t!==`carry`&&this.drops.add(`security_context`,[...h,...g]),c.lockConfiguration=this.config.lockConfiguration,z(this.config,c),this.remote.sampling=null,this.context.clear(),l&&this.context.setMany(l),this.breadcrumbs.clear(),this.newSession(),this.builder.invalidateResource(),await this.syncSender(),this.bus?.rotateContext(),t===`carry`&&(this.rotating=!1,await this.carry(h,m.stored)),this.diagnostics.report(`security.rotated`,`The runtime rotated its security context.`,{pending:t})}async carry(e,t){for(let t of e)this.route(t);this.sender&&await this.sender.adopt(t,this.config.securityContext.id)}async health(){let e=this.sender?.stats()??{pending:0,inFlight:0,lastSendAt:null},t=[];this.mismatchVersion&&t.push(`runtime.version_mismatch`),this.contextMismatch&&t.push(`security.context_mismatch`),this.ready&&this.hasDestination()&&this.role()===`sender`&&!this.sender&&t.push(`sender.unavailable`);let{sourcePolicy:n,validation:r,maxMessageBytes:i,maxRecordsPerMessage:a,maxMessagesPerSecond:o,maxTrackedSources:s}=this.config.bus;return{...e,pending:e.pending+this.bootBuffer.length+this.pendingRecords.length+this.forwardBuffer.length,stored:await this.sender?.queueDepth()??0,sdkVersion:this.sdkVersion,owningSdkVersion:this.mismatchVersion,status:this.destroyed?`stopped`:this.rotating?`rotating`:t.length?`degraded`:this.ready?`ready`:`starting`,mode:this.role()===`forwarder`?`forwarder`:this.hasDestination()?`sender`:`console-only`,senderReady:this.sender!==void 0&&!this.destroyed&&!this.rotating,configurationLocked:this.config.lockConfiguration,issues:t,securityContext:{...this.config.securityContext},bus:{sourcePolicy:n,validation:r,maxMessageBytes:i,maxRecordsPerMessage:a,maxMessagesPerSecond:o,maxTrackedSources:s}}}async stats(){let e=await this.queueDepth(),t=this.sender?.stats()??{pending:0,inFlight:0,lastSendAt:null},n=this.bootBuffer.length+this.pendingRecords.length+this.forwardBuffer.length;return{...t,pending:t.pending+n,stored:e}}async clearPersisted(e){if(await this.senderLoad,this.sender){await this.sender.clearPersisted(e,this.config.securityContext.id);return}let[{createStorage:t,storageName:n},{ContextStorage:r},{storageLimits:i},{clearEmergencyContext:a}]=await Promise.all([Promise.resolve().then(()=>require("./factory-CNj4DH3n.cjs")),Promise.resolve().then(()=>require("./context-storage-BjzeBSxH.cjs")),Promise.resolve().then(()=>require("./storage-BA9RqRO-.cjs")),Promise.resolve().then(()=>require("./emergency-queue-Cs1hrjsC.cjs"))]),o=this.config.persistence.namespace,s=this.memoryStorage??await t(this.config.storage,n(o),i(this.config.retention),this.diagnostics,void 0,o),c=new r(s,this.config.securityContext,o);try{e===`namespace`?await c.clearNamespace():await c.clear(),a(this.config.securityContext.id,this.diagnostics,o,e===`namespace`)}finally{s!==this.memoryStorage&&await c.close()}}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){this.meter.collect(),this.ready||await this.started,this.role()===`forwarder`?this.sendForwarded():(await this.senderLoad,await this.sender?.flush())}};function Y(e,t,n=new WeakMap){if(Object.is(e,t))return!0;if(e instanceof RegExp&&t instanceof RegExp)return String(e)===String(t);if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Object.keys(e),i=Object.keys(t);return r.length===i.length&&r.every(r=>Object.hasOwn(t,r)&&Y(Reflect.get(e,r),Reflect.get(t,r),n))}function Vt(){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 X=new Map;function Z(){return(J.current()??J.stopped())||J.configure({},!0)}function Ht(e=`context`){return[`context`,`namespace`].includes(e)?Z().clearPersisted(e):Promise.reject(Error(`Invalid persistence scope.`))}function Ut(e){J.configure(e),Q()}function Wt(e){Z().setConfigurationLocked(e)}function Gt(e,t){return Z().rotateSecurityContext(e,t)}async function Kt(){let e=Z();return Q(),{...await e.health(),loggerCache:{...e.config.loggerCache,size:X.size}}}function Q(){let e=(J.current()??J.stopped())?.config.loggerCache.maxEntries,t=e===void 0?256:e;if(t!==null)for(let e of X.keys()){if(X.size<=t)break;X.delete(e)}return t}function qt(e,t){let n=Q();if(t||n===0)return new x(Z,e,t);let r=X.get(e);return r??=new x(Z,e),X.delete(e),X.set(e,r),Q(),r}function $(){return qt(`app`)}function Jt(e,t){$().trace(e,t)}function Yt(e,t){$().debug(e,t)}function Xt(e,t){$().info(e,t)}function Zt(e,t){$().warn(e,t)}function Qt(e,t,n){$().error(e,t,n)}function $t(e,t,n){$().fatal(e,t,n)}function en(e,t){$().logAction(e,t)}function tn(e,t){$().logEvent(e,t)}function nn(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function rn(e,t={}){return oe(e,t,(e,t,n)=>{Z().recordMetric(e,t,n)})}function an(e,t={}){return se(e,t,(e,t,n)=>{Z().recordMetric(e,t,n)})}function on(e,t,n){return $().timeSync(e,t,n)}function sn(e,t,n){return $().timeAsync(e,t,n)}function cn(e,t){Z().addBreadcrumb(e,t)}function ln(e,t){Z().context.set(e,t)}function un(e){Z().context.setMany(e)}function dn(e){Z().context.remove(e)}function fn(e,t){return Z().journey.start(e,t)}function pn(){Z().journey.end()}function mn(){return Z().journey.current()}function hn(){return Z().journey.getToken()}function gn(e){return Z().journey.adopt(e,`manual`,!0)}function _n(e,t){return Z().registerWorker(e,t)}function vn(e,t){return Z().registerFrame(e,t)}function yn(){Z().tracing.rotate(`explicit`)}function bn(){return Z().tracing.headers()}function xn(){return Z().flush()}function Sn(){return Z().queueDepth()}function Cn(){return Z().stats()}function wn(){Z().newSession()}function Tn(){return Z().diagnostics.snapshot()}async function En(){await J.current()?.destroy()}exports.OneLogger=x,exports.addBreadcrumb=cn,exports.adoptJourney=gn,exports.clearPersistedLogs=Ht,exports.configure=Ut,exports.counter=rn,exports.createMemoryTransport=Vt,exports.currentJourney=mn,exports.debug=Yt,exports.endJourney=pn,exports.error=Qt,exports.fatal=$t,exports.flush=xn,exports.getDiagnosticCounters=Tn,exports.getHealth=Kt,exports.getJourneyToken=hn,exports.getLogger=qt,exports.getQueueDepth=Sn,exports.getStats=Cn,exports.getTraceHeaders=bn,exports.histogram=an,exports.info=Xt,exports.logAction=en,exports.logEvent=tn,exports.logMetric=nn,exports.newSession=wn,exports.registerFrame=vn,exports.registerWorker=_n,exports.removeContext=dn,exports.rotateSecurityContext=Gt,exports.setConfigurationLocked=Wt,exports.setContext=ln,exports.setContextMap=un,exports.shutdown=En,exports.startJourney=fn,exports.startTrace=yn,exports.timeAsync=sn,exports.timeSync=on,exports.trace=Jt,exports.warn=Zt;
2
2
  //# sourceMappingURL=index.cjs.map