@utk09/ui-observability 0.9.5 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +315 -99
- package/bin/uiobs.mjs +8 -0
- package/dist/{batch-BQFtb3i5.cjs → batch-C8OcWR2L.cjs} +2 -2
- package/dist/{batch-BQFtb3i5.cjs.map → batch-C8OcWR2L.cjs.map} +1 -1
- package/dist/{batch-BUJh-1jZ.js → batch-CL9uWYY3.js} +5 -6
- package/dist/{batch-BUJh-1jZ.js.map → batch-CL9uWYY3.js.map} +1 -1
- package/dist/bus/bus.d.ts +15 -0
- package/dist/{bus-DeOPHWaD.js → bus-BZ0GldpT.js} +125 -112
- package/dist/bus-BZ0GldpT.js.map +1 -0
- package/dist/bus-VWlmM5xs.cjs +2 -0
- package/dist/bus-VWlmM5xs.cjs.map +1 -0
- package/dist/capture/interactions.d.ts +18 -0
- package/dist/capture/lifecycle.d.ts +20 -0
- package/dist/capture/reports.d.ts +17 -0
- package/dist/capture/resource-timing.d.ts +14 -0
- package/dist/capture/server-timing.d.ts +19 -0
- package/dist/capture/types.d.ts +13 -0
- package/dist/capture/unclean-exit.d.ts +31 -0
- package/dist/capture/user-timing.d.ts +22 -0
- package/dist/console-BPZCuSLc.cjs +2 -0
- package/dist/console-BPZCuSLc.cjs.map +1 -0
- package/dist/{console-DbAZYJuy.js → console-BeCF7n59.js} +20 -20
- package/dist/{console-DbAZYJuy.js.map → console-BeCF7n59.js.map} +1 -1
- package/dist/constants-DqKJH_MP.cjs +2 -0
- package/dist/constants-DqKJH_MP.cjs.map +1 -0
- package/dist/constants-zyrqveN4.js +304 -0
- package/dist/constants-zyrqveN4.js.map +1 -0
- package/dist/constants.d.ts +58 -2
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
- package/dist/{context-storage-DxZf4Gfh.js → context-storage-BzkoHzkQ.js} +2 -3
- package/dist/{context-storage-DxZf4Gfh.js.map → context-storage-BzkoHzkQ.js.map} +1 -1
- package/dist/core/debug-buffer.d.ts +34 -0
- package/dist/core/debug-bundle.d.ts +12 -0
- package/dist/core/deferred.d.ts +7 -0
- package/dist/core/logger.d.ts +7 -2
- package/dist/core/measure.d.ts +19 -0
- package/dist/core/pipeline.d.ts +6 -1
- package/dist/core/record.d.ts +20 -1
- package/dist/core/remote-sampling.d.ts +5 -1
- package/dist/core/runtime.d.ts +45 -2
- package/dist/core/sampling.d.ts +5 -4
- package/dist/core/sender.d.ts +3 -1
- package/dist/core/spans.d.ts +5 -0
- package/dist/{deadline-5_PecIl5.js → deadline-BOjOxNHj.js} +3 -5
- package/dist/{deadline-5_PecIl5.js.map → deadline-BOjOxNHj.js.map} +1 -1
- package/dist/deadline-XSnm95pg.cjs.map +1 -1
- package/dist/debug-bundle-BzJNpbF0.cjs +2 -0
- package/dist/debug-bundle-BzJNpbF0.cjs.map +1 -0
- package/dist/debug-bundle-C7UkHZ-q.js +25 -0
- package/dist/debug-bundle-C7UkHZ-q.js.map +1 -0
- package/dist/doctor.cjs +2 -0
- package/dist/doctor.cjs.map +1 -0
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +98 -0
- package/dist/doctor.js.map +1 -0
- package/dist/{emergency-queue-Cs1hrjsC.cjs → emergency-queue-CNTRui5t.cjs} +2 -2
- package/dist/{emergency-queue-Cs1hrjsC.cjs.map → emergency-queue-CNTRui5t.cjs.map} +1 -1
- package/dist/{emergency-queue-BYUyDHGD.js → emergency-queue-Zy6lNafo.js} +17 -19
- package/dist/{emergency-queue-BYUyDHGD.js.map → emergency-queue-Zy6lNafo.js.map} +1 -1
- package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
- package/dist/{error-like-Ywo5uRHo.js.map → error-like-B11pB4aL.js.map} +1 -1
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-BhC7HTSt.js → errors-Dh7kef0i.js} +5 -6
- package/dist/{errors-BhC7HTSt.js.map → errors-Dh7kef0i.js.map} +1 -1
- package/dist/{errors-CgY633cG.cjs → errors-tfEr48bS.cjs} +2 -2
- package/dist/{errors-CgY633cG.cjs.map → errors-tfEr48bS.cjs.map} +1 -1
- package/dist/{factory-C5TujXlU.js → factory-BonqI3NL.js} +16 -20
- package/dist/{factory-C5TujXlU.js.map → factory-BonqI3NL.js.map} +1 -1
- package/dist/{factory-CNj4DH3n.cjs → factory-CJXVYp0R.cjs} +2 -2
- package/dist/{factory-CNj4DH3n.cjs.map → factory-CJXVYp0R.cjs.map} +1 -1
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
- package/dist/{fixed-window-CtaFHanJ.js → fixed-window-Dq3MLUUv.js} +2 -3
- package/dist/{fixed-window-CtaFHanJ.js.map → fixed-window-Dq3MLUUv.js.map} +1 -1
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/{global-scope-dp2jADRl.js → global-scope-D9I8s-oN.js} +2 -3
- package/dist/{global-scope-dp2jADRl.js.map → global-scope-D9I8s-oN.js.map} +1 -1
- package/dist/guards-Cidk71ME.js +7 -0
- package/dist/guards-Cidk71ME.js.map +1 -0
- package/dist/guards-nJ70syPt.cjs +2 -0
- package/dist/guards-nJ70syPt.cjs.map +1 -0
- package/dist/{identity-Da9TkuKd.cjs → identity-Cxgj6pZX.cjs} +2 -2
- package/dist/{identity-Da9TkuKd.cjs.map → identity-Cxgj6pZX.cjs.map} +1 -1
- package/dist/{identity-8vKkyAWm.js → identity-DT5VmvXy.js} +15 -16
- package/dist/{identity-8vKkyAWm.js.map → identity-DT5VmvXy.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +27 -7
- package/dist/index.js +980 -604
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-CCA1LvtO.js → indexeddb-storage-BJVtiQKm.js} +29 -30
- package/dist/{indexeddb-storage-CCA1LvtO.js.map → indexeddb-storage-BJVtiQKm.js.map} +1 -1
- package/dist/{indexeddb-storage-BTfIFRHF.cjs → indexeddb-storage-CIoW21Xd.cjs} +2 -2
- package/dist/{indexeddb-storage-BTfIFRHF.cjs.map → indexeddb-storage-CIoW21Xd.cjs.map} +1 -1
- package/dist/interactions-DTgKy_6K.js +119 -0
- package/dist/interactions-DTgKy_6K.js.map +1 -0
- package/dist/interactions-fEN6FbVo.cjs +2 -0
- package/dist/interactions-fEN6FbVo.cjs.map +1 -0
- package/dist/{journey-BUJ4WJxP.js → journey-CuJrHzEg.js} +18 -19
- package/dist/{journey-BUJ4WJxP.js.map → journey-CuJrHzEg.js.map} +1 -1
- package/dist/{journey-B_tTnvac.cjs → journey-pffMVMfa.cjs} +2 -2
- package/dist/{journey-B_tTnvac.cjs.map → journey-pffMVMfa.cjs.map} +1 -1
- package/dist/keys-BHhw_0Wh.cjs.map +1 -1
- package/dist/{keys-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
- package/dist/{keys-D5r_GH9q.js.map → keys-BU9j5YqW.js.map} +1 -1
- package/dist/library-console-C1m6g1BR.js +13 -0
- package/dist/library-console-C1m6g1BR.js.map +1 -0
- package/dist/library-console-D2GY9Or6.cjs +2 -0
- package/dist/library-console-D2GY9Or6.cjs.map +1 -0
- package/dist/{library-request-BaZOi4eg.cjs → library-request-1BX_UlaX.cjs} +2 -2
- package/dist/{library-request-BaZOi4eg.cjs.map → library-request-1BX_UlaX.cjs.map} +1 -1
- package/dist/library-request-BQBT9N9Q.js +24 -0
- package/dist/{library-request-BKOcaKtQ.js.map → library-request-BQBT9N9Q.js.map} +1 -1
- package/dist/lifecycle-2EtUaRpo.cjs +2 -0
- package/dist/lifecycle-2EtUaRpo.cjs.map +1 -0
- package/dist/lifecycle-BaKx_-32.js +55 -0
- package/dist/lifecycle-BaKx_-32.js.map +1 -0
- package/dist/log-record-CAoGBBf3.js +16 -0
- package/dist/log-record-CAoGBBf3.js.map +1 -0
- package/dist/log-record-i9zOTkpQ.cjs +2 -0
- package/dist/log-record-i9zOTkpQ.cjs.map +1 -0
- package/dist/{long-frames-CF3qiSAX.cjs → long-frames-BVg4i5SC.cjs} +2 -2
- package/dist/{long-frames-CF3qiSAX.cjs.map → long-frames-BVg4i5SC.cjs.map} +1 -1
- package/dist/{long-frames-DI5ypfAF.js → long-frames-Czk7IupC.js} +4 -5
- package/dist/{long-frames-DI5ypfAF.js.map → long-frames-Czk7IupC.js.map} +1 -1
- package/dist/models/config.d.ts +168 -4
- package/dist/models/health.d.ts +25 -0
- package/dist/models/metric.d.ts +13 -0
- package/dist/models/storage.d.ts +5 -0
- package/dist/{network-DdzXDI3J.js → network-DBNwApoF.js} +117 -70
- package/dist/network-DBNwApoF.js.map +1 -0
- package/dist/network-xbbuvG_6.cjs +2 -0
- package/dist/network-xbbuvG_6.cjs.map +1 -0
- package/dist/openfin-Bxelt0yg.js +7 -0
- package/dist/{openfin-BwEN0uj4.js.map → openfin-Bxelt0yg.js.map} +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/otlp-BDvFrLnc.cjs +2 -0
- package/dist/otlp-BDvFrLnc.cjs.map +1 -0
- package/dist/otlp-BTJdIa6F.js +81 -0
- package/dist/otlp-BTJdIa6F.js.map +1 -0
- package/dist/patch-BX8KrPCT.cjs.map +1 -1
- package/dist/{patch-CCWfuEY7.js → patch-UdPz1ea8.js} +2 -3
- package/dist/{patch-CCWfuEY7.js.map → patch-UdPz1ea8.js.map} +1 -1
- package/dist/{platform-DBSKTvFn.cjs → platform-C2Ez5kDc.cjs} +2 -2
- package/dist/{platform-DBSKTvFn.cjs.map → platform-C2Ez5kDc.cjs.map} +1 -1
- package/dist/{platform-Bw1btWCT.js → platform-DkcuXwe-.js} +5 -6
- package/dist/{platform-Bw1btWCT.js.map → platform-DkcuXwe-.js.map} +1 -1
- package/dist/remote-rules-Cfb4K-Nl.js +98 -0
- package/dist/remote-rules-Cfb4K-Nl.js.map +1 -0
- package/dist/remote-rules-vzvk7aKf.cjs +2 -0
- package/dist/remote-rules-vzvk7aKf.cjs.map +1 -0
- package/dist/reports-Dk2YhKIh.cjs +2 -0
- package/dist/reports-Dk2YhKIh.cjs.map +1 -0
- package/dist/reports-TA-zInnq.js +70 -0
- package/dist/reports-TA-zInnq.js.map +1 -0
- package/dist/resource-timing-BLv3EA2A.js +76 -0
- package/dist/resource-timing-BLv3EA2A.js.map +1 -0
- package/dist/resource-timing-Cysw1S1f.cjs +2 -0
- package/dist/resource-timing-Cysw1S1f.cjs.map +1 -0
- package/dist/sampling-C4VV-1MS.js +60 -0
- package/dist/sampling-C4VV-1MS.js.map +1 -0
- package/dist/sampling-Ckh2yW9k.cjs +2 -0
- package/dist/sampling-Ckh2yW9k.cjs.map +1 -0
- package/dist/sanitize-6ymPlVvP.js +112 -0
- package/dist/sanitize-6ymPlVvP.js.map +1 -0
- package/dist/sanitize-BAWzkZt0.cjs +2 -0
- package/dist/sanitize-BAWzkZt0.cjs.map +1 -0
- package/dist/select-ZF4by-lF.cjs +3 -0
- package/dist/select-ZF4by-lF.cjs.map +1 -0
- package/dist/select-xtQaenIi.js +270 -0
- package/dist/select-xtQaenIi.js.map +1 -0
- package/dist/{sender-DUUmSglb.js → sender-CiMHC9YG.js} +202 -509
- package/dist/sender-CiMHC9YG.js.map +1 -0
- package/dist/sender-D5wBoXA8.cjs +2 -0
- package/dist/sender-D5wBoXA8.cjs.map +1 -0
- package/dist/storage/persistence.d.ts +8 -0
- package/dist/storage-BA9RqRO-.cjs.map +1 -1
- package/dist/{storage-w7Tslvlq.js → storage-DZwed89z.js} +2 -3
- package/dist/storage-DZwed89z.js.map +1 -0
- package/dist/storm-CYi9Swpx.cjs +2 -0
- package/dist/{storm-CNZjsw4T.cjs.map → storm-CYi9Swpx.cjs.map} +1 -1
- package/dist/{storm-Daq2jGHU.js → storm-VR024_QN.js} +4 -5
- package/dist/{storm-Daq2jGHU.js.map → storm-VR024_QN.js.map} +1 -1
- package/dist/transport/headers.d.ts +8 -0
- package/dist/transport/http-transport.d.ts +2 -6
- package/dist/transport/serializers/otlp.d.ts +14 -0
- package/dist/transport/status-transport.d.ts +5 -2
- package/dist/transport/worker-client.d.ts +14 -0
- package/dist/transport/worker-entry.d.ts +5 -0
- package/dist/transport/worker-protocol.d.ts +36 -0
- package/dist/transport/worker-server.d.ts +3 -0
- package/dist/transport/worker-transport.d.ts +9 -0
- package/dist/{types-BR9t_w28.js → types-BAerHgCq.js} +2 -3
- package/dist/types-BAerHgCq.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/unclean-exit-CwcUhFOn.js +62 -0
- package/dist/unclean-exit-CwcUhFOn.js.map +1 -0
- package/dist/unclean-exit-DFUN57wY.cjs +2 -0
- package/dist/unclean-exit-DFUN57wY.cjs.map +1 -0
- package/dist/user-timing-C9kfRq3J.cjs +2 -0
- package/dist/user-timing-C9kfRq3J.cjs.map +1 -0
- package/dist/user-timing-_jZIhDKI.js +63 -0
- package/dist/user-timing-_jZIhDKI.js.map +1 -0
- package/dist/{web-socket-BacvKOvD.cjs → web-socket-BWUoqBh8.cjs} +2 -2
- package/dist/{web-socket-BacvKOvD.cjs.map → web-socket-BWUoqBh8.cjs.map} +1 -1
- package/dist/{web-socket-CpsD8WAa.js → web-socket-CV7yIMnm.js} +7 -8
- package/dist/{web-socket-CpsD8WAa.js.map → web-socket-CV7yIMnm.js.map} +1 -1
- package/dist/{web-vitals-Bflr5jSA.js → web-vitals-Bq4WFHQo.js} +2 -3
- package/dist/{web-vitals-Bflr5jSA.js.map → web-vitals-Bq4WFHQo.js.map} +1 -1
- package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -1
- package/dist/worker-protocol-Bai7GAIA.cjs +2 -0
- package/dist/worker-protocol-Bai7GAIA.cjs.map +1 -0
- package/dist/worker-protocol-CrsdSDLn.js +49 -0
- package/dist/worker-protocol-CrsdSDLn.js.map +1 -0
- package/dist/worker-server-BrIYkfoa.cjs +2 -0
- package/dist/worker-server-BrIYkfoa.cjs.map +1 -0
- package/dist/worker-server-Dp5HYm4b.js +83 -0
- package/dist/worker-server-Dp5HYm4b.js.map +1 -0
- package/dist/worker-transport-Bwej4N2e.cjs +2 -0
- package/dist/worker-transport-Bwej4N2e.cjs.map +1 -0
- package/dist/worker-transport-D6jtgpqN.js +199 -0
- package/dist/worker-transport-D6jtgpqN.js.map +1 -0
- package/package.json +31 -41
- package/dist/bus-BW6N-pY8.cjs +0 -2
- package/dist/bus-BW6N-pY8.cjs.map +0 -1
- package/dist/bus-DeOPHWaD.js.map +0 -1
- package/dist/console-Ce6heqZZ.cjs +0 -2
- package/dist/console-Ce6heqZZ.cjs.map +0 -1
- package/dist/constants-CN7GE1Lt.js +0 -246
- package/dist/constants-CN7GE1Lt.js.map +0 -1
- package/dist/constants-CW-MlHdY.cjs +0 -2
- package/dist/constants-CW-MlHdY.cjs.map +0 -1
- package/dist/interactions-BUDLxbv1.js +0 -74
- package/dist/interactions-BUDLxbv1.js.map +0 -1
- package/dist/interactions-NHbLKrqe.cjs +0 -2
- package/dist/interactions-NHbLKrqe.cjs.map +0 -1
- package/dist/library-request-BKOcaKtQ.js +0 -25
- package/dist/network-CF8UO5PK.cjs +0 -2
- package/dist/network-CF8UO5PK.cjs.map +0 -1
- package/dist/network-DdzXDI3J.js.map +0 -1
- package/dist/openfin-BwEN0uj4.js +0 -8
- package/dist/remote-rules-DIcC5vVC.js +0 -91
- package/dist/remote-rules-DIcC5vVC.js.map +0 -1
- package/dist/remote-rules-DpFmOef2.cjs +0 -2
- package/dist/remote-rules-DpFmOef2.cjs.map +0 -1
- package/dist/sampling-BVjspJWu.cjs +0 -2
- package/dist/sampling-BVjspJWu.cjs.map +0 -1
- package/dist/sampling-Cm3WhI0a.js +0 -76
- package/dist/sampling-Cm3WhI0a.js.map +0 -1
- package/dist/sanitize-C-ahCFsG.js +0 -123
- package/dist/sanitize-C-ahCFsG.js.map +0 -1
- package/dist/sanitize-DHucKGdi.cjs +0 -2
- package/dist/sanitize-DHucKGdi.cjs.map +0 -1
- package/dist/sender-D3fRCR8d.cjs +0 -3
- package/dist/sender-D3fRCR8d.cjs.map +0 -1
- package/dist/sender-DUUmSglb.js.map +0 -1
- package/dist/storage-w7Tslvlq.js.map +0 -1
- package/dist/storm-CNZjsw4T.cjs +0 -2
- package/dist/types-BR9t_w28.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards-nJ70syPt.cjs","names":["isObject","value"],"sources":["../src/utils/guards.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":"AAUA,SAAgBA,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=identity-
|
|
1
|
+
const e=require("./constants-DqKJH_MP.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.vn,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._n){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.vn,p,n);let m=a(r,`session`,`ui-observability.tab`,n)??``;return m||(m=i(n),o(r,`session`,e.An,m,n)),{sessionId:f,tabId:m,contextId:l}}function l(t,n,r){o(r,`session`,e.An,t,n)}var u=class{diagnostics;stores;touchMs;idleMs;lastTouchAt=0;constructor(n,r=t,i=e.yn,a=e._n){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.vn,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-Cxgj6pZX.cjs.map
|
|
@@ -1 +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":"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"}
|
|
1
|
+
{"version":3,"file":"identity-Cxgj6pZX.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":"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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { An as e, _n as t, vn as n, yn as r } from "./constants-zyrqveN4.js";
|
|
2
|
+
// src/utils/identity.ts
|
|
3
3
|
var i = {
|
|
4
4
|
local: () => localStorage,
|
|
5
5
|
session: () => sessionStorage
|
|
@@ -41,24 +41,24 @@ function l(e, t, n, r, i) {
|
|
|
41
41
|
e[t]().setItem(n, r);
|
|
42
42
|
});
|
|
43
43
|
}
|
|
44
|
-
function u(e, t,
|
|
45
|
-
let a = c(e, "local",
|
|
44
|
+
function u(e, t, r, i) {
|
|
45
|
+
let a = c(e, "local", n, t);
|
|
46
46
|
if (a) try {
|
|
47
47
|
let e = JSON.parse(a);
|
|
48
|
-
return e.id && (i === 0 ||
|
|
48
|
+
return e.id && (i === 0 || r - (e.lastSeenAt ?? 0) < i) ? e.id : void 0;
|
|
49
49
|
} catch {
|
|
50
50
|
t.report("storage.degraded", "The session record is not valid JSON. The library starts a new session.");
|
|
51
51
|
return;
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
function d(
|
|
55
|
-
let d = s(
|
|
54
|
+
function d(r, a = i, o = t) {
|
|
55
|
+
let d = s(r), f = Date.now(), p = s(r), m = u(a, r, f, o) ?? p, h = JSON.stringify({
|
|
56
56
|
id: m,
|
|
57
57
|
lastSeenAt: f
|
|
58
58
|
});
|
|
59
|
-
l(a, "local",
|
|
60
|
-
let g = c(a, "session", "ui-observability.tab",
|
|
61
|
-
return g || (g = s(
|
|
59
|
+
l(a, "local", n, h, r);
|
|
60
|
+
let g = c(a, "session", "ui-observability.tab", r) ?? "";
|
|
61
|
+
return g || (g = s(r), l(a, "session", e, g, r)), {
|
|
62
62
|
sessionId: m,
|
|
63
63
|
tabId: g,
|
|
64
64
|
contextId: d
|
|
@@ -73,8 +73,8 @@ var p = class {
|
|
|
73
73
|
touchMs;
|
|
74
74
|
idleMs;
|
|
75
75
|
lastTouchAt = 0;
|
|
76
|
-
constructor(e,
|
|
77
|
-
this.diagnostics = e, this.stores =
|
|
76
|
+
constructor(e, n = i, a = r, o = t) {
|
|
77
|
+
this.diagnostics = e, this.stores = n, this.touchMs = a, this.idleMs = o;
|
|
78
78
|
}
|
|
79
79
|
touch(e) {
|
|
80
80
|
let t = Date.now();
|
|
@@ -90,14 +90,13 @@ var p = class {
|
|
|
90
90
|
}
|
|
91
91
|
write(e, t) {
|
|
92
92
|
this.lastTouchAt = t;
|
|
93
|
-
let
|
|
93
|
+
let r = JSON.stringify({
|
|
94
94
|
id: e,
|
|
95
95
|
lastSeenAt: t
|
|
96
96
|
});
|
|
97
|
-
l(this.stores, "local",
|
|
97
|
+
l(this.stores, "local", n, r, this.diagnostics);
|
|
98
98
|
}
|
|
99
99
|
};
|
|
100
|
-
//#endregion
|
|
101
100
|
export { f as a, s as i, p as n, o, a as r, d as s, i as t };
|
|
102
101
|
|
|
103
|
-
//# sourceMappingURL=identity-
|
|
102
|
+
//# sourceMappingURL=identity-DT5VmvXy.js.map
|
|
@@ -1 +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":"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"}
|
|
1
|
+
{"version":3,"file":"identity-DT5VmvXy.js","names":["TAB_ID_KEY","SESSION_IDLE_MS","SESSION_ID_KEY","SESSION_TOUCH_MS","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":"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"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-DqKJH_MP.cjs"),t=require("./log-record-i9zOTkpQ.cjs"),n=require("./error-like-gGRx2s36.cjs"),r=require("./guards-nJ70syPt.cjs"),i=require("./deadline-XSnm95pg.cjs"),a=require("./platform-C2Ez5kDc.cjs"),o=require("./library-console-D2GY9Or6.cjs"),s=require("./sanitize-BAWzkZt0.cjs"),c=require("./identity-Cxgj6pZX.cjs"),l=require("./library-request-1BX_UlaX.cjs"),u=require("./batch-C8OcWR2L.cjs"),d=require("./journey-pffMVMfa.cjs"),f=require("./sampling-Ckh2yW9k.cjs");function p(t){return Math.round((performance.now()-t)*e.X)/e.X}function m(e,t,n,r,i){e.logMetric(`${t}.duration`,n,`ms`,`histogram`,{status:r,...i})}function h(e,t,n,r,i){let a=p(n);e.error(`${t} failed`,r,{"action.duration_ms":a,status:`FAILURE`,...i}),m(e,t,a,`FAILURE`,i)}function g(e,t,n,r){let i=performance.now();try{let a=n();return m(e,t,p(i),`SUCCESS`,r),a}catch(n){throw h(e,t,i,n,r),n}}async function _(e,t,n,r){let i=performance.now();try{let a=await n();return m(e,t,p(i),`SUCCESS`,r),a}catch(n){throw h(e,t,i,n,r),n}}var v=new WeakMap;function y(e){let t=e.idle;t!==void 0&&(e.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be cancelled.`,()=>{cancelIdleCallback(t)}),e.idle=void 0),clearTimeout(e.timer),e.timer=void 0}function b(t,n){typeof requestIdleCallback==`function`&&typeof cancelIdleCallback==`function`&&(n.idle=n.diagnostics.guard(`pipeline.crashed`,`The idle callback could not be scheduled.`,()=>requestIdleCallback(e=>{x(t,n,e)},{timeout:e.G})),n.idle!==void 0)||(n.timer=setTimeout(()=>{x(t,n)},0),i.r(n.timer))}function x(e,t,n){if(v.get(e)!==t||t.draining)return;y(t),t.draining=!0;let r=t.work;t.work=[];let i=0;for(;i<r.length&&(!n||n.didTimeout&&i===0||n.timeRemaining()>0);)if(t.diagnostics.guard(`pipeline.crashed`,`The library could not build a deferred record.`,r[i]),i++,v.get(e)!==t)return;t.work=[...r.slice(i),...t.work],t.draining=!1,t.work.length>0?b(e,t):v.delete(e)}function S(t,n,r,i){let a=v.get(t),o=i>0?Math.min(i,e.K):e.K;if(a&&a.work.length>=o&&!a.draining&&(x(t,a),a=v.get(t)),a){if(a.work.length>=o){r.count(`record.dropped_by_ceiling`);return}a.work.push(n)}else a={work:[n],diagnostics:r,draining:!1},v.set(t,a),b(t,a)}function C(e){let t=v.get(e);t&&x(e,t)}function w(e){let t=v.get(e);if(t){y(t),v.delete(e);for(let e of t.work)t.diagnostics.count(`record.dropped_by_ceiling`);t.work=[]}}var ee=[e.N,e.wn,e.q];function te(e,t){let r=t.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>{if(!(e instanceof Error)&&!n.r(e))return;let t=Error(e.message);return t.name=e.name,t.stack=e.stack,t});if(r)return r;let i=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(i??typeof e)}function ne(e,t,n){return n.guard(`record.sanitize_failed`,`The library could not read the error reason.`,()=>e instanceof Error?e:t)??t}function re(e,t){if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return e;if(typeof e==`object`&&e)return t.guard(`record.sanitize_failed`,`The library could not read the properties of the error reason.`,()=>{let t=e,r=n.r(e),i={},a=0;for(let e of Object.keys(t)){let o=t[e];r&&n.t.has(e)||!n.n(o)||(i[e]=o,a++)}return a===0?void 0:i})}function ie(e){if(!r.t(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function ae(e){return ee.some(t=>e===t||e.startsWith(`${t}.`))?`system`:`log`}function T(e,t){return e===void 0?{}:t.guard(`record.sanitize_failed`,`The library could not read the payload.`,()=>({...e}))??{"uiobs.sanitize_failed":!0}}var E=class n{bind;namespace;options;levelType;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n,this.levelType=ae(t)}child(e,t={}){return new n(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...t.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.W,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=this.bind();this.submit(o,`INFO`,`metric`,s=>{let c=T(a,o.diagnostics),l={...c,"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,[e.Nt.attributeKeys]:Object.keys(c)};this.writeNow(o,`INFO`,`metric`,t,l,!0,s)})};timeSync=(e,t,n)=>g(this,e,t,n);timeAsync=(e,t,n)=>_(this,e,t,n);write(e,t,n,r){let i=this.bind();this.submit(i,e,t,a=>{this.writeNow(i,e,t,n,r,!1,a)})}submit(e,n,r,i){if(!e.isDestroyed()){if(e.isRotating())e.diagnostics.count(`record.dropped_during_rotation`);else if(e.config.payloadMode===`defer`&&e.config.enabled&&!e.config.debugBuffer.enabled&&this.namespace!==`uiobs.diagnostics`){if(!e.builder.isEnabled(n,this.namespace,r)&&!this.mirrors(e,n))return;let o=e.journey.current(),s={timeUnixNano:t.r(),trace:e.tracing.resolve(),journey:o?{...o}:null,context:e.context.getAll(),url:a.t(e.diagnostics)};S(e,()=>{i(s)},e.diagnostics,e.config.buffering.maxPendingRecords)}else i()}}writeNow(e,t,n,r,i,a,o){if(!(e.config.enabled&&e.config.debugBuffer.enabled)&&!e.builder.isEnabled(t,this.namespace,n)){this.mirrors(e,t)&&this.print(e,t,r,i,void 0,null,void 0,o);return}let s={snapshot:o,level:t,type:n,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:a?i:T(i,e.diagnostics)},{record:c,dropped:l}=e.builder.build(s),u=!!e.config.redact||e.config.processors.length>0,d=n!==`metric`&&e.config.capturePolicy.breadcrumbs>0,f=l===`sampling`&&u&&d?e.builder.build(s,!0):void 0,p=c??f?.record??null,m=p?p.body:l===`sampling`&&!u?r:void 0;d&&m!==void 0&&e.breadcrumbs.push({t:o?Number(o.timeUnixNano.slice(0,-6)):Date.now(),category:n===`action`?`action`:n===`event`?`event`:`log`,message:m}),this.print(e,t,r,i,void 0,p,f?.dropped??l,o),e.emit(c)}writeError(e,t,n,r){let i=this.bind();this.submit(i,e,this.levelType,a=>{this.writeErrorNow(i,e,t,n,r,a)})}writeErrorNow(t,n,r,i,a,o){let s=t.builder.isEnabled(n,this.namespace);if(!s&&!this.mirrors(t,n))return;let c=a===void 0&&(t.diagnostics.guard(`record.sanitize_failed`,`The library could not read the error slot.`,()=>ie(i))??!1),l=c?i:a,u=c?void 0:i,d=u===void 0?void 0:te(u,t.diagnostics),f=d===void 0?void 0:ne(u,d,t.diagnostics);if(!s){this.print(t,n,r,l,f,null,void 0,o);return}let p=d?re(u,t.diagnostics):void 0,{record:m,dropped:h}=t.builder.build({snapshot:o,level:n,type:this.levelType,body:r,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(l,t.diagnostics),...d?{"error.type":d.name,"error.message":d.message,"error.stack_trace":d.stack}:{},...p===void 0?{}:{[e.d]:p},[e.c]:t.breadcrumbs.snapshot()}});this.print(t,n,r,l,f,m,h,o),t.emit(m)}print(e,t,n,r,i,a,o,s){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 c=e.builder.build({snapshot:s,level:t,type:this.levelType,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...T(r,e.diagnostics),...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{}}},!0).record;c&&e.console.write(this.namespace,t,c.body,c.attributes)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},oe=`overflow`,se=new Set([e.g,e.h,e.a,e.v,e.f,e.p,e.m]);function ce(e={}){let t={};for(let n of Object.keys(e).sort()){if(n.startsWith(`metric.`)||se.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 le(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 ue(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 de(t,n,r){let i={"metric.name":t.name,"metric.unit":t.unit,"metric.type":t.kind,[e.Nt.start]:r,[e.Nt.attributeKeys]:Object.keys(n.attributes)};return t.kind===`counter`?(i[`metric.value`]=n.sum,i):{...i,[e.Nt.count]:n.count,[e.Nt.sum]:n.sum,[e.Nt.min]:n.min,[e.Nt.max]:n.max,[e.Nt.bounds]:t.boundaries,[e.Nt.buckets]:n.buckets}}function fe(e,t,n){let r={name:e,kind:`counter`,unit:t.unit??`count`,boundaries:[]};return{add:(e,t)=>{n(r,e,t)}}}function pe(t,n,r){let i={name:t,kind:`histogram`,unit:n.unit??`count`,boundaries:n.boundaries??e.Mt};return{record:(e,t)=>{r(i,e,t)}}}var me=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,ce(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,de(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=le(t.boundaries,this.policy.maxHistogramBoundaries),i=ue(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.Mt]},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=oe,a=t.series.get(i),o={[e._]:!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()),i.r(this.timer))}},he={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},ge=class{settings;diagnostics;limits;constructor(t,n,r=e.Kt){this.settings=t,this.diagnostics=n,this.limits=r}update(e){this.settings=e}accepts(t){return this.settings.level===null||!Object.hasOwn(e.wt,this.settings.level)?!1:e.wt[t]>=e.wt[this.settings.level]}write(e,t,n,r,i){if(!this.accepts(t)||typeof console>`u`||o.t())return;let a=`%c[%s]%c[${t}]%c`,{styles:c}=this.settings,l=he[t];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${l}.`,()=>{let u=[];i!==void 0&&u.push(i),r!==void 0&&u.push(s.n(r,this.limits,this.diagnostics)),o.n(()=>{console[l](a,c.namespace,e,c[t],``,n,...u)})})}},_e=class{value=0;next(){return++this.value}},ve=/^[0-9a-f]{32}$/,ye=/^[0-9a-f]{16}$/,be=/[1-9a-f]/;function xe(e){return ve.test(e.traceId)&&be.test(e.traceId)&&ye.test(e.spanId)&&be.test(e.spanId)}function Se(){return c.o(16)}function D(){return c.o(8)}function Ce(e){return{traceId:Se(),spanId:D(),traceFlags:1,startedAt:Date.now(),reason:e,ended:!1}}function we(e,t,n){return`00-${e}-${t}-${(n&255).toString(16).padStart(2,`0`)}`}function Te(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var Ee=class{diagnostics;maxAgeMs;load;spans;ambient=Ce(`start`);otel;constructor(t,n=e.Fn,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`),Te(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(xe(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){let t=this.ambient;this.ambient=Ce(e);let n=Te(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.Pn]=we(a.traceId,a.spanId,a.traceFlags),{headers:n};let s=o.keeps(a.traceId),c=s?a.traceFlags:a.traceFlags&-2,l=t?D():a.spanId;return n[e.Pn]=we(a.traceId,l,c),!t||!s?{headers:n}:{headers:n,span:{traceId:a.traceId,spanId:l,parentSpanId:a.spanId}}}},De=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)}},Oe=Object.keys(e.wt),ke=[`gzip`,`none`],Ae=[`omit`,`same-origin`,`include`],je=[`auto`,`indexeddb`,`localstorage`,`memory`,`none`],Me=[`storage`,`memory`],Ne=[`auto`,`sender`,`forwarder`,`off`],Pe=[`auto`,`provider`,`client`],Fe=[`auto`,`context`,`tab`,`origin`],Ie=[`error`,`warn`,`info`,`log`],Le=[`limited`,`until-delivered`],Re={logFlushIntervalMs:[100,6e4],logBatchSize:[1,1e3],metricFlushIntervalMs:[100,6e4],metricBatchSize:[1,1e3]},ze={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.D]},Ve=[6e4,864e5],O=[0,2147483647],k=[0,2**53-1],He=[1,2**53-1],Ue=[100,1e4],We={capturePolicy:{ranges:{breadcrumbs:[0,1e6],errorDedupeMs:O,maxErrorSignatures:k,errorsPerWindow:k,consolePerWindow:k,longFramesPerWindow:k,webSocketPerWindow:k,reportsPerWindow:k,resourcesPerWindow:k,lifecyclePerWindow:k,windowMs:O,errorCeiling:k}},metadata:{ranges:{}},persistence:{ranges:{}},diagnostics:{ranges:{throttleMs:O},custom:{records:ot}},correlation:{ranges:{sessionIdleMs:O,sessionTouchMs:O,traceMaxAgeMs:O}},metrics:{ranges:{maxSeries:k,maxInstruments:k,maxHistogramBoundaries:k}},buffering:{ranges:{maxPendingRecords:k,maxPendingBytes:k},choices:{overflow:[`drop-oldest`,`drop-newest`,`persist`]}},delivery:{ranges:{requestTimeoutMs:[1,O[1]],maxConcurrentRequests:He,retryBaseDelayMs:O,retryMaxDelayMs:O,retryIdleDelayMs:O,batchesPerDrain:He},choices:{priority:[`low`,`auto`,`high`]}},debugBuffer:{ranges:{maxRecords:[1,1e4],maxAgeMs:O}}},Ge=[`errors`,`rejections`,`resourceErrors`,`fetch`,`xhr`,`httpMetrics`,`navigation`,`webVitals`,`longFrames`,`fullUrls`,`webSocket`,`uncleanExit`,`userTiming`,`serverTiming`,`reports`,`lifecycle`],Ke=`null`,A=`a level name: ${j(Oe)}`,qe=`true, false or a list of ${j(Ie)}`,Je=`a list of strings and RegExp patterns`,Ye=`a list of origin URLs such as "https://api.example" and RegExp patterns`,Xe=`a list of origin URLs such as "https://app.example". For a sandboxed frame, set bus.mode: "sender" in the frame`,Ze=`a list of strings`,Qe=`true, false or a list of diagnostic codes`;function j(e){let t=e.map(e=>`"${e}"`);return`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}function $e(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 ${$e(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,j(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 et(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 tt(e,t,n){return e===void 0?t:e===null?null:typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:(M(n,`loggerCache.maxEntries`,`a nonnegative safe integer or null`,e,String(t)),t)}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 Oe.find(e=>e===t)}function nt(e,t,n,r){if(t===void 0)return n;let i=L(t);return i===void 0?(M(r,e,A,t,`"${n}"`),n):i}function rt(e,t,n){if(e===void 0)return t;if(!r.t(e))return M(n,`minLevels`,`an object of level names`,e,`the value in force`),t;let i=[];for(let[t,r]of Object.entries(e)){let e=L(r);t!==``&&e!==void 0?i.push([t,e]):M(n,`minLevels["${t}"]`,A,r,`minLevel for it`)}return Object.fromEntries(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 ${$e(t)}. ${e} must be ${r}.`):o.push(n)}return o}function it(e){return typeof e==`function`?e:void 0}function at(e){return r.t(e)&&typeof e.name==`string`&&e.name!==``&&typeof e.install==`function`&&typeof e.uninstall==`function`?e:void 0}function ot(e,t,n,r){return t===void 0||typeof t==`boolean`?t??n:Array.isArray(t)?R(e,t,[],Qe,st,r):(M(r,e,Qe,t,`the value in force`),n)}function st(e){return typeof e==`string`?e:void 0}function ct(e){return typeof e==`string`||e instanceof RegExp?e:void 0}function lt(e){return Ie.find(t=>t===e)}function ut(e){if(typeof e==`string`)try{let{origin:t}=new URL(e);return t===Ke?void 0:t}catch{return}}function dt(e){return e instanceof RegExp?e:ut(e)}function ft(e){return r.t(e)?Object.values(e).every(e=>typeof e==`string`):!1}function pt(e,t,n){if(e!==void 0)return typeof e==`function`||ft(e)?e:(n.report(`config.invalid`,`headers must be an object of strings or a function. The library keeps the headers in force.`),t)}function mt(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function ht(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||mt(t)?t:(r.report(`config.invalid`,`serializer must be "${e.mn}", "ecs" or an implementation. The library uses "${e.mn}".`),e.mn)}var gt=new Set(Object.keys(e.L));function _t(e,t){let n={},r=Object.entries(e??{});for(let[e,i]of r)gt.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 vt(e,t,n){if(e===void 0)return t??`DEBUG`;let r=L(e);return r===void 0?(M(n,`console.level`,A,e,`the console level in force`),t):r}function yt(t,n,r){if(t===void 0)return n;if(t===!1)return{level:null,styles:n.styles};if(t===!0)return{level:e.I,styles:n.styles};if(typeof t==`string`){let e=L(t);return e===void 0?(M(r,`console`,A,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:vt(t.level,n.level,r),styles:{...n.styles,..._t(t.styles,r)}}}function bt(e,t,n){let r=e??{};return{...t,...r,rates:{...t.rates,...r.rates},alwaysSampleTypes:R(`sampling.alwaysSampleTypes`,r.alwaysSampleTypes,t.alwaysSampleTypes,Ze,st,n),alwaysSampleFrom:nt(`sampling.alwaysSampleFrom`,r.alwaysSampleFrom,t.alwaysSampleFrom,n),remote:P(`sampling.remote`,r.remote,t.remote,n)}}function xt(e,t,n){let r=e??{};return{maxTrackedSources:F(`bus.maxTrackedSources`,r.maxTrackedSources,[0,2**53-1],t.maxTrackedSources,n),sourcePolicy:N(`bus.sourcePolicy`,r.sourcePolicy,[`registered`,`trusted-origin`],t.sourcePolicy,n),validation:N(`bus.validation`,r.validation,[`strict`,`envelope`],t.validation,n),maxMessageBytes:F(`bus.maxMessageBytes`,r.maxMessageBytes,[0,2**53-1],t.maxMessageBytes,n),maxRecordsPerMessage:F(`bus.maxRecordsPerMessage`,r.maxRecordsPerMessage,[0,2**53-1],t.maxRecordsPerMessage,n),maxMessagesPerSecond:F(`bus.maxMessagesPerSecond`,r.maxMessagesPerSecond,[0,2**53-1],t.maxMessagesPerSecond,n),mode:N(`bus.mode`,r.mode,Ne,t.mode,n),trustedOrigins:R(`bus.trustedOrigins`,r.trustedOrigins,t.trustedOrigins,Xe,ut,n),openFinRole:N(`bus.openFinRole`,r.openFinRole,Pe,t.openFinRole,n)}}function St(e,t,n){let r=e??{};return{scope:N(`journey.scope`,r.scope,Fe,t.scope,n),maxAgeMs:F(`journey.maxAgeMs`,r.maxAgeMs,Ve,t.maxAgeMs,n)}}function Ct(e,t,n){let r=e??{};return{mode:N(`retention.mode`,r.mode,Le,t.mode,n),...I(`retention`,r,t,ze,n)}}function wt(e,t,n){return e===void 0?t:typeof e==`boolean`?e:Array.isArray(e)?R(`capture.console`,e,[],qe,lt,n):(M(n,`capture.console`,qe,e,`the value in force`),t)}function Tt(t,n,r){let i=t??{},a={...n,...i,remoteToggles:R(`capture.remoteToggles`,i.remoteToggles,n.remoteToggles,`a list of capture switch names without privacy controls`,t=>e.qt.find(e=>e===t),r),resourceTiming:Et(i.resourceTiming,n.resourceTiming,r),interactions:Dt(i.interactions,n.interactions,r),console:wt(i.console,n.console,r),longFrameThresholdMs:et(`capture.longFrameThresholdMs`,i.longFrameThresholdMs,n.longFrameThresholdMs,r),ignoreUrls:R(`capture.ignoreUrls`,i.ignoreUrls,n.ignoreUrls,Je,ct,r),userTimingInclude:R(`capture.userTimingInclude`,i.userTimingInclude,n.userTimingInclude,Je,ct,r),propagateTraceHeaderTo:R(`capture.propagateTraceHeaderTo`,i.propagateTraceHeaderTo,n.propagateTraceHeaderTo,Ye,dt,r),plugins:R(`capture.plugins`,i.plugins,n.plugins,`a list of objects with a name, install() and uninstall()`,at,r)};for(let e of Ge)a[e]=P(`capture.${e}`,i[e],n[e],r);return a}function Et(t,n,i){return t===void 0?n:typeof t==`boolean`?t:r.t(t)?{slowMs:et(`capture.resourceTiming.slowMs`,t.slowMs,typeof n==`object`?n.slowMs??1e3:e.on,i)}:(i.report(`config.invalid`,`capture.resourceTiming must be a boolean or an options object.`),n)}function Dt(e,t,n){if(e===void 0)return t;if(typeof e==`boolean`)return e;if(!r.t(e))return n.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{n.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:M(n,`capture.interactions.actionAttribute`,`an attribute name of letters, digits, hyphens and underscores`,e.actionAttribute,`"${s}"`)),{actionAttribute:s,text:P(`capture.interactions.text`,e.text,i.text??!1,n),selector:P(`capture.interactions.selector`,e.selector,i.selector??!1,n),ignoreSelector:typeof o==`string`||o===null?o:void 0,maxTextChars:F(`capture.interactions.maxTextChars`,e.maxTextChars,[0,2**53-1],i.maxTextChars??50,n),rageClicks:P(`capture.interactions.rageClicks`,e.rageClicks,i.rageClicks??!1,n),rageClickCount:F(`capture.interactions.rageClickCount`,e.rageClickCount,[2,20],i.rageClickCount??3,n),rageClickWindowMs:F(`capture.interactions.rageClickWindowMs`,e.rageClickWindowMs,Ue,i.rageClickWindowMs??1e3,n),deadClicks:P(`capture.interactions.deadClicks`,e.deadClicks,i.deadClicks??!1,n),deadClickMs:F(`capture.interactions.deadClickMs`,e.deadClickMs,Ue,i.deadClickMs??1e3,n)}}var Ot={metricsEndpoint:`The library sends metric records as log records.`,tracesEndpoint:`The library sends no span.`};function kt(t,n,r,i,o){let s=r;if(typeof n==`string`&&n!==``)try{new URL(n),s=n}catch(e){o.report(`config.invalid`,`${t} is not a valid absolute URL: ${a.i(n,!1)}. The library keeps the value in force.`,void 0,e)}else n===``?s=``:n!==void 0&&M(o,t,`a URL string`,n,`the value in force`);return s!==``&&i!==`otlp`?(o.report(`config.invalid`,`${t} needs serializer "${e.mn}". ${Ot[t]}`),``):s}function At(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=r.custom?.[o],f=c;d?f=d(`${e}.${o}`,s,c,i):typeof c==`number`&&l?f=F(`${e}.${o}`,s,l,c,i):typeof c==`boolean`?f=P(`${e}.${o}`,s,c,i):u?f=N(`${e}.${o}`,s,u,String(c),i):s===void 0||typeof s==`string`?f=s??c:M(i,`${e}.${o}`,`a string`,s,String(c)),Object.assign(a,{[o]:f})}return a}function z(t,n,r){let i=r??e.U,o=Object.fromEntries(Object.keys(We).map(e=>[e,At(e,t[e],i[e],We[e],n)])),s={...i,...t,...o,lockConfiguration:P(`lockConfiguration`,t.lockConfiguration,i.lockConfiguration,n),loggerCache:{maxEntries:tt(t.loggerCache?.maxEntries,i.loggerCache.maxEntries,n)},securityContext:{id:typeof t.securityContext?.id==`string`&&t.securityContext.id||i.securityContext.id,isolation:P(`securityContext.isolation`,t.securityContext?.isolation,i.securityContext.isolation,n)},endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,enabled:P(`enabled`,t.enabled,i.enabled,n),payloadMode:N(`payloadMode`,t.payloadMode,[`copy`,`defer`],i.payloadMode,n),minLevel:nt(`minLevel`,t.minLevel,i.minLevel,n),minLevels:rt(t.minLevels,i.minLevels,n),processors:R(`processors`,t.processors,i.processors,`a list of functions`,it,n),compression:N(`compression`,t.compression,ke,i.compression,n),credentials:N(`credentials`,t.credentials,Ae,i.credentials,n),headers:`headers`in t?pt(t.headers,i.headers,n):i.headers,storage:N(`storage`,t.storage,je,i.storage,n),identity:N(`identity`,t.identity,Me,i.identity,n),serializer:ht(t.serializer,r?.serializer,n),console:yt(t.console,i.console,n),sampling:bt(t.sampling,i.sampling,n),bus:xt(t.bus,i.bus,n),batching:I(`batching`,t.batching,i.batching,Re,n),retention:Ct(t.retention,i.retention,n),limits:I(`limits`,t.limits,i.limits,Be,n),journey:St(t.journey,i.journey,n),capture:Tt(t.capture,i.capture,n)};for(let e of[`metricsEndpoint`,`tracesEndpoint`])s[e]=kt(e,t[e],i[e],s.serializer,n);if(s.transport!==void 0&&typeof s.transport!=`function`&&(n.report(`config.invalid`,`transport must be a function. The library ignores the value.`),s.transport=i.transport),s.onDrop!==void 0&&typeof s.onDrop!=`function`&&(n.report(`config.invalid`,`onDrop must be a function. The library ignores the value.`),s.onDrop=i.onDrop),s.contextProvider!==void 0&&typeof s.contextProvider!=`function`&&(n.report(`config.invalid`,`contextProvider must be a function. The library ignores the value.`),s.contextProvider=i.contextProvider),s.transportWorker!==void 0&&typeof s.transportWorker!=`function`&&(n.report(`config.invalid`,`transportWorker must be a function. The library keeps the value in force.`),s.transportWorker=i.transportWorker),s.transportOnExit!==void 0&&typeof s.transportOnExit!=`function`&&(n.report(`config.invalid`,`transportOnExit must be a function. The library ignores the value.`),s.transportOnExit=i.transportOnExit),s.endpoint===``)s.transport===void 0&&n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(s.endpoint!==null)try{new URL(s.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.i(s.endpoint,!1)}.`,void 0,e)}for(let e of[`metricsEndpoint`,`tracesEndpoint`])s[e]!==``&&s.endpoint===null&&!s.transport&&n.report(`config.invalid`,`${e} needs endpoint or transport. The library sends nothing to ${e}.`);s.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.Wn}'.`),e.Wn);let c=s.sampling.defaultRate;(typeof c!=`number`||c<0||c>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(c)}. The library uses 1.`),s.sampling.defaultRate=1);let l=s.sampling.remoteMaxRate;typeof l==`number`&&l>=0&&l<=1||(n.report(`config.invalid`,`sampling.remoteMaxRate must be 0..1. The value is ${String(l)}. The library uses 1.`),s.sampling.remoteMaxRate=1);let u=Object.entries(s.sampling.rates);for(let[e,t]of u)(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.`),s.sampling.rates[e]=1);s.capture.ignoreUrls=s.capture.ignoreUrls.filter(e=>e!==r?.endpoint&&e!==r?.metricsEndpoint&&e!==r?.tracesEndpoint);for(let e of[s.endpoint,s.metricsEndpoint,s.tracesEndpoint])e&&!s.capture.ignoreUrls.includes(e)&&(s.capture.ignoreUrls=[...s.capture.ignoreUrls,e]);return s.delivery.retryMaxDelayMs<s.delivery.retryBaseDelayMs&&(n.report(`config.invalid`,`delivery.retryMaxDelayMs must be at least retryBaseDelayMs.`),s.delivery.retryBaseDelayMs=i.delivery.retryBaseDelayMs,s.delivery.retryMaxDelayMs=i.delivery.retryMaxDelayMs),s.capture.urlTransform!==void 0&&typeof s.capture.urlTransform!=`function`&&(n.report(`config.invalid`,`capture.urlTransform must be a function.`),s.capture.urlTransform=i.capture.urlTransform),jt(t,n),s}function jt(t,n){let r=new Set([...Object.keys(e.U),...e.Hn]);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.F){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.U[r]),...e.Un[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 Mt(t,n){for(let r of Object.keys(n))e.F.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.F)Object.assign(t[r],n[r])}var Nt=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)}},Pt=class{policy;kept=[];constructor(e){this.policy=e}push(e){let{enabled:t,maxRecords:n}=this.policy();t&&(this.kept.push({at:Date.now(),record:e}),this.kept.length>=n*2&&(this.kept=this.kept.slice(-n)))}drain(){let t=this.live();return this.kept=[],t.map(({record:t})=>({...t,attributes:{...t.attributes,[e.u]:!0}}))}snapshot(){return this.live().map(({record:e})=>e)}live(){let{enabled:e,maxRecords:t,maxAgeMs:n}=this.policy();if(!e)return this.kept=[],[];let r=n===0?-1/0:Date.now()-n;return this.kept.slice(-t).filter(e=>e.at>=r)}clear(){this.kept=[]}},B=class{handler;throttleMs;consoleFallback;counters=new Map;lastEmitted=new Map;constructor(t,n=e.J,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,i){let a=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:i,at:s,count:a},{handler:l}=this;if(l)try{o.n(()=>{l(c)})}catch{this.count(`handler.threw`),this.consoleFallback&&typeof console<`u`&&o.n(()=>{console.warn(`${e.Et} 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 Ft=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=u.t(t,e.f);typeof n==`string`&&V(i.journeyIds,n);let r=u.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.`,()=>{l.r(()=>{o.n(()=>{t(n)})})});this.reporting=!1}}},It=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=u.r(e);if((t?this.actions:this.held.length-this.actions)<(t?2e3:500))this.actions+=+!!t;else{let e=this.held.findIndex(e=>u.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}},Lt={name:`ui.measure.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Mt},Rt={name:`ui.measure.phase.duration`,kind:`histogram`,unit:`ms`,boundaries:e.Mt};function zt(e,t,n,r){let i=String(e),a=Date.now(),o=performance.now(),s,c=!1,l=e=>a+e-o,u=(e,a)=>{s&&=(r.metric(Rt,e-s.at,{...t,"measure.name":i,"measure.phase":s.name}),n&&r.span({name:s.name,kind:`internal`,traceId:n.traceId,spanId:D(),parentSpanId:n.spanId,startMs:l(s.at),endMs:l(e),error:a,attributes:{"measure.name":i}}),void 0)};return{phase:e=>{if(c)return;let t=performance.now();u(t,!1),s={name:String(e),at:t}},end:(e=`ok`)=>{if(c)return;c=!0;let s=performance.now(),d=e===`error`;u(s,d);let f={...t,"measure.outcome":e};r.metric(Lt,s-o,{...f,"measure.name":i}),n&&r.span({...n,name:i,kind:`internal`,startMs:a,endMs:l(s),error:d,attributes:f})}}}var Bt=`error.`,Vt=[e.v,e.f,e.p],Ht={processor:{label:`A processor`,code:`record.dropped_by_processor`},redact:{label:`The redact hook`,code:`record.dropped_by_redact`}},Ut=[`metric.name`,`metric.unit`,`metric.type`,`metric.value`,...Object.values(e.Nt),...Object.values(e.xn)];function Wt(e){return Object.fromEntries(Ut.filter(t=>t in e).map(t=>[t,e[t]]))}function H(e){return e}var Gt=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t,n,r){let{config:i}=this.deps;if(!i.enabled)return!1;if(r!==void 0&&e.Ct.includes(r))return!0;let a=this.deps.remote.sampling?.minLevelFor(n)??f.n(n,i);return e.wt[t]>=e.wt[a]}keepForDebug(e){let{config:t,debug:n}=this.deps;if(!n||!t.enabled||!t.debugBuffer.enabled)return;let{record:r}=this.build(e,!0);r&&n.push(r)}build(n,r=!1){let{config:i,diagnostics:o,tracing:c,journey:l,sequence:u,limits:d,remote:p}=this.deps;if(!r&&!this.isEnabled(n.level,n.namespace,n.type))return o.count(`record.dropped_by_level`),this.keepForDebug(n),{record:null,dropped:`level`};let m=n.trace??n.snapshot?.trace??c.resolve(),h=n.snapshot?n.snapshot.journey:l.current(),g=f.o({level:n.level,type:n.type,namespace:n.namespace,journeyId:h?.id??``,traceId:m.traceId,aggregated:n.aggregated},i,p.sampling?.current()??null);if(!r&&!g)return o.count(`record.dropped_by_sampling`),this.keepForDebug(n),{record:null,dropped:`sampling`};let _=u.next(),v=n.snapshot?.url??a.t(o),y=i.metadata.pageUrl?a.i(v,i.capture.fullUrls,i.capture.urlTransform,o):``,b,x=0;try{let e=s.r(n.snapshot?.context??this.deps.context.getAll(),d,o),t=s.r(this.provided(),d,o),r=s.r(n.scoped??{},d,o),i=s.r(n.payload??{},d,o);x=e.bytes+t.bytes+r.bytes+i.bytes,b={...H(e.value),...H(t.value),...H(r.value),...H(i.value)}}catch(t){o.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),b={[e.y]:!0}}Object.assign(b,n.fixed),b[e.g]=n.type,b[e.h]=_,b[e.a]=n.namespace,b[e.v]=y,h&&(b[e.f]=h.id,b[e.p]=h.name,h.parentId!==void 0&&(b[e.m]=h.parentId));let S=s.i(n.body,d.maxBodyChars);S!==n.body&&o.count(`record.truncated`);let C={timeUnixNano:n.snapshot?.timeUnixNano??t.r(),traceId:m.traceId,spanId:m.spanId,traceFlags:m.traceFlags,severityNumber:e.bn[n.level],severityText:n.level,body:S,attributes:b,resource:this.resource()},w=i.processors.map(e=>[e,`processor`]);if(i.redact&&w.push([i.redact,`redact`]),w.length>0){let e=this.applyHooks(C,w,n.fixed);if(typeof e==`string`)return{record:null,dropped:e};({record:C,bytes:x}=e)}if(x>d.maxRecordBytes){o.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped the caller attributes.`,{bytes:x,body:C.body});let t={[e.g]:n.type,[e.h]:_,[e.a]:n.namespace,[e.s]:!0,[e.o]:x};for(let e of Vt)e in C.attributes&&(t[e]=C.attributes[e]);for(let[e,n]of Object.entries(C.attributes))e.startsWith(Bt)&&(t[e]=n);let r=s.r(t,d,o).bytes;r>d.maxRecordBytes&&`error.data`in t&&(Reflect.deleteProperty(t,e.d),r=s.r(t,d,o).bytes);let i=C.attributes[e.c];if(i!==void 0){let n=s.r(i,d,o).bytes;r+n<=d.maxRecordBytes&&(t[e.c]=i)}Object.assign(t,n.fixed),C.attributes=t}return{record:C}}redactForwarded(e){let{redact:t}=this.deps.config;if(!t)return e;let n=[[t,`redact`]],r=this.applyHooks(e,n,Wt(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:i,limits:a}=this.deps,o=s.r(r.attributes,a,i),c=H(o.value);return Object.assign(c,n),{record:{...r,attributes:c},bytes:o.bytes}}runHook(n,r,i){let{diagnostics:a}=this.deps,{label:o,code:s}=Ht[r],c;try{c=n(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 t.n(l)?t.t(l.severityText)?{...l,severityNumber:e.bn[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,n=t.guard(`handler.threw`,`The contextProvider threw an error. The record has no attributes from it.`,()=>{let t=e();return t===void 0?{}:r.t(t)&&typeof t.then!=`function`?t:null});return n===null&&t.report(`config.invalid`,`contextProvider must return an object of attributes. The library ignores the value.`),n??{}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.rn]:t.serviceName,[e.in]:t.serviceVersion,[e.$t]:t.environment,[e.ln]:e.Mn,[e.un]:e.Nn,[e.cn]:e.jn,[e.en]:r.platform,[e.an]:n.sessionId,[e.sn]:n.tabId,[e.Qt]:n.contextId,...t.metadata.userAgent?{[e.Zt]:r.userAgent}:{},...!t.metadata.openfin||r.openfinUuid===void 0?{}:{[e.nn]:r.openfinUuid},...!t.metadata.openfin||r.openfinName===void 0?{}:{[e.tn]:r.openfinName}},this.resourceCache}},Kt=1e3,qt={start:`ui.start`,interaction:`ui.interaction`,navigation:`ui.navigation`,explicit:`ui.trace`,maxAge:`ui.trace`};function Jt(e){return`${String(Math.round(e*Kt))}000`}function Yt(e){return{name:qt[e.reason],kind:`internal`,traceId:e.traceId,spanId:e.spanId,parentSpanId:``,startMs:e.startedAt,endMs:e.endedAt,error:!1,attributes:{}}}function Xt(t){return{[e.xn.kind]:t.kind,[e.xn.parentId]:t.parentSpanId,[e.xn.start]:Jt(t.startMs),[e.xn.end]:Jt(t.endMs),[e.xn.status]:t.error?`error`:`unset`,...t.link?{[e.xn.linkTraceId]:t.link.traceId,[e.xn.linkSpanId]:t.link.spanId}:{}}}var Zt={errors:async()=>(await Promise.resolve().then(()=>require("./errors-tfEr48bS.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-xbbuvG_6.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-fEN6FbVo.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-DFuoTQbZ.cjs"))).WebVitalsCapture,longFrames:async()=>(await Promise.resolve().then(()=>require("./long-frames-BVg4i5SC.cjs"))).LongFrameCapture,console:async()=>(await Promise.resolve().then(()=>require("./console-BPZCuSLc.cjs"))).ConsoleCapture,uncleanExit:async()=>(await Promise.resolve().then(()=>require("./unclean-exit-DFUN57wY.cjs"))).UncleanExitCapture,userTiming:async()=>(await Promise.resolve().then(()=>require("./user-timing-C9kfRq3J.cjs"))).UserTimingCapture,reports:async()=>(await Promise.resolve().then(()=>require("./reports-Dk2YhKIh.cjs"))).ReportCapture,resourceTiming:async()=>(await Promise.resolve().then(()=>require("./resource-timing-Cysw1S1f.cjs"))).ResourceTimingCapture,lifecycle:async()=>(await Promise.resolve().then(()=>require("./lifecycle-2EtUaRpo.cjs"))).LifecycleCapture},Qt=new WeakMap,$t=0;function en(e){let t=Qt.get(e);return t===void 0&&(t=++$t,Qt.set(e,t)),t}var U=Symbol.for(e.dn),W=Symbol.for(e.fn),tn=[`batching`,`retention`],G={endpoint:null,metricsEndpoint:``,tracesEndpoint:``,headers:void 0,credentials:`omit`,transport:void 0,transportOnExit:void 0,transportWorker:void 0},nn=Object.keys(G),rn=new Set([`bus.role_resolved`,`config.reconfigured`,`security.rotated`,`journey.adopted`,`journey.expired`]);function an(e){return JSON.stringify({...e,urlTransform:e.urlTransform?en(e.urlTransform):void 0,webVitalsLoader:e.webVitalsLoader!==void 0,ignoreUrls:e.ignoreUrls.map(String),propagateTraceHeaderTo:e.propagateTraceHeaderTo.map(String),userTimingInclude:e.userTimingInclude.map(String),plugins:e.plugins.map(en)})}function on(e){if(!r.t(e))return e;let t={...e};for(let e of[`url`,`endpoint`]){let n=t[e];typeof n==`string`&&(t[e]=a.i(n,!1))}return t}function sn(e){return{...e,endpoint:null,metricsEndpoint:``,tracesEndpoint:``,transport:void 0,transportOnExit:void 0,transportWorker:void 0,bus:{...e.bus,mode:`off`}}}function cn(e){return!!e.endpoint||!!e.metricsEndpoint||!!e.tracesEndpoint||e.transport!==void 0||e.transportWorker!==void 0}function K(t){return t.sdkVersion===e.Nn}var q=class n{rotating=!1;closingContext=!1;mismatchVersion=null;contextMismatch=!1;rotation;memoryStorage;storagePersistence=`off`;recordingDiagnostic=!1;diagnosticLogger=new E(()=>this,e.q);debugBuffer=new Pt(()=>this.config.debugBuffer);explicitSecurityContext;ownerAdopted=!1;isRotating(){return this.rotating}setConfigurationLocked(e){typeof e==`boolean`&&(this.config.lockConfiguration=e)}static local=null;sdkVersion=e.Nn;diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new Nt;breadcrumbs;tracing;sequence=new _e;journey;builder;remote={sampling:null,changed:()=>{this.refreshCaptures()}};identityEpoch=0;remoteCaptureTimer;installedCaptureKey=``;console;drops;meter;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=new It(e=>{this.dropHeld(e)});captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1,longFrames:!1,uncleanExit:!1,userTiming:!1};bootBuffer=new It(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=()=>{C(this),this.role()===`forwarder`&&(this.tracing.end(),this.sendForwarded())};constructor(e,t=!1){this.diagnostics=new B(e.onDiagnostic),this.platform=a.n(this.diagnostics),this.degraded=t||this.onServer(),this.config=z(this.allowed(e),this.diagnostics),this.explicitSecurityContext=!!e.securityContext?.id,this.config.securityContext.id||=c.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()?c.r():c.t,this.identity=c.s(this.diagnostics,this.stores,this.config.correlation.sessionIdleMs),this.sessionTouch=new c.n(this.diagnostics,this.stores,this.config.correlation.sessionTouchMs,this.config.correlation.sessionIdleMs),this.breadcrumbs=new De(this.config.capturePolicy.breadcrumbs);let n=e=>f.i(e,this.config.sampling.defaultRate);this.tracing=new Ee(this.diagnostics,this.config.correlation.traceMaxAgeMs||1/0,this.config.otelLoader,{enabled:()=>this.config.tracesEndpoint!==``,keeps:n,onEnd:e=>{n(e.traceId)&&this.recordSpan(Yt(e))}}),this.tracing.loadOtel(),this.limits={...this.config.limits},this.console=new ge(this.config.console,this.diagnostics,this.limits),this.drops=new Ft(this.config,this.diagnostics),this.journeyOptions={...d.t,maxAgeMs:this.config.journey.maxAgeMs},this.journey=new d.n(this.journeyOptions,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new Gt({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,debug:this.debugBuffer}),this.meter=new me(()=>this.config.batching.metricFlushIntervalMs,(e,t,n)=>{this.emitPoint(e,t,n)},this.diagnostics,this.config.metrics),this.diagnostics.setHandler(this.diagnosticHandler())}diagnosticHandler(){return this.config.diagnostics.records===!1?this.config.onDiagnostic:e=>{this.recordDiagnostic(e),this.config.onDiagnostic?.(e)}}recordDiagnostic(e){let{records:t}=this.config.diagnostics;if((t===!0||t!==!1&&t.includes(e.code))&&!this.recordingDiagnostic){this.recordingDiagnostic=!0;try{(rn.has(e.code)?this.diagnosticLogger.info:this.diagnosticLogger.warn)(e.message,{"diagnostic.code":e.code,"diagnostic.count":e.count,"diagnostic.detail":on(e.detail)})}finally{this.recordingDiagnostic=!1}}}addBreadcrumb(e,t){this.rotating||this.destroyed||this.diagnostics.guard(`record.sanitize_failed`,`The library could not add the breadcrumb.`,()=>{let n={t:Date.now(),category:`custom`,message:s.i(String(e),this.limits.maxBodyChars)};if(t!==void 0){let e=s.n(t,this.limits,this.diagnostics);n.data=r.t(e)?e:{value:e}}this.breadcrumbs.push(n)})}recordMetric(e,t,n){!this.destroyed&&!this.rotating&&this.meter.record(e,t,n)}startMeasure(e,t){let n=this.identityEpoch,r=()=>!this.destroyed&&!this.rotating&&(!this.config.securityContext.isolation||this.identityEpoch===n);return zt(e,this.diagnostics.guard(`record.sanitize_failed`,`The library could not read the attributes of the measure.`,()=>({...t}))??{},this.tracing.request().span,{metric:(e,t,n)=>{r()&&this.recordMetric(e,t,n)},span:e=>{r()&&this.recordSpan(e)}})}recordSpan(t){if(this.config.tracesEndpoint===``)return;let{record:n}=this.builder.build({level:`INFO`,type:`span`,body:t.name,namespace:e.In,payload:t.attributes,fixed:Xt(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.Pt,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[U]??null}static current(){let e=n.local;if(e)return e.destroyed?null:e;let t=n.pinned();return t&&K(t)?t:null}static stopped(){let e=n.local;if(e?.destroyed)return e;let t=globalThis[W];return t&&K(t)?t:null}isDestroyed(){return this.destroyed}static configure(e,t=!1){let r=n.local;if(r&&!r.destroyed)return r.reconfigure(e),r;n.local=null;let i=n.pinned();if(i){if(!K(i))return n.startDegraded(e,i.sdkVersion);if(!i.destroyed)return i.reconfigure(e),i}let a=new n(e);return a.tunablesLocked=!t,globalThis[U]=a,Reflect.deleteProperty(globalThis,W),a.init(),a}static startDegraded(t,r){let i=new n(t,!0);n.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.Nn}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,{found:a,own:e.Nn}),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=z(e,this.diagnostics,this.config);J(this.config,t)||this.diagnostics.report(`config.locked`,`Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.`);return}C(this);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]&&!J({...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=z(t,this.diagnostics,this.config);this.keepStartupTunables(n);let{redact:r,processors:i}=this.config;Mt(this.config,n),(this.config.redact!==r||this.config.processors!==i)&&this.debugBuffer.clear(),this.breadcrumbs.resize(this.config.capturePolicy.breadcrumbs),this.diagnostics.setHandler(this.diagnosticHandler()),this.diagnostics.setPolicy(this.config.diagnostics.throttleMs,this.config.diagnostics.consoleFallback),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.refreshCaptures(),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&&cn(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, transport and transportWorker.`)),sn(e)):e}keepRouting(e){if(!this.tunablesLocked||this.degraded||!this.config.securityContext.isolation)return e;let t=z(e,new B,this.config),n=nn.filter(e=>!J(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 nn)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,tn),!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)J(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;for(let n of[`transport`,`transportWorker`])n in e&&e[n]===void 0!=(this.config[n]===void 0)&&(this.diagnostics.report(`config.invalid`,`You cannot add or remove ${n} after the delivery stack loads. The transport in force stays.`),t={...t},Reflect.deleteProperty(t,n));return(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-VWlmM5xs.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){C(this),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:c.i(this.diagnostics)),this.rotating=e,this.identityEpoch++,this.remote.sampling=null,this.refreshCaptures()}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-D5wBoXA8.cjs")),t=this.destroyed?null:await e.create({storage:this.memoryStorage,onStorage:e=>{e.name===`memory`&&(this.memoryStorage=e)},onPersistence:e=>{this.storagePersistence=e},config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap,onLoss:this.reportLoss,remote:this.remote,beforeExit:()=>{C(this),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)}refreshCaptures(){if(clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 0,this.destroyed)return;let e=this.remote.sampling?.wire();e&&(this.remoteCaptureTimer=setTimeout(()=>{this.refreshCaptures()},e.ttlMs),i.r(this.remoteCaptureTimer)),an(this.effectiveCapture())!==this.installedCaptureKey&&this.installCaptures()}effectiveCapture(){let t={...this.config.capture},n=this.remote.sampling?.current()?.capture;for(let r of e.qt){let e=n?.[r];if(t.remoteToggles.includes(r)&&e!==void 0){if(e&&typeof t[r]==`object`)continue;t[r]=e}}return t}async installCaptures(){if(this.degraded)return;let t=++this.captureGeneration,n=this.effectiveCapture();this.installedCaptureKey=an(n);let 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`),n.uncleanExit&&r.push(`uncleanExit`),n.userTiming&&r.push(`userTiming`),n.reports&&r.push(`reports`),n.resourceTiming&&r.push(`resourceTiming`),n.lifecycle&&r.push(`lifecycle`);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:Object.assign(Object.create(this.config),{capture:n}),diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new E(()=>this,e.N),once:this.captureOnce,recordMetric:(e,t,n)=>{this.recordMetric(e,t,n)},recordSpan:e=>{this.recordSpan(e)},sessionId:()=>this.identity.sessionId};for(let e of i)e&&this.captures.push(new e(o));let s=a?[...n.plugins,new a(this.diagnostics,o.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-BWUoqBh8.cjs"))).WebSocketCapture)}pluginCapture(t){let{name:n}=t,r=(e,t,n)=>{this.recordMetric(e,t,n)},i={logger:new E(()=>this,`${e.N}.${n}`),counter:(e,t={})=>fe(e,t,r),histogram:(e,t={})=>pe(e,t,r),addBreadcrumb:(e,t)=>{this.addBreadcrumb(e,t)},ownRequest:l.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.`,Zt[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;C(this),this.meter.collect(),this.tracing.end(),this.destroyed=!0,w(this),clearTimeout(this.remoteCaptureTimer),this.remoteCaptureTimer=void 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(),n.pinned()===this&&(Reflect.deleteProperty(globalThis,U),globalThis[W]=this)}emit(e){if(!e||this.destroyed||this.rotating&&!this.closingContext)return;this.sessionTouch.touch(this.identity.sessionId);let t=e.severityText===`ERROR`||e.severityText===`FATAL`?[...this.debugBuffer.drain(),e]:[e];for(let e of t)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 n=[];for(let r of e){if(!t.n(r)){this.diagnostics.count(`record.dropped_malformed`);continue}if(r.attributes[`uiobs.debug_buffer`]!==!0&&!f.a(r,this.config,this.remote.sampling?.current()??null)){this.diagnostics.count(`record.dropped_by_sampling`);continue}let e=this.builder.redactForwarded(r);e&&n.push(e)}if(this.rotating)this.drops.add(`security_context`,n);else for(let e of n)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 E(()=>this,e.wn).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=c.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,c.a(e,this.diagnostics,this.stores),this.builder.invalidateResource()}newSession(){this.destroyed||(C(this),this.resetSession(c.i(this.diagnostics)))}resetSession(e){this.meter.collect(),this.tracing.rotate(`explicit`),this.journey.end(),this.breadcrumbs.clear(),this.debugBuffer.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 n=t.pending??`discard`,i=t.timeoutMs??5e3;return!r.t(e)||!r.t(e.delivery)||![`discard`,`flush`,`retain`,`carry`].includes(n)||!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.`)):(C(this),this.rotating=!0,this.rotation=this.rotateContext(e,n,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??c.i(this.diagnostics);if(i===r)throw Error(`A rotation requires a different security-context id.`);let a={...G,...e.delivery},o=this.diagnostics.snapshot()[`config.invalid`]??0,s=z(this.allowed({...a,securityContext:{id:i}}),this.diagnostics,{...this.config,...G});if((this.diagnostics.snapshot()[`config.invalid`]??0)!==o)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([s.endpoint,s.metricsEndpoint,s.tracesEndpoint]);s.capture.ignoreUrls=s.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]),s.lockConfiguration=this.config.lockConfiguration,Mt(this.config,s),this.identityEpoch++,this.remote.sampling=null,this.refreshCaptures(),this.context.clear(),l&&this.context.setMany(l),this.breadcrumbs.clear(),this.newSession(),this.builder.invalidateResource(),await this.syncSender(),this.bus?.rotateContext(),this.rotating=!1,t===`carry`&&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 debugBundle(t){let{configSummary:n}=await Promise.resolve().then(()=>require("./debug-bundle-BzJNpbF0.cjs")),{record:r}=this.builder.build({level:`INFO`,type:`system`,body:`debug bundle`,namespace:e.q,payload:{[e.c]:this.breadcrumbs.snapshot()}},!0),i=r?.attributes??{},a=i[e.c],o=i[e.v];return{createdAt:new Date().toISOString(),sdkVersion:this.sdkVersion,health:t,diagnostics:this.diagnostics.snapshot(),resource:r?.resource??{},pageUrl:typeof o==`string`?o:``,breadcrumbs:Array.isArray(a)?a:[],debugBuffer:this.debugBuffer.snapshot(),config:n(this.config,this.limits,this.diagnostics)}}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},storagePersistence:this.storagePersistence,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-CJXVYp0R.cjs")),Promise.resolve().then(()=>require("./context-storage-BjzeBSxH.cjs")),Promise.resolve().then(()=>require("./storage-BA9RqRO-.cjs")),Promise.resolve().then(()=>require("./emergency-queue-CNTRui5t.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(){C(this),this.meter.collect(),this.ready||await this.started,this.role()===`forwarder`?this.sendForwarded():(await this.senderLoad,await this.sender?.flush())}};function J(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)&&J(Reflect.get(e,r),Reflect.get(t,r),n))}var Y;function ln(t={}){if(Y)return Y;let n=new B(t.onDiagnostic);if(typeof document<`u`||typeof addEventListener!=`function`)return n.report(`config.invalid`,`Call serveTransportWorker() in a dedicated worker.`),()=>void 0;let i=!1,a,o,s=t=>{n.guard(`transport.http_error`,`The transport worker could not read its connection.`,()=>{let s=t.data;if(!r.t(s)||s.p!==`ui-observability.transport/1`||s.t!==e.Bn.connect||t.ports.length===0)return;let c=t.ports[0];a||s.v!==`0.11.0`?(c.postMessage(e.zn),c.close()):(a=c,Promise.resolve().then(()=>require("./worker-server-BrIYkfoa.cjs")).then(e=>{i||(o=e.serveWorkerPort(c,n))}).catch(t=>{n.report(`transport.http_error`,`The transport worker delivery module could not load.`,void 0,t),n.guard(`transport.http_error`,`The failed transport port could not be closed.`,()=>{c.postMessage(e.zn),c.close()})}))})},c=()=>{i||(i=!0,Y=void 0,removeEventListener(`message`,s),o?.(),n.guard(`transport.http_error`,`The transport service could not close its port.`,()=>{a?.postMessage(e.zn)}),n.guard(`transport.http_error`,`The transport port could not close.`,()=>{a?.close()}))};return addEventListener(`message`,s),Y=c,c}function un(){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(q.current()??q.stopped())||q.configure({},!0)}function dn(e=`context`){return[`context`,`namespace`].includes(e)?Z().clearPersisted(e):Promise.reject(Error(`Invalid persistence scope.`))}function fn(e){q.configure(e),Q()}function pn(e){Z().setConfigurationLocked(e)}function mn(e,t){return Z().rotateSecurityContext(e,t)}async function hn(){let e=Z();return Q(),{...await e.health(),loggerCache:{...e.config.loggerCache,size:X.size}}}async function gn(){let e=await hn();return Z().debugBundle(e)}function Q(){let e=(q.current()??q.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 _n(e,t){let n=Q();if(t||n===0)return new E(Z,e,t);let r=X.get(e);return r??=new E(Z,e),X.delete(e),X.set(e,r),Q(),r}function $(){return _n(`app`)}function vn(e,t){$().trace(e,t)}function yn(e,t){$().debug(e,t)}function bn(e,t){$().info(e,t)}function xn(e,t){$().warn(e,t)}function Sn(e,t,n){$().error(e,t,n)}function Cn(e,t,n){$().fatal(e,t,n)}function wn(e,t){$().logAction(e,t)}function Tn(e,t){$().logEvent(e,t)}function En(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function Dn(e,t={}){return fe(e,t,(e,t,n)=>{Z().recordMetric(e,t,n)})}function On(e,t={}){return pe(e,t,(e,t,n)=>{Z().recordMetric(e,t,n)})}function kn(e,t){return Z().startMeasure(e,t)}function An(e,t,n){return $().timeSync(e,t,n)}function jn(e,t,n){return $().timeAsync(e,t,n)}function Mn(e,t){Z().addBreadcrumb(e,t)}function Nn(e,t){Z().context.set(e,t)}function Pn(e){Z().context.setMany(e)}function Fn(e){Z().context.remove(e)}function In(e,t){return Z().journey.start(e,t)}function Ln(){Z().journey.end()}function Rn(){return Z().journey.current()}function zn(){return Z().journey.getToken()}function Bn(e){return Z().journey.adopt(e,`manual`,!0)}function Vn(e,t){return Z().registerWorker(e,t)}function Hn(e,t){return Z().registerFrame(e,t)}function Un(){Z().tracing.rotate(`explicit`)}function Wn(){return Z().tracing.headers()}function Gn(){return Z().flush()}function Kn(){return Z().queueDepth()}function qn(){return Z().stats()}function Jn(){Z().newSession()}function Yn(){return Z().diagnostics.snapshot()}async function Xn(){await q.current()?.destroy()}exports.OneLogger=E,exports.addBreadcrumb=Mn,exports.adoptJourney=Bn,exports.clearPersistedLogs=dn,exports.collectDebugBundle=gn,exports.configure=fn,exports.counter=Dn,exports.createMemoryTransport=un,exports.currentJourney=Rn,exports.debug=yn,exports.endJourney=Ln,exports.error=Sn,exports.fatal=Cn,exports.flush=Gn,exports.getDiagnosticCounters=Yn,exports.getHealth=hn,exports.getJourneyToken=zn,exports.getLogger=_n,exports.getQueueDepth=Kn,exports.getStats=qn,exports.getTraceHeaders=Wn,exports.histogram=On,exports.info=bn,exports.logAction=wn,exports.logEvent=Tn,exports.logMetric=En,exports.newSession=Jn,exports.registerFrame=Hn,exports.registerWorker=Vn,exports.removeContext=Fn,exports.rotateSecurityContext=mn,exports.serveTransportWorker=ln,exports.setConfigurationLocked=pn,exports.setContext=Nn,exports.setContextMap=Pn,exports.shutdown=Xn,exports.startJourney=In,exports.startMeasure=kn,exports.startTrace=Un,exports.timeAsync=jn,exports.timeSync=An,exports.trace=vn,exports.warn=xn;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|