@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
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
require("./constants-CW-MlHdY.cjs");const e=require("./platform-DBSKTvFn.cjs"),t=require("./patch-BX8KrPCT.cjs");function n(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function r(){return history}var i=class{ctx;name=`interactions`;installed=!1;restores=[];lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){if(this.installed){this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate);for(let e of this.restores.splice(0))e()}}onClick=e=>{if(this.ctx.isActive?.()===!1)return;let t=e.target;if(!(t instanceof Element))return;let r=this.ctx.config.capture.interactions,i=typeof r==`object`?r:{},a=i.ignoreSelector===void 0?`[data-observability-ignore]`:i.ignoreSelector;if(a&&t.closest(a))return;let o=i.actionAttribute??`data-observability-action`,s=t.closest(`[${o}]`)?.getAttribute(o)??``,c={};i.selector&&(c.selector=n(t)),i.text&&(c.text=t.textContent.trim().slice(0,i.maxTextChars??50)),this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:(s||`unknown-click`).slice(0,this.ctx.config.limits.maxBodyChars),data:Object.keys(c).length>0?c:void 0})};onNavigate=()=>{let t=this.lastUrl,n=location.href;if(t===n||(this.lastUrl=n,this.ctx.isActive?.()===!1))return;let r=this.ctx.config.capture.fullUrls,{urlTransform:i}=this.ctx.config.capture,a=e.i(t,r,i,this.ctx.diagnostics),o=e.i(n,r,i,this.ctx.diagnostics);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${a} -> ${o}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":a})};installHistory(){if(typeof history>`u`)return;let e=r(),n=this.onNavigate,i=!0,a=t.t(e,`pushState`,e=>function(...t){e.apply(this,t),i&&queueMicrotask(n)}),o=t.t(e,`replaceState`,e=>function(...t){e.apply(this,t),i&&queueMicrotask(n)});this.restores.push(()=>{i=!1,a(),o()})}};exports.InteractionCapture=i;
|
|
2
|
-
//# sourceMappingURL=interactions-NHbLKrqe.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interactions-NHbLKrqe.cjs","names":["recordedUrl","patch","require_platform","require_patch","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","action","data","from","to","full","fromUrl","urlTransform","toUrl","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\n // An absent or empty attribute gives \"\". The message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const data: Record<string, unknown> = {};\n if (options.selector) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars),\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n };\n\n /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) return;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"iHAoBA,SAASI,EAAgB,EAA0B,CACjD,IAAMC,EAAMC,EAAQ,QAAQ,YAAY,EAElCC,EAASD,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIC,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAID,EAAQ,KAAO,GACjB,MAAO,IAAIA,E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A,gBAA+B,CAC7B,GAAI,OAAO,QAAY,IACrB,OAKF,IAAMX,EAASJ,EAAe,EACxBkB,EAAa,KAAK,WAEpBC,EAAS,GAEPC,EAAmB7B,EAAAA,EACvBa,EACA,YACC,GACC,SAAyB,GAAGiB,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EAGrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEMK,EAAsBhC,EAAAA,EAC1Ba,EACA,eACC,GACC,SAAyB,GAAGiB,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EACrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEA,KAAK,SAAS,SAAW,CACvB,EAAS,GACTE,EAAiB,EACjBG,EAAoB,CACtB,CAAC,CACH,CACF"}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { Sn as e, _t as t } from "./constants-CN7GE1Lt.js";
|
|
2
|
-
import { t as n } from "./global-scope-dp2jADRl.js";
|
|
3
|
-
//#region src/utils/library-request.ts
|
|
4
|
-
var r = n(t), i = Symbol.for(e), a = globalThis, o = () => a[i] ?? 0;
|
|
5
|
-
function s(e) {
|
|
6
|
-
return r.run(e);
|
|
7
|
-
}
|
|
8
|
-
function c() {
|
|
9
|
-
return r.open();
|
|
10
|
-
}
|
|
11
|
-
async function l(e) {
|
|
12
|
-
a[i] = o() + 1;
|
|
13
|
-
try {
|
|
14
|
-
return await e();
|
|
15
|
-
} finally {
|
|
16
|
-
a[i] = o() - 1;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function u() {
|
|
20
|
-
return o() > 0;
|
|
21
|
-
}
|
|
22
|
-
//#endregion
|
|
23
|
-
export { l as i, u as n, s as r, c as t };
|
|
24
|
-
|
|
25
|
-
//# sourceMappingURL=library-request-BKOcaKtQ.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./error-like-gGRx2s36.cjs"),t=require("./library-request-BaZOi4eg.cjs"),n=require("./platform-DBSKTvFn.cjs"),r=require("./patch-BX8KrPCT.cjs"),i=require("./types-C7WNpnG1.cjs");var a=1e3,o={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function s(t,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":t,"server.address":new URL(n,a).hostname};if(r===0){let t=e.r(i)?i.name:``;return o[`error.type`]=t===``?`_OTHER`:t,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function c(){return XMLHttpRequest.prototype}function l(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function u(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),f(n??`GET`)}function d(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function f(e){return typeof e==`string`?e.toUpperCase():String(e)}var p=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return t.t()||i.t(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,t=(e,t)=>this.prepareFetch(e,t),n=(e,t,n,r)=>{this.record(e.method,e.url,t,n,r,e.span,e.routingContextId)},i=r.t(globalThis,`fetch`,r=>{let i=r.bind(globalThis);return async function(r,a){let o=e?t(r,a):void 0;if(!o)return i(r,a);let s=performance.now();try{let e=await i(o.input,o.init);return n(o,e.status,performance.now()-s,void 0),e}catch(e){throw n(o,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=l(e);if(!this.ignored(n))return{method:u(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t,routingContextId:this.ctx.config.securityContext.id};if(!n.propagate||d(e))return a;try{let n=this.ctx.tracing.request(),r=Object.entries(n.headers);if(e instanceof Request){let t=new Headers(e.headers);for(let[e,n]of r)t.set(e,n);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,n]of r)e.set(t,n);a.init={...t,headers:e}}a.span=n.span}catch(n){a.input=e,a.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n)=>{this.record(e.method,e.url,t,n,void 0,e.span,e.routingContextId)},o=c(),s=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:f(r),url:l(i),startedAt:0}}),n.apply(this,[r,i,...a])}),u=r.t(o,`send`,r=>function(...o){let s=e?this.__uiobs:void 0;s&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${s.method} ${s.url}.`,()=>{n(s.url)||(s.startedAt=performance.now(),s.routingContextId=t.config.securityContext.id,this.addEventListener(`loadend`,()=>{a(s,this.status,performance.now()-s.startedAt)},{once:!0}),i(s.url)&&(s.span=m(this,s.url,t)))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l,u,d){if(this.ctx.isActive?.()===!1||this.ctx.config.securityContext.isolation&&d!==void 0&&d!==this.ctx.config.securityContext.id)return;let f=n.i(r,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics);!this.warnedTransport&&t.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${f} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${f}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),u&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the span of ${e} ${f}.`,()=>{let t=Date.now();this.ctx.recordSpan({...u,name:e,kind:`client`,startMs:t-c,endMs:t,error:i===0||i>=400,attributes:{...s(e,r,i,l),"url.full":f}})}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${f}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${f} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":f,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${f} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${f} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${f}`,n)})}};function m(e,t,n){try{let t=n.tracing.request();for(let[n,r]of Object.entries(t.headers))e.setRequestHeader(n,r);return t.span}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e);return}}exports.NetworkCapture=p;
|
|
2
|
-
//# sourceMappingURL=network-CF8UO5PK.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-CF8UO5PK.cjs","names":["isErrorLike","isLibraryRequest","matchesAny","patch","recordedUrl","isTransportPending","require_error_like","require_library_request","require_platform","require_patch","require_types","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","span","endMs","rounded","xhr"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n )\n return;\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":"kMAgBA,IAAMW,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIC,EAAKH,CAAI,CAAC,CAAC,QACvC,EAEA,GAAII,IAAW,EAAG,CAEhB,IAAMC,EAAOnB,EAAAA,EAAYoB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS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ED,IAAMjD,EAAa,CACjB,sBAAuBC,EACvB,WAAYC,EACZ,4BAA6BC,EAC7B,mBAAoB8C,CACtB,EAEI9C,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGF,EAAO,GAAGC,EAAI,SAAUG,EAAOL,CAAU,EAGhEG,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGF,EAAO,GAAGC,EAAI,YAAY,OAAOC,CAAM,IAAKH,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGC,EAAO,GAAGC,IAAOF,CAAU,CACtD,CACF,CACF,CACF,EASA,SAAS4C,EACP,EACA,EACA,EACwB,CACxB,GAAI,CACF,IAAMd,EAAQf,EAAI,QAAQ,QAAQ,EAClC,IAAK,GAAM,CAACkB,EAAKC,KAAU,OAAO,QAAQJ,EAAM,OAAO,EACrDoB,EAAI,iBAAiBjB,EAAKC,CAAK,EAEjC,OAAOJ,EAAM,IACf,OAASzB,EAAO,CACdU,EAAI,YAAY,OACd,wBACA,oFACA,CAAE,KAAI,EACNV,CACF,EACA,MACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-DdzXDI3J.js","names":["isErrorLike","isTransportPending","isLibraryRequest","recordedUrl","patch","matchesAny","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","routingContextId","span","endMs","rounded"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Delivery context when the request started. */\n routingContextId?: string;\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(\n plan.method,\n plan.url,\n status,\n durationMs,\n error,\n plan.span,\n plan.routingContextId,\n );\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = {\n method,\n url,\n input,\n init,\n routingContextId: this.ctx.config.securityContext.id,\n };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(\n meta.method,\n meta.url,\n status,\n durationMs,\n undefined,\n meta.span,\n meta.routingContextId,\n );\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n meta.routingContextId = ctx.config.securityContext.id;\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n routingContextId?: string,\n ): void {\n if (\n this.ctx.isActive?.() === false ||\n (this.ctx.config.securityContext.isolation &&\n routingContextId !== undefined &&\n routingContextId !== this.ctx.config.securityContext.id)\n )\n return;\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(\n target,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAMM,IAAgB,KAMhBC,IAA+B;CACnC,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAO;EAAM;EAAO;EAAM;EAAO;EAAK;EAAM;EAAK;EAAM;EAAG;EAAK;EAAG;EAAK;CAAE;AACxF;AAWA,SAASC,EACP,GACA,GACA,GACA,GACkB;CAElB,IAAMC,IAAO,OAAO,WAAa,MAAc,SAAS,OAAO,KAAA,GACzDC,IAA+B;EACnC,uBAAuBC;EACvB,kBAAkB,IAAI,IAAIC,GAAKH,CAAI,CAAC,CAAC;CACvC;CAEA,IAAII,MAAW,GAAG;EAEhB,IAAMC,IAAOd,EAAYe,CAAK,IAAIA,EAAM,OAAO;EAE/C,OADA,EAAW,gBAAgBD,MAAS,KAAK,WAAWA,GAC7CJ;CACT;CAOA,OALA,EAAW,+BAA+BG,GACtCA,KAAU,QACZ,EAAW,gBAAgB,OAAOA,CAAM,IAGnCH;AACT;AA4BA,SAASM,IAAyB;CAChC,OAAO,eAAe;AACxB;AAyBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAE,WAAQA;EAChB,IAAI,OAAON,KAAQ,UACjB,OAAOA;CAEX;CAGA,OAAO,OAAOM,C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GACA,GACA,GACwB;CACxB,IAAI;EACF,IAAMd,IAAQf,EAAI,QAAQ,QAAQ;EAClC,KAAK,IAAM,CAACkB,GAAKC,MAAU,OAAO,QAAQJ,EAAM,OAAO,GACrD,EAAI,iBAAiBG,GAAKC,CAAK;EAEjC,OAAOJ,EAAM;CACf,SAASzB,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;EACA;CACF;AACF"}
|
package/dist/openfin-BwEN0uj4.js
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import { It as e, Lt as t, mt as n } from "./constants-CN7GE1Lt.js";
|
|
2
|
-
import { n as r, r as i, u as a } from "./sampling-Cm3WhI0a.js";
|
|
3
|
-
//#region src/core/remote-sampling.ts
|
|
4
|
-
var o = class {
|
|
5
|
-
config;
|
|
6
|
-
rules = null;
|
|
7
|
-
receivedAt = 0;
|
|
8
|
-
until = 0;
|
|
9
|
-
constructor(e) {
|
|
10
|
-
this.config = e;
|
|
11
|
-
}
|
|
12
|
-
apply(e) {
|
|
13
|
-
if (!e) {
|
|
14
|
-
this.rules = null;
|
|
15
|
-
return;
|
|
16
|
-
}
|
|
17
|
-
let t = Date.now();
|
|
18
|
-
this.rules = e.rules, this.receivedAt = t, this.until = t + e.ttlMs;
|
|
19
|
-
}
|
|
20
|
-
current() {
|
|
21
|
-
if (!this.rules) return null;
|
|
22
|
-
let e = Date.now();
|
|
23
|
-
return !this.config.sampling.remote || e < this.receivedAt || e >= this.until ? (this.rules = null, null) : this.rules;
|
|
24
|
-
}
|
|
25
|
-
minLevelFor(e) {
|
|
26
|
-
let t = r(e, this.config), a = this.current(), o = i(e, a?.minLevels ?? {})?.value ?? a?.minLevel;
|
|
27
|
-
return o !== void 0 && n[o] < n[t] ? o : t;
|
|
28
|
-
}
|
|
29
|
-
wire() {
|
|
30
|
-
let e = this.current();
|
|
31
|
-
return e ? {
|
|
32
|
-
...e,
|
|
33
|
-
v: 1,
|
|
34
|
-
ttlMs: this.until - Date.now()
|
|
35
|
-
} : null;
|
|
36
|
-
}
|
|
37
|
-
}, s = class extends Error {};
|
|
38
|
-
function c(e) {
|
|
39
|
-
return typeof e == "number" && e >= 0 && e <= 1;
|
|
40
|
-
}
|
|
41
|
-
function l(t) {
|
|
42
|
-
if (t.length > 4096) throw new s(`The header is longer than ${String(e)} characters.`);
|
|
43
|
-
try {
|
|
44
|
-
return JSON.parse(t);
|
|
45
|
-
} catch {
|
|
46
|
-
throw new s("The header is not valid JSON.");
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
function u(e) {
|
|
50
|
-
if (e === void 0) return {};
|
|
51
|
-
let t = "rates must be an object with at most 100 rates from 0 to 1.";
|
|
52
|
-
if (!a(e)) throw new s(t);
|
|
53
|
-
let n = Object.entries(e);
|
|
54
|
-
if (n.length > 100 || !n.every(([, e]) => c(e))) throw new s(t);
|
|
55
|
-
return Object.fromEntries(n);
|
|
56
|
-
}
|
|
57
|
-
function d(e) {
|
|
58
|
-
let t = "minLevels must be an object with at most 100 level names.";
|
|
59
|
-
if (!a(e)) throw new s(t);
|
|
60
|
-
let r = Object.entries(e), i = r.every(([, e]) => typeof e == "string" && Object.hasOwn(n, e));
|
|
61
|
-
if (r.length > 100 || !i) throw new s(t);
|
|
62
|
-
return Object.fromEntries(r);
|
|
63
|
-
}
|
|
64
|
-
function f(e) {
|
|
65
|
-
if (!a(e)) throw new s("The rules must be an object.");
|
|
66
|
-
if (e.v !== 1) throw new s("The version must be 1.");
|
|
67
|
-
let { ttlMs: r, defaultRate: i, minLevel: o } = e;
|
|
68
|
-
if (typeof r != "number" || !(r > 0 && r <= 36e5)) throw new s(`ttlMs must be a number more than 0 and at most ${String(t)}.`);
|
|
69
|
-
if (i !== void 0 && !c(i)) throw new s("defaultRate must be a number from 0 to 1.");
|
|
70
|
-
if (o !== void 0 && !(typeof o == "string" && Object.hasOwn(n, o))) throw new s("minLevel must be a level name, for example DEBUG.");
|
|
71
|
-
let l = { rates: u(e.rates) };
|
|
72
|
-
return i !== void 0 && (l.defaultRate = i), o !== void 0 && (l.minLevel = o), e.minLevels !== void 0 && (l.minLevels = d(e.minLevels)), {
|
|
73
|
-
rules: l,
|
|
74
|
-
ttlMs: r
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
function p(e, t) {
|
|
78
|
-
try {
|
|
79
|
-
return f(typeof e == "string" ? l(e) : e);
|
|
80
|
-
} catch (e) {
|
|
81
|
-
let n = e instanceof s ? ` ${e.message}` : "";
|
|
82
|
-
return t.report("config.invalid", `The library ignores the sampling rules from the server.${n}`, void 0, e), null;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
function m(e, t, n) {
|
|
86
|
-
n && (e.sampling ??= new o(t)), e.sampling?.apply(n);
|
|
87
|
-
}
|
|
88
|
-
//#endregion
|
|
89
|
-
export { p as n, m as t };
|
|
90
|
-
|
|
91
|
-
//# sourceMappingURL=remote-rules-DIcC5vVC.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-DIcC5vVC.js","names":["REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","levelFor","longestPrefix","isObject","RemoteSampling","config","update","now","local","namespace","rules","remote","RuleError","isRate","value","parseText","text","readRates","rule","entries","rate","readMinLevels","valid","level","readRules","ttlMs","defaultRate","minLevel","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { levelFor, longestPrefix } from \"./sampling\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n /** Lowest level for each namespace prefix. It can only lower the level of the config. */\n minLevels?: Record<string, LogLevel>;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends for a namespace. A remote prefix level wins\n * over the remote `minLevel`. A remote level applies only when it is lower than the config level.\n * @param namespace Target application namespace.\n * @returns The lower of the remote level and the config level of the namespace.\n */\n minLevelFor(namespace: string): LogLevel {\n const local = levelFor(namespace, this.config);\n const rules = this.current();\n const remote = longestPrefix(namespace, rules?.minLevels ?? {})?.value ?? rules?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[local] ? remote : local;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Reads the level for each namespace prefix.\n * @param value Value of `minLevels`.\n * @returns The levels.\n * @throws RuleError when a level is not valid.\n */\nfunction readMinLevels(value: unknown): Record<string, LogLevel> {\n const rule = `minLevels must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} level names.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n const valid = entries.every(\n ([, level]) => typeof level === \"string\" && Object.hasOwn(LEVEL_ORDER, level),\n );\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !valid) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, LogLevel>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n if (value.minLevels !== undefined) {\n rules.minLevels = readMinLevels(value.minLevels);\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":";;;AA8CA,IAAaM,IAAb,MAA4B;CAaG;CAX7B,QAAoC;CAGpC,aAAqB;CAGrB,QAAgB;CAKhB,YAAY,GAAyC;EAAxB,KAAA,SAAAC;CAAyB;CAMtD,MAAM,GAAmC;EACvC,IAAI,CAACC,GAAQ;GACX,KAAK,QAAQ;GACb;EACF;EAEA,IAAMC,IAAM,KAAK,IAAI;EAIrB,AAFA,KAAK,QAAQD,EAAO,OACpB,KAAK,aAAaC,GAClB,KAAK,QAAQA,IAAMD,EAAO;CAC5B;CAMA,UAA8B;EAC5B,IAAI,CAAC,KAAK,OACR,OAAO;EAGT,IAAMC,IAAM,KAAK,IAAI;EASrB,OALI,CAAC,KAAK,OAAO,SAAS,UAAUA,IAAM,KAAK,cAAcA,KAAO,KAAK,SACvE,KAAK,QAAQ,MACN,QAGF,KAAK;CACd;CAQA,YAAY,GAA6B;EACvC,IAAMC,IAAQP,EAASQ,GAAW,KAAK,MAAM,GACvCC,IAAQ,KAAK,QAAQ,GACrBC,IAAST,EAAcO,GAAWC,GAAO,aAAa,CAAC,CAAC,CAAC,EAAE,SAASA,GAAO;EAEjF,OAAOC,MAAW,KAAA,KAAaX,EAAYW,KAAUX,EAAYQ,KAASG,IAASH;CACrF;CAMA,OAA0B;EACxB,IAAME,IAAQ,KAAK,QAAQ;EAM3B,OAJKA,IAIE;GAAE,GAAGA;GAAO,GAAA;GAA4B,OAAO,KAAK,QAAQ,KAAK,IAAI;EAAE,IAHrE;CAIX;AACF,GCnGME,IAAN,cAAwB,MAAM,CAAC;AAO/B,SAASC,EAAO,GAAiC;CAC/C,OAAO,OAAOC,KAAU,YAAYA,KAAA,KAA8BA,K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,EACvF;CAGF,IAAI2B,MAAgB,KAAA,KAAa,CAACb,EAAOa,CAAW,GAClD,MAAM,IAAId,EAAU,2CAA2C;CAGjE,IACEe,MAAa,KAAA,KACb,EAAE,OAAOA,KAAa,YAAY,OAAO,OAAO3B,GAAa2B,CAAQ,IAErE,MAAM,IAAIf,EAAU,mDAAmD;CAGzE,IAAMF,IAAqB,EAAE,OAAOO,EAAUH,EAAM,KAAK,EAAE;CAc3D,OAZIY,MAAgB,KAAA,MAClB,EAAM,cAAcA,IAGlBC,MAAa,KAAA,MACf,EAAM,WAAWA,IAGfb,EAAM,cAAc,KAAA,MACtB,EAAM,YAAYO,EAAcP,EAAM,SAAS,IAG1C;EAAE;EAAO;CAAM;AACxB;AAQA,SAAgBc,EAAiB,GAAc,GAA+C;CAC5F,IAAI;EACF,OAAOJ,EAAU,OAAOK,KAAQ,WAAWd,EAAUc,CAAG,IAAIA,CAAG;CACjE,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiBlB,IAAY,IAAIkB,EAAM,YAAY;EAQlE,OANAE,EAAY,OACV,kBACA,0DAA0DD,KAC1D,KAAA,GACAD,CACF,GACO;CACT;AACF;AAQA,SAAgBG,EACd,GACA,GACA,GACM;CAKN,AAJI3B,MACF,EAAK,aAAa,IAAIF,EAAeC,CAAM,IAG7C6B,EAAK,UAAU,MAAM5B,CAAM;AAC7B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CW-MlHdY.cjs"),t=require("./sampling-BVjspJWu.cjs");var n=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevelFor(n){let r=t.n(n,this.config),i=this.current(),a=t.r(n,i?.minLevels??{})?.value??i?.minLevel;return a!==void 0&&e.mt[a]<e.mt[r]?a:r}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},r=class extends Error{};function i(e){return typeof e==`number`&&e>=0&&e<=1}function a(t){if(t.length>4096)throw new r(`The header is longer than ${String(e.It)} characters.`);try{return JSON.parse(t)}catch{throw new r(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let n=`rates must be an object with at most 100 rates from 0 to 1.`;if(!t.u(e))throw new r(n);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>i(e)))throw new r(n);return Object.fromEntries(a)}function s(n){let i=`minLevels must be an object with at most 100 level names.`;if(!t.u(n))throw new r(i);let a=Object.entries(n),o=a.every(([,t])=>typeof t==`string`&&Object.hasOwn(e.mt,t));if(a.length>100||!o)throw new r(i);return Object.fromEntries(a)}function c(n){if(!t.u(n))throw new r(`The rules must be an object.`);if(n.v!==1)throw new r(`The version must be 1.`);let{ttlMs:a,defaultRate:c,minLevel:l}=n;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new r(`ttlMs must be a number more than 0 and at most ${String(e.Lt)}.`);if(c!==void 0&&!i(c))throw new r(`defaultRate must be a number from 0 to 1.`);if(l!==void 0&&!(typeof l==`string`&&Object.hasOwn(e.mt,l)))throw new r(`minLevel must be a level name, for example DEBUG.`);let u={rates:o(n.rates)};return c!==void 0&&(u.defaultRate=c),l!==void 0&&(u.minLevel=l),n.minLevels!==void 0&&(u.minLevels=s(n.minLevels)),{rules:u,ttlMs:a}}function l(e,t){try{return c(typeof e==`string`?a(e):e)}catch(e){let n=e instanceof r?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${n}`,void 0,e),null}}function u(e,t,r){r&&(e.sampling??=new n(t)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
|
|
2
|
-
//# sourceMappingURL=remote-rules-DpFmOef2.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-DpFmOef2.cjs","names":["levelFor","longestPrefix","LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","isObject","LEVEL_ORDER","REMOTE_SAMPLING_MAX_TTL_MS","require_constants","require_sampling","RemoteSampling","config","update","now","local","namespace","rules","remote","RuleError","isRate","value","parseText","text","readRates","rule","entries","rate","readMinLevels","valid","level","readRules","ttlMs","defaultRate","minLevel","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { levelFor, longestPrefix } from \"./sampling\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n /** Lowest level for each namespace prefix. It can only lower the level of the config. */\n minLevels?: Record<string, LogLevel>;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends for a namespace. A remote prefix level wins\n * over the remote `minLevel`. A remote level applies only when it is lower than the config level.\n * @param namespace Target application namespace.\n * @returns The lower of the remote level and the config level of the namespace.\n */\n minLevelFor(namespace: string): LogLevel {\n const local = levelFor(namespace, this.config);\n const rules = this.current();\n const remote = longestPrefix(namespace, rules?.minLevels ?? {})?.value ?? rules?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[local] ? remote : local;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Reads the level for each namespace prefix.\n * @param value Value of `minLevels`.\n * @returns The levels.\n * @throws RuleError when a level is not valid.\n */\nfunction readMinLevels(value: unknown): Record<string, LogLevel> {\n const rule = `minLevels must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} level names.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n const valid = entries.every(\n ([, level]) => typeof level === \"string\" && Object.hasOwn(LEVEL_ORDER, level),\n );\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !valid) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, LogLevel>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n if (value.minLevels !== undefined) {\n rules.minLevels = readMinLevels(value.minLevels);\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":"iFA8CA,IAAaS,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF,CAEA,IAAMC,EAAM,KAAK,IAAI,EAErB,KAAK,MAAQD,EAAO,MACpB,KAAK,WAAaC,EAClB,KAAK,MAAQA,EAAMD,EAAO,KAC5B,CAMA,SAA8B,CAC5B,GAAI,CAAC,KAAK,MACR,OAAO,KAGT,IAAMC,EAAM,KAAK,IAA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,SAAWd,EAAUc,CAAG,EAAIA,CAAG,CACjE,OAASC,EAAO,CACd,IAAMC,EAASD,aAAiBlB,EAAY,IAAIkB,EAAM,UAAY,GAQlE,OANAE,EAAY,OACV,iBACA,0DAA0DD,IAC1D,IAAA,GACAD,CACF,EACO,IACT,CACF,CAQA,SAAgBG,EACd,EACA,EACA,EACM,CACF3B,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7C6B,EAAK,UAAU,MAAM5B,CAAM,CAC7B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-CW-MlHdY.cjs"),t=require("./fixed-window-CvESpFYV.cjs");function n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function r(){return`${String(Date.now())}000000`}function i(t){return typeof t==`string`&&Object.hasOwn(e.mt,t)}function a(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function o(t){let n=e.J;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.Y);return n>>>0}function s(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function c(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={value:i,length:r.length});return n}function l(e,t){return c(e,t.minLevels)?.value??t.minLevel}function u(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,o=c(e,r),s=n?c(e,n.rates):void 0;return s&&s.length>=(o?.length??-1)?Math.min(s.value,a):o?o.value:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function d(t,n){return n>=1?!0:n<=0?!1:o(t)/e.Cn<n}function f(t,n,r){if(t.aggregated===!0||t.type===`span`||t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=u(t.namespace,n,r),a=l(t.namespace,n),o=e.mt[t.level]<e.mt[a];return r&&o&&!e.pt.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),d(t.journeyId||t.traceId,i)}function p(t,n,r=null){return f({level:t.severityText,type:s(t,e.f),namespace:s(t,e.r),journeyId:s(t,e.c),traceId:t.traceId,aggregated:s(t,`log.type`)===`metric`&&s(t,e.Ct.start)!==``},n,r)}var m=class{window={start:0,count:0};allow(n,r=500,i=e.q){return n.severityText!==`ERROR`&&n.severityText!==`FATAL`||r===0||t.t(this.window,r,i)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return n}});
|
|
2
|
-
//# sourceMappingURL=sampling-BVjspJWu.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-BVjspJWu.cjs","names":["LEVEL_ORDER","FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LEVEL_ORDER","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","ERROR_STORM_WINDOW_MS","countInWindow","require_constants","require_fixed_window","isObject","value","nowUnixNano","isLogLevel","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/utils/guards.ts","../src/models/log-record.ts","../src/core/sampling.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","// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\" | \"span\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. Set 0 for no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n ): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return limit === 0 || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":"qFAUA,SAAgBc,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CC8CA,SAAgBC,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOF,GAAU,UAAY,OAAO,OAAOf,EAAAA,GAAae,CAAK,CACtE,CAUA,SAAgBG,EAAY,EAAoC,CAC9D,GAAI,OAAOH,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAMI,EAASJ,EACf,OACE,OAAOI,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA,EAAO,aAAe,MACtB,OAAOA,EAAO,UAAa,UAC3BA,EAAO,WAAa,IAExB,CC/DA,SAASC,EAAK,EAAuB,CACnC,IAAIC,EAAIpB,EAAAA,EAER,IAAK,IAAIqB,EAAI,EAAGA,EAAIP,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWO,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGnB,EAAAA,CAAS,EAG5B,OAAOmB,IAAM,CACf,CASA,SAASE,EAAS,EAAmB,EAAqB,CACxD,IAAMR,EAAiBI,EAAO,WAAWK,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AYuC,GAOzE,OANIP,GAAUQ,GAAiB,CAACvC,EAAAA,GAAmB,SAASqC,EAAM,IAAe,IAC/E,EAAO,KAAK,IAAIF,EAAMT,EAAO,SAAS,aAAa,GAK9CQ,EAAUG,EAAM,WAAaA,EAAM,QAASF,CAAI,CACzD,CAUA,SAAgBK,EACd,EACA,EACA,EAA6B,KACpB,CACT,OAAOJ,EACL,CACE,MAAOtB,EAAO,aACd,KAAMI,EAASJ,EAAQb,EAAAA,CAAa,EACpC,UAAWiB,EAASJ,EAAQZ,EAAAA,CAAkB,EAC9C,UAAWgB,EAASJ,EAAQX,EAAAA,CAAe,EAC3C,QAASW,EAAO,QAChB,WACEI,EAASJ,EAAA,UAAqB,IAAM,UAAYI,EAASJ,EAAQV,EAAAA,GAAY,KAAK,IAAM,EAC5F,EACAsB,EACAK,CACF,CACF,CAQA,IAAaU,EAAb,KAA0B,CAExB,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAS5D,MACE,EACA,EAAA,IACA,EAAWpC,EAAAA,EACF,CAMT,OALIS,EAAO,eAAiB,SAAWA,EAAO,eAAiB,SAKxD4B,IAAU,GAAKpC,EAAAA,EAAc,KAAK,OAAQoC,EAAOC,CAAQ,CAClE,CACF"}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { Cn as e, Ct as t, J as n, Y as r, c as i, f as a, mt as o, pt as s, q as c, r as l } from "./constants-CN7GE1Lt.js";
|
|
2
|
-
import { t as u } from "./fixed-window-CtaFHanJ.js";
|
|
3
|
-
//#region src/utils/guards.ts
|
|
4
|
-
function d(e) {
|
|
5
|
-
return typeof e == "object" && !!e && !Array.isArray(e);
|
|
6
|
-
}
|
|
7
|
-
//#endregion
|
|
8
|
-
//#region src/models/log-record.ts
|
|
9
|
-
function f() {
|
|
10
|
-
return `${String(Date.now())}000000`;
|
|
11
|
-
}
|
|
12
|
-
function p(e) {
|
|
13
|
-
return typeof e == "string" && Object.hasOwn(o, e);
|
|
14
|
-
}
|
|
15
|
-
function m(e) {
|
|
16
|
-
if (typeof e != "object" || !e) return !1;
|
|
17
|
-
let t = e;
|
|
18
|
-
return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/core/sampling.ts
|
|
22
|
-
function h(e) {
|
|
23
|
-
let t = n;
|
|
24
|
-
for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, r);
|
|
25
|
-
return t >>> 0;
|
|
26
|
-
}
|
|
27
|
-
function g(e, t) {
|
|
28
|
-
let n = e.attributes[t];
|
|
29
|
-
return typeof n == "string" ? n : "";
|
|
30
|
-
}
|
|
31
|
-
function _(e, t) {
|
|
32
|
-
let n;
|
|
33
|
-
for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
|
|
34
|
-
value: i,
|
|
35
|
-
length: r.length
|
|
36
|
-
});
|
|
37
|
-
return n;
|
|
38
|
-
}
|
|
39
|
-
function v(e, t) {
|
|
40
|
-
return _(e, t.minLevels)?.value ?? t.minLevel;
|
|
41
|
-
}
|
|
42
|
-
function y(e, t, n) {
|
|
43
|
-
let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = _(e, r), s = n ? _(e, n.rates) : void 0;
|
|
44
|
-
return s && s.length >= (o?.length ?? -1) ? Math.min(s.value, a) : o ? o.value : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
|
|
45
|
-
}
|
|
46
|
-
function b(t, n) {
|
|
47
|
-
return n >= 1 ? !0 : n <= 0 ? !1 : h(t) / e < n;
|
|
48
|
-
}
|
|
49
|
-
function x(e, t, n) {
|
|
50
|
-
if (e.aggregated === !0 || e.type === "span" || e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
|
|
51
|
-
let r = y(e.namespace, t, n), i = v(e.namespace, t), a = o[e.level] < o[i];
|
|
52
|
-
return n && a && !s.includes(e.type) && (r = Math.min(r, t.sampling.remoteMaxRate)), b(e.journeyId || e.traceId, r);
|
|
53
|
-
}
|
|
54
|
-
function S(e, n, r = null) {
|
|
55
|
-
return x({
|
|
56
|
-
level: e.severityText,
|
|
57
|
-
type: g(e, a),
|
|
58
|
-
namespace: g(e, l),
|
|
59
|
-
journeyId: g(e, i),
|
|
60
|
-
traceId: e.traceId,
|
|
61
|
-
aggregated: g(e, "log.type") === "metric" && g(e, t.start) !== ""
|
|
62
|
-
}, n, r);
|
|
63
|
-
}
|
|
64
|
-
var C = class {
|
|
65
|
-
window = {
|
|
66
|
-
start: 0,
|
|
67
|
-
count: 0
|
|
68
|
-
};
|
|
69
|
-
allow(e, t = 500, n = c) {
|
|
70
|
-
return e.severityText !== "ERROR" && e.severityText !== "FATAL" || t === 0 || u(this.window, t, n);
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
//#endregion
|
|
74
|
-
export { S as a, m as c, b as i, f as l, v as n, x as o, _ as r, p as s, C as t, d as u };
|
|
75
|
-
|
|
76
|
-
//# sourceMappingURL=sampling-Cm3WhI0a.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-Cm3WhI0a.js","names":["UINT32_MAX","METRIC_KEYS","FNV_OFFSET_BASIS","FNV_PRIME","ATTR_JOURNEY_ID","ATTR_LOG_TYPE","LEVEL_ORDER","LEVEL_BYPASS_TYPES","ERROR_STORM_WINDOW_MS","ATTR_APP_NAMESPACE","countInWindow","isObject","value","nowUnixNano","isLogLevel","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling","limit","windowMs"],"sources":["../src/utils/guards.ts","../src/models/log-record.ts","../src/core/sampling.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","// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\" | \"span\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @param limit Maximum records in one window. Set 0 for no limit.\n * @param windowMs Rate limit window, in milliseconds.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(\n record: LogRecord,\n limit = ERROR_CEILING_MAX_PER_WINDOW,\n windowMs = ERROR_STORM_WINDOW_MS,\n ): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return limit === 0 || countInWindow(this.window, limit, windowMs);\n }\n}\n"],"mappings":";;;AAUA,SAAgBW,EAAS,GAAkD;CACzE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;;;AC8CA,SAAgBC,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAOA,SAAgBC,EAAW,GAAmC;CAC5D,OAAO,OAAOF,KAAU,YAAY,OAAO,OAAON,GAAaM,CAAK;AACtE;AAUA,SAAgBG,EAAY,GAAoC;CAC9D,IAAI,OAAOH,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAMI,IAASJ;CACf,OACE,OAAOI,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AC/DA,SAASC,EAAK,GAAuB;CACnC,IAAIC,IAAIhB;CAER,KAAK,IAAIiB,IAAI,GAAGA,IAAIP,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWO,CAAC,GACvB,IAAI,KAAK,KAAKD,GAAGf,CAAS;CAG5B,OAAOe,MAAM;AACf;AASA,SAASE,EAAS,GAAmB,GAAqB;CACxD,IAAMR,IAAiBI,EAAO,WAAWK;CACzC,OAAO,OAAOT,KAAU,WAAWA,IAAQ;AAC7C;AAiBA,SAAgBU,EACd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