observability-toolkit-hooks 1.0.0 → 1.0.3
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/LICENSE +95 -0
- package/dist/hook-runner.js +1 -1
- package/dist/lib/core/config-dir-recovery.js +2 -2
- package/dist/lib/core/constants.js +3 -1
- package/dist/lib/core/load-envrc.js +3 -4
- package/dist/runner/{agent-context-4XTCLMLZ.js → agent-context-4HKRF6ZJ.js} +4 -4
- package/dist/runner/{agent-file-budget-Q33ESBBE.js → agent-file-budget-MGYZEBEW.js} +3 -3
- package/dist/runner/{agent-transcript-metrics-W5CZZFMI.js → agent-transcript-metrics-56XNPBWS.js} +5 -5
- package/dist/runner/{chunk-UW3GQZSM.js → chunk-2PQCUHOU.js} +3 -3
- package/dist/runner/{chunk-DGB4NSSD.js → chunk-2XKE4E7E.js} +6 -6
- package/dist/runner/{chunk-LHWRXY2G.js → chunk-2YXDQERF.js} +3 -3
- package/dist/runner/{chunk-4KWBQTTG.js → chunk-34O6HVAQ.js} +2 -2
- package/dist/runner/{chunk-M4R4QIQH.js → chunk-3DZNNATE.js} +2 -2
- package/dist/runner/{chunk-XSO3B4QN.js → chunk-3IC2KNJ4.js} +3 -3
- package/dist/runner/{chunk-LYY6RCIE.js → chunk-5GJLO6EX.js} +3 -3
- package/dist/runner/{chunk-C3WHUMU5.js → chunk-67K2WTSP.js} +6 -6
- package/dist/runner/{chunk-IY7AP7NA.js → chunk-6QFGAAUD.js} +3 -3
- package/dist/runner/{chunk-AGSGKELQ.js → chunk-6RSOKWNG.js} +4 -4
- package/dist/runner/{chunk-YGFN3LN2.js → chunk-BOZSNQGU.js} +2 -2
- package/dist/runner/{chunk-WU7ANGCW.js → chunk-C3NW5R45.js} +4 -4
- package/dist/runner/{chunk-2NTNAJZE.js → chunk-D626UD7P.js} +3 -3
- package/dist/runner/{chunk-GG2I4TGI.js → chunk-E3YCQK2D.js} +12 -27
- package/dist/runner/{chunk-GG2I4TGI.js.map → chunk-E3YCQK2D.js.map} +4 -4
- package/dist/runner/{chunk-PJHWHJ3K.js → chunk-EAA5QNOB.js} +4 -4
- package/dist/runner/{chunk-MC75VXMX.js → chunk-EZL3KMMB.js} +5 -5
- package/dist/runner/{chunk-LBCZAYFR.js → chunk-H4M6YEDJ.js} +3 -3
- package/dist/runner/{chunk-VVGOPPEN.js → chunk-JJHQOX5Q.js} +3 -3
- package/dist/runner/{chunk-DNSTWC26.js → chunk-LFCMGDJC.js} +2 -2
- package/dist/runner/{chunk-KGSA5JYP.js → chunk-LK6UFBC5.js} +3 -3
- package/dist/runner/{chunk-52RY6LQT.js → chunk-N6435YLW.js} +26 -9
- package/dist/runner/chunk-N6435YLW.js.map +7 -0
- package/dist/runner/{chunk-JRNNLOPR.js → chunk-OJWQCABS.js} +4 -4
- package/dist/runner/{chunk-VOV4Y5VU.js → chunk-OWXBKC5K.js} +6 -6
- package/dist/runner/{chunk-WJHNCOUF.js → chunk-PPDN7VWX.js} +3 -3
- package/dist/runner/{chunk-7OM5CYES.js → chunk-QD52DSVB.js} +7 -9
- package/dist/runner/chunk-QD52DSVB.js.map +7 -0
- package/dist/runner/{chunk-FDJJ3TYU.js → chunk-QESRH3ED.js} +7 -7
- package/dist/runner/{chunk-UEXDE3WP.js → chunk-S2B2J6ZB.js} +5 -5
- package/dist/runner/{chunk-LQ2LGUYJ.js → chunk-SA4ZNI3N.js} +2 -2
- package/dist/runner/{chunk-I7TD2QVR.js → chunk-SGL5GFKY.js} +3 -3
- package/dist/runner/{chunk-X7XLMSZX.js → chunk-VAX5JACX.js} +2 -2
- package/dist/runner/{chunk-NKZU4RRG.js → chunk-WVVJE7ZI.js} +2 -2
- package/dist/runner/{chunk-RIGVYJ2O.js → chunk-XFKV6REH.js} +4 -4
- package/dist/runner/{chunk-TRMFD36J.js → chunk-XYINMMHR.js} +3 -3
- package/dist/runner/{chunk-J3F3Z3EQ.js → chunk-YDN63WUY.js} +5 -5
- package/dist/runner/{chunk-V2GSP6VR.js → chunk-YZDEUJOZ.js} +3 -3
- package/dist/runner/{chunk-SRMAJQMV.js → chunk-ZCZUJKZD.js} +2 -2
- package/dist/runner/{chunk-VT5T6OEI.js → chunk-ZEYUSIMT.js} +3 -3
- package/dist/runner/{chunk-FGKYDQHZ.js → chunk-ZHCBXQ5O.js} +6 -6
- package/dist/runner/{compact-36NP3PKT.js → compact-PH4S4MIT.js} +7 -7
- package/dist/runner/{git-commit-BA53DOJQ.js → git-commit-67MX3SQY.js} +7 -7
- package/dist/runner/{hook-runner-JHH6PGKE.js → hook-runner-O345UBIB.js} +25 -26
- package/dist/runner/{hook-runner-JHH6PGKE.js.map → hook-runner-O345UBIB.js.map} +1 -1
- package/dist/runner/{mcp-status-QEUH2KGX.js → mcp-status-XWMUEEAB.js} +11 -11
- package/dist/runner/{notification-FKMBCSXF.js → notification-3WY33IIL.js} +8 -8
- package/dist/runner/{post-tool-3MRHTBKH.js → post-tool-AIQSU3VH.js} +28 -28
- package/dist/runner/{post-tool-agent-BB34MNHI.js → post-tool-agent-O3U4FP2R.js} +15 -15
- package/dist/runner/{post-tool-changelog-sync-OP2TT2I7.js → post-tool-changelog-sync-EZSRRRDR.js} +9 -9
- package/dist/runner/{post-tool-code-structure-LE7J2SC2.js → post-tool-code-structure-TERICHXZ.js} +9 -9
- package/dist/runner/{post-tool-edit-ledger-IJMEYHKF.js → post-tool-edit-ledger-B7QKW2UY.js} +7 -7
- package/dist/runner/{post-tool-failure-XTH2I2Z7.js → post-tool-failure-GDKD57FZ.js} +15 -15
- package/dist/runner/{post-tool-git-E46HZGZO.js → post-tool-git-GGHJFPBQ.js} +11 -11
- package/dist/runner/{post-tool-mcp-AMCDY5GH.js → post-tool-mcp-GH7MQJHG.js} +15 -15
- package/dist/runner/{post-tool-task-state-TLDOI33H.js → post-tool-task-state-PNE63AUM.js} +10 -10
- package/dist/runner/{pre-tool-SQE2FZQO.js → pre-tool-6UBCNWIJ.js} +18 -18
- package/dist/runner/{pre-tool-agent-OZUPVFUI.js → pre-tool-agent-CBX55CM6.js} +16 -16
- package/dist/runner/{quality-evaluator-XYNDKDRG.js → quality-evaluator-SPT3LTR6.js} +19 -19
- package/dist/runner/{session-end-3MJTDLLA.js → session-end-NQ7HY5C2.js} +10 -10
- package/dist/runner/{session-start-5ZMCLKBS.js → session-start-EPMNSIX6.js} +18 -18
- package/dist/runner/{shipper-status-MADX6SPG.js → shipper-status-FLIPBYTK.js} +3 -3
- package/dist/runner/{span-shipper-4HQDHC47.js → span-shipper-H6XGJPUR.js} +7 -7
- package/dist/runner/{stop-RTKSIYJV.js → stop-3WZ3HHMG.js} +24 -24
- package/dist/runner/{subagent-CBCG4OLZ.js → subagent-GU56QFXI.js} +12 -12
- package/dist/runner/{token-metrics-AD2RAFGM.js → token-metrics-3KQXGOYX.js} +10 -10
- package/dist/runner/{user-prompt-T5NZ2UJD.js → user-prompt-RV3N24AN.js} +15 -15
- package/package.json +4 -2
- package/dist/runner/chunk-52RY6LQT.js.map +0 -7
- package/dist/runner/chunk-7OM5CYES.js.map +0 -7
- /package/dist/runner/{agent-context-4XTCLMLZ.js.map → agent-context-4HKRF6ZJ.js.map} +0 -0
- /package/dist/runner/{agent-file-budget-Q33ESBBE.js.map → agent-file-budget-MGYZEBEW.js.map} +0 -0
- /package/dist/runner/{agent-transcript-metrics-W5CZZFMI.js.map → agent-transcript-metrics-56XNPBWS.js.map} +0 -0
- /package/dist/runner/{chunk-UW3GQZSM.js.map → chunk-2PQCUHOU.js.map} +0 -0
- /package/dist/runner/{chunk-DGB4NSSD.js.map → chunk-2XKE4E7E.js.map} +0 -0
- /package/dist/runner/{chunk-LHWRXY2G.js.map → chunk-2YXDQERF.js.map} +0 -0
- /package/dist/runner/{chunk-4KWBQTTG.js.map → chunk-34O6HVAQ.js.map} +0 -0
- /package/dist/runner/{chunk-M4R4QIQH.js.map → chunk-3DZNNATE.js.map} +0 -0
- /package/dist/runner/{chunk-XSO3B4QN.js.map → chunk-3IC2KNJ4.js.map} +0 -0
- /package/dist/runner/{chunk-LYY6RCIE.js.map → chunk-5GJLO6EX.js.map} +0 -0
- /package/dist/runner/{chunk-C3WHUMU5.js.map → chunk-67K2WTSP.js.map} +0 -0
- /package/dist/runner/{chunk-IY7AP7NA.js.map → chunk-6QFGAAUD.js.map} +0 -0
- /package/dist/runner/{chunk-AGSGKELQ.js.map → chunk-6RSOKWNG.js.map} +0 -0
- /package/dist/runner/{chunk-YGFN3LN2.js.map → chunk-BOZSNQGU.js.map} +0 -0
- /package/dist/runner/{chunk-WU7ANGCW.js.map → chunk-C3NW5R45.js.map} +0 -0
- /package/dist/runner/{chunk-2NTNAJZE.js.map → chunk-D626UD7P.js.map} +0 -0
- /package/dist/runner/{chunk-PJHWHJ3K.js.map → chunk-EAA5QNOB.js.map} +0 -0
- /package/dist/runner/{chunk-MC75VXMX.js.map → chunk-EZL3KMMB.js.map} +0 -0
- /package/dist/runner/{chunk-LBCZAYFR.js.map → chunk-H4M6YEDJ.js.map} +0 -0
- /package/dist/runner/{chunk-VVGOPPEN.js.map → chunk-JJHQOX5Q.js.map} +0 -0
- /package/dist/runner/{chunk-DNSTWC26.js.map → chunk-LFCMGDJC.js.map} +0 -0
- /package/dist/runner/{chunk-KGSA5JYP.js.map → chunk-LK6UFBC5.js.map} +0 -0
- /package/dist/runner/{chunk-JRNNLOPR.js.map → chunk-OJWQCABS.js.map} +0 -0
- /package/dist/runner/{chunk-VOV4Y5VU.js.map → chunk-OWXBKC5K.js.map} +0 -0
- /package/dist/runner/{chunk-WJHNCOUF.js.map → chunk-PPDN7VWX.js.map} +0 -0
- /package/dist/runner/{chunk-FDJJ3TYU.js.map → chunk-QESRH3ED.js.map} +0 -0
- /package/dist/runner/{chunk-UEXDE3WP.js.map → chunk-S2B2J6ZB.js.map} +0 -0
- /package/dist/runner/{chunk-LQ2LGUYJ.js.map → chunk-SA4ZNI3N.js.map} +0 -0
- /package/dist/runner/{chunk-I7TD2QVR.js.map → chunk-SGL5GFKY.js.map} +0 -0
- /package/dist/runner/{chunk-X7XLMSZX.js.map → chunk-VAX5JACX.js.map} +0 -0
- /package/dist/runner/{chunk-NKZU4RRG.js.map → chunk-WVVJE7ZI.js.map} +0 -0
- /package/dist/runner/{chunk-RIGVYJ2O.js.map → chunk-XFKV6REH.js.map} +0 -0
- /package/dist/runner/{chunk-TRMFD36J.js.map → chunk-XYINMMHR.js.map} +0 -0
- /package/dist/runner/{chunk-J3F3Z3EQ.js.map → chunk-YDN63WUY.js.map} +0 -0
- /package/dist/runner/{chunk-V2GSP6VR.js.map → chunk-YZDEUJOZ.js.map} +0 -0
- /package/dist/runner/{chunk-SRMAJQMV.js.map → chunk-ZCZUJKZD.js.map} +0 -0
- /package/dist/runner/{chunk-VT5T6OEI.js.map → chunk-ZEYUSIMT.js.map} +0 -0
- /package/dist/runner/{chunk-FGKYDQHZ.js.map → chunk-ZHCBXQ5O.js.map} +0 -0
- /package/dist/runner/{compact-36NP3PKT.js.map → compact-PH4S4MIT.js.map} +0 -0
- /package/dist/runner/{git-commit-BA53DOJQ.js.map → git-commit-67MX3SQY.js.map} +0 -0
- /package/dist/runner/{mcp-status-QEUH2KGX.js.map → mcp-status-XWMUEEAB.js.map} +0 -0
- /package/dist/runner/{notification-FKMBCSXF.js.map → notification-3WY33IIL.js.map} +0 -0
- /package/dist/runner/{post-tool-3MRHTBKH.js.map → post-tool-AIQSU3VH.js.map} +0 -0
- /package/dist/runner/{post-tool-agent-BB34MNHI.js.map → post-tool-agent-O3U4FP2R.js.map} +0 -0
- /package/dist/runner/{post-tool-changelog-sync-OP2TT2I7.js.map → post-tool-changelog-sync-EZSRRRDR.js.map} +0 -0
- /package/dist/runner/{post-tool-code-structure-LE7J2SC2.js.map → post-tool-code-structure-TERICHXZ.js.map} +0 -0
- /package/dist/runner/{post-tool-edit-ledger-IJMEYHKF.js.map → post-tool-edit-ledger-B7QKW2UY.js.map} +0 -0
- /package/dist/runner/{post-tool-failure-XTH2I2Z7.js.map → post-tool-failure-GDKD57FZ.js.map} +0 -0
- /package/dist/runner/{post-tool-git-E46HZGZO.js.map → post-tool-git-GGHJFPBQ.js.map} +0 -0
- /package/dist/runner/{post-tool-mcp-AMCDY5GH.js.map → post-tool-mcp-GH7MQJHG.js.map} +0 -0
- /package/dist/runner/{post-tool-task-state-TLDOI33H.js.map → post-tool-task-state-PNE63AUM.js.map} +0 -0
- /package/dist/runner/{pre-tool-SQE2FZQO.js.map → pre-tool-6UBCNWIJ.js.map} +0 -0
- /package/dist/runner/{pre-tool-agent-OZUPVFUI.js.map → pre-tool-agent-CBX55CM6.js.map} +0 -0
- /package/dist/runner/{quality-evaluator-XYNDKDRG.js.map → quality-evaluator-SPT3LTR6.js.map} +0 -0
- /package/dist/runner/{session-end-3MJTDLLA.js.map → session-end-NQ7HY5C2.js.map} +0 -0
- /package/dist/runner/{session-start-5ZMCLKBS.js.map → session-start-EPMNSIX6.js.map} +0 -0
- /package/dist/runner/{shipper-status-MADX6SPG.js.map → shipper-status-FLIPBYTK.js.map} +0 -0
- /package/dist/runner/{span-shipper-4HQDHC47.js.map → span-shipper-H6XGJPUR.js.map} +0 -0
- /package/dist/runner/{stop-RTKSIYJV.js.map → stop-3WZ3HHMG.js.map} +0 -0
- /package/dist/runner/{subagent-CBCG4OLZ.js.map → subagent-GU56QFXI.js.map} +0 -0
- /package/dist/runner/{token-metrics-AD2RAFGM.js.map → token-metrics-3KQXGOYX.js.map} +0 -0
- /package/dist/runner/{user-prompt-T5NZ2UJD.js.map → user-prompt-RV3N24AN.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts", "../../../node_modules/@opentelemetry/core/src/baggage/constants.ts", "../../../node_modules/@opentelemetry/core/src/baggage/utils.ts", "../../../node_modules/@opentelemetry/core/src/baggage/propagation/W3CBaggagePropagator.ts", "../../../node_modules/@opentelemetry/core/src/common/anchored-clock.ts", "../../../node_modules/@opentelemetry/core/src/common/attributes.ts", "../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts", "../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts", "../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts", "../../../node_modules/@opentelemetry/core/src/common/globalThis.ts", "../../../node_modules/@opentelemetry/core/src/version.ts", "../../../node_modules/@opentelemetry/core/src/semconv.ts", "../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts", "../../../node_modules/@opentelemetry/core/src/platform/node/index.ts", "../../../node_modules/@opentelemetry/core/src/platform/index.ts", "../../../node_modules/@opentelemetry/core/src/common/time.ts", "../../../node_modules/@opentelemetry/core/src/common/timer-util.ts", "../../../node_modules/@opentelemetry/core/src/ExportResult.ts", "../../../node_modules/@opentelemetry/core/src/propagation/composite.ts", "../../../node_modules/@opentelemetry/core/src/internal/validators.ts", "../../../node_modules/@opentelemetry/core/src/trace/TraceState.ts", "../../../node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts", "../../../node_modules/@opentelemetry/core/src/trace/rpc-metadata.ts", "../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts", "../../../node_modules/@opentelemetry/core/src/utils/merge.ts", "../../../node_modules/@opentelemetry/core/src/utils/timeout.ts", "../../../node_modules/@opentelemetry/core/src/utils/url.ts", "../../../node_modules/@opentelemetry/core/src/utils/promise.ts", "../../../node_modules/@opentelemetry/core/src/utils/callback.ts", "../../../node_modules/@opentelemetry/core/src/utils/configuration.ts", "../../../node_modules/@opentelemetry/core/src/internal/exporter.ts", "../../../node_modules/@opentelemetry/core/src/index.ts", "../../../node_modules/@opentelemetry/resources/src/default-service-name.ts", "../../../node_modules/@opentelemetry/resources/src/utils.ts", "../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts", "../../../node_modules/@opentelemetry/resources/src/detect-resources.ts", "../../../node_modules/@opentelemetry/resources/src/semconv.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/platform/node/machine-id/getMachineId.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/platform/node/utils.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/platform/node/HostDetector.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/platform/node/index.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/platform/index.ts", "../../../node_modules/@opentelemetry/resources/src/detectors/index.ts", "../../../node_modules/@opentelemetry/resources/src/index.ts", "../../../node_modules/@opentelemetry/context-async-hooks/src/AbstractAsyncHooksContextManager.ts", "../../../node_modules/@opentelemetry/context-async-hooks/src/AsyncHooksContextManager.ts", "../../../node_modules/@opentelemetry/context-async-hooks/src/AsyncLocalStorageContextManager.ts", "../../../node_modules/@opentelemetry/context-async-hooks/src/index.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/enums.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/inspect.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/Span.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/Sampler.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/semconv.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/TracerMetrics.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/version.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/Tracer.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/MultiSpanProcessor.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/sampler/AlwaysOffSampler.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/sampler/AlwaysOnSampler.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/sampler/ParentBasedSampler.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/SpanProcessorMetrics.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/BatchSpanProcessorBase.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/platform/node/export/BatchSpanProcessor.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/platform/node/RandomIdGenerator.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/platform/node/index.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/platform/index.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/TracerProvider.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/ConsoleSpanExporter.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/InMemorySpanExporter.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/SimpleSpanProcessor.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/export/NoopSpanProcessor.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/sampler/TraceIdRatioBasedSampler.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/sdk-trace/src/index.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider-shim.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/BatchSpanProcessor-shim.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/SimpleSpanProcessor-shim.ts", "../../../node_modules/@opentelemetry/sdk-trace-base/src/index-shim.ts", "../../../node_modules/@opentelemetry/sdk-trace-node/src/NodeTracerProvider.ts", "../../../node_modules/@opentelemetry/sdk-trace-node/src/index.ts", "../../../lib/otel/attributes.ts", "../../../lib/core/load-envrc.ts", "../../../lib/otel/otel.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/LoggerProvider.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources/src/ResourceImpl.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/common/global-error-handler.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/version.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/semconv.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/platform/node/index.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/common/time.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/ExportResult.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/utils/timeout.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/utils/promise.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/utils/callback.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/internal/exporter.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core/src/index.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources/src/default-service-name.ts", "../../../node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources/src/utils.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/Logger.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/LogRecordImpl.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/utils/validation.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/internal/LoggerProviderSharedState.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/export/NoopLogRecordProcessor.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/MultiLogRecordProcessor.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/internal/utils.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/semconv.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/LoggerMetrics.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/version.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/export/SimpleLogRecordProcessor.ts", "../../../node_modules/@opentelemetry/sdk-logs/src/export/LogRecordProcessorMetrics.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/AggregationTemporality.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/MetricData.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/MetricReader.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/utils.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/Aggregation.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/types.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/Drop.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/Histogram.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/ExponentialHistogram.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/Buckets.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/mapping/ieee754.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/util.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/mapping/types.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/mapping/ExponentMapping.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/mapping/LogarithmMapping.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/exponential-histogram/mapping/getMapping.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/LastValue.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/aggregator/Sum.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/AggregationOption.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/AggregationSelector.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/semconv.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/MetricReaderMetrics.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/version.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/PeriodicExportingMetricReader.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/export/MetricDataSplitter.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/MeterProvider.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/ViewRegistry.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/InstrumentDescriptor.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/Instruments.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/Meter.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MetricStorage.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/DeltaMetricProcessor.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/HashMap.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/TemporalMetricProcessor.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/AsyncMetricStorage.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MetricStorageRegistry.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/RegistrationConflicts.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MultiWritableMetricStorage.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/ObservableRegistry.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/ObservableResult.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/SyncMetricStorage.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MeterSharedState.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MeterProviderSharedState.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/state/MetricCollector.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/Predicate.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/AttributesProcessor.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/InstrumentSelector.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/MeterSelector.ts", "../../../node_modules/@opentelemetry/sdk-metrics/src/view/View.ts", "../../../lib/otel/file-exporters.ts", "../../../lib/otel/host-resource.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Baggage,\n BaggageEntry,\n BaggageEntryMetadata,\n} from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n if (!entry) return;\n const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n const keyPairPart =\n metadataSeparatorIndex === -1\n ? entry\n : entry.substring(0, metadataSeparatorIndex);\n\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n\n const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n if (!rawKey || !rawValue) return;\n let key: string;\n let value: string;\n try {\n key = decodeURIComponent(rawKey);\n value = decodeURIComponent(rawValue);\n } catch {\n return;\n }\n\n let metadata;\n if (\n metadataSeparatorIndex !== -1 &&\n metadataSeparatorIndex < entry.length - 1\n ) {\n const metadataString = entry.substring(metadataSeparatorIndex + 1);\n metadata = baggageEntryMetadataFromString(metadataString);\n }\n\n return { key, value, metadata };\n}\n\n/**\n * Parses a single baggage header string into the provided record, applying limits defined in this package.\n * Uses indexOf/substring in a while loop to avoid allocating a full array of split entries.\n * Returns the updated pair count so callers can track totals across multiple header values.\n */\nexport function parseBaggageHeaderString(\n value: string,\n baggage: Record<string, BaggageEntry>,\n count: number,\n totalSize: number\n): [count: number, totalSize: number] {\n let start = 0;\n while (start < value.length && count < BAGGAGE_MAX_NAME_VALUE_PAIRS) {\n const end = value.indexOf(BAGGAGE_ITEMS_SEPARATOR, start);\n const entryEnd = end === -1 ? value.length : end;\n const entryLength = entryEnd - start;\n\n if (entryLength <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS) {\n const keyPair = parsePairKeyValue(value.substring(start, entryEnd));\n if (keyPair) {\n // Comma separator is counted for every accepted entry after the first\n const entrySize = (count === 0 ? 0 : 1) + entryLength;\n if (totalSize + entrySize > BAGGAGE_MAX_TOTAL_LENGTH) break;\n baggage[keyPair.key] = keyPair.metadata\n ? { value: keyPair.value, metadata: keyPair.metadata }\n : { value: keyPair.value };\n count++;\n totalSize += entrySize;\n }\n }\n\n if (end === -1) break;\n start = end + 1;\n }\n return [count, totalSize];\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (typeof value === 'string' && value.length > 0) {\n value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n\n if (keyPair !== undefined && keyPair.value.length > 0) {\n result[keyPair.key] = keyPair.value;\n }\n });\n }\n\n return result;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n BaggageEntry,\n Context,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\nimport { propagation } from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport {\n getKeyPairs,\n parseBaggageHeaderString,\n serializeKeyPairs,\n} from '../utils';\n\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nexport class W3CBaggagePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const baggage = propagation.getBaggage(context);\n if (!baggage || isTracingSuppressed(context)) return;\n const keyPairs = getKeyPairs(baggage)\n .filter((pair: string) => {\n return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = serializeKeyPairs(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, BAGGAGE_HEADER, headerValue);\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const headerValue = getter.get(carrier, BAGGAGE_HEADER);\n if (!headerValue) {\n return context;\n }\n\n const baggage: Record<string, BaggageEntry> = {};\n let count = 0;\n\n let totalSize = 0;\n if (Array.isArray(headerValue)) {\n for (let i = 0; i < headerValue.length; i++) {\n [count, totalSize] = parseBaggageHeaderString(\n headerValue[i],\n baggage,\n count,\n totalSize\n );\n }\n } else {\n [count] = parseBaggageHeaderString(\n headerValue,\n baggage,\n count,\n totalSize\n );\n }\n\n if (count === 0) {\n return context;\n }\n\n return propagation.setBaggage(context, propagation.createBaggage(baggage));\n }\n\n fields(): string[] {\n return [BAGGAGE_HEADER];\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface Clock {\n /**\n * Return the current time in milliseconds from some epoch such as the Unix epoch or process start\n */\n now(): number;\n}\n\n/**\n * A utility for returning wall times anchored to a given point in time. Wall time measurements will\n * not be taken from the system, but instead are computed by adding a monotonic clock time\n * to the anchor point.\n *\n * This is needed because the system time can change and result in unexpected situations like\n * spans ending before they are started. Creating an anchored clock for each local root span\n * ensures that span timings and durations are accurate while preventing span times from drifting\n * too far from the system clock.\n *\n * Only creating an anchored clock once per local trace ensures span times are correct relative\n * to each other. For example, a child span will never have a start time before its parent even\n * if the system clock is corrected during the local trace.\n *\n * Heavily inspired by the OTel Java anchored clock\n * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java\n */\nexport class AnchoredClock implements Clock {\n private _monotonicClock: Clock;\n private _epochMillis: number;\n private _performanceMillis: number;\n\n /**\n * Create a new AnchoredClock anchored to the current time returned by systemClock.\n *\n * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date\n * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance\n */\n public constructor(systemClock: Clock, monotonicClock: Clock) {\n this._monotonicClock = monotonicClock;\n this._epochMillis = systemClock.now();\n this._performanceMillis = monotonicClock.now();\n }\n\n /**\n * Returns the current time by adding the number of milliseconds since the\n * AnchoredClock was created to the creation epoch time\n */\n public now(): number {\n const delta = this._monotonicClock.now() - this._performanceMillis;\n return this._epochMillis + delta;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n const out: Attributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = (attributes as Record<string, unknown>)[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n const elementType = typeof element;\n\n if (elementType === type) {\n continue;\n }\n\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n );\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n } else if (raw === 'false') {\n return false;\n } else {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n );\n return false;\n }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @deprecated Use globalThis directly instead.\n */\nexport const _globalThis = globalThis;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.12.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport {\n SDK_INFO,\n _globalThis,\n otperformance,\n getBooleanFromEnv,\n getStringFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './node';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Distinguish between a relative performance.now() value and an absolute\n // epoch-millisecond timestamp.\n //\n // performance.timeOrigin uses a monotonic clock that may be slightly ahead\n // of Date.now() due to clock adjustments (see MDN docs). This means a\n // real epoch-ms value (e.g. Date.now()) can land just below\n // performance.timeOrigin, causing it to be misclassified as a relative\n // performance.now() reading and doubled when timeOrigin is added.\n //\n // A genuine performance.now() value represents elapsed time since the\n // document/process started, so it is bounded by system uptime. No real\n // system has been running long enough for performance.now() to reach half\n // the current epoch time (~1994 in ms terms). We therefore treat any value\n // below half of performance.timeOrigin as a relative performance.now()\n // reading, and everything else as an absolute epoch-millisecond timestamp.\n if (time < performance.timeOrigin / 2) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @deprecated please copy this code to your implementation instead, this function will be removed in the next major version of this package.\n * @param timer\n */\nexport function unrefTimer(timer: { unref(): unknown } | number): void {\n if (typeof timer !== 'number') {\n timer.unref();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n const fields = new Set<string>();\n for (const propagator of this._propagators) {\n // older propagators may not have fields function, null check to be sure\n const propagatorFields =\n typeof propagator.fields === 'function' ? propagator.fields() : [];\n for (const field of propagatorFields) {\n fields.add(field);\n }\n }\n this._fields = Array.from(fields);\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TraceState as TraceStateApi } from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements TraceStateApi {\n private _length: number;\n private _rawTraceState: string;\n private _internalState: Map<string, string> | undefined;\n\n constructor(rawTraceState?: string) {\n this._rawTraceState =\n typeof rawTraceState === 'string' ? rawTraceState : '';\n this._length = this._rawTraceState.length;\n }\n\n set(key: string, value: string): TraceState {\n if (!validateKey(key) || !validateValue(value)) {\n return this;\n }\n\n const currState = this._getState();\n const currValue = currState.get(key);\n // Get the new length depending if we already have a value or not\n // - for existing keys we add the difference between the length of the values\n // - for new keys is the key & value lenght plus\n // - +1 for the key/value splitter\n // - +1 for the separator if there are other keys\n let newLength = this._length;\n if (typeof currValue === 'string') {\n newLength += value.length - currValue.length;\n } else {\n newLength += key.length + value.length + (currState.size > 0 ? 2 : 1);\n }\n if (newLength > MAX_TRACE_STATE_LEN) {\n return this;\n }\n\n const newState = new Map(currState);\n newState.delete(key);\n newState.set(key, value);\n return this._fromState(newState, newLength);\n }\n\n unset(key: string): TraceState {\n const currState = this._getState();\n const currValue = currState.get(key);\n\n // No need to create a new instance if the key does not exist\n if (typeof currValue !== 'string') {\n return this;\n }\n\n // Get the new length depending if we already have a value or not\n // - for existing keys we substract key and value length plus\n // - +1 for the key/value splitter\n // - +1 for the separator if there are other keys\n let newLength = this._length - (key.length + currValue.length + 1);\n if (currState.size > 1) {\n // remove separator from length if there's no key or only one.\n newLength = newLength - 1;\n }\n\n const newState = new Map(currState);\n newState.delete(key);\n return this._fromState(newState, newLength);\n }\n\n get(key: string): string | undefined {\n const currState = this._getState();\n return currState.get(key);\n }\n\n serialize(): string {\n // Maps put new entries at the end. We prepend the seralized entry\n // to get the right order according to the spec (updated members go 1st)\n let serialized = '';\n let index = 0;\n for (const entry of this._getState()) {\n if (index > 0) {\n serialized = LIST_MEMBERS_SEPARATOR + serialized;\n }\n serialized =\n `${entry[0]}${LIST_MEMBER_KEY_VALUE_SPLITTER}${entry[1]}` + serialized;\n index++;\n }\n return serialized;\n }\n\n private _getState(): Map<string, string> {\n if (this._internalState) {\n return this._internalState;\n }\n\n // Not parsed yet, lets do it\n const vendorMembers = this._rawTraceState.split(LIST_MEMBERS_SEPARATOR);\n\n // This Map will have the order reversed\n const vendorEntries = new Map();\n let currentLength = 0;\n\n for (const member of vendorMembers) {\n const m = member.trim();\n const idx = m.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (idx === -1) {\n continue;\n }\n\n const key = m.slice(0, idx);\n const value = m.slice(idx + 1);\n if (!validateKey(key) || !validateValue(value)) {\n continue;\n }\n\n // Skip if adding the new member exceeds the length\n const futureLength =\n currentLength + m.length + (vendorEntries.size > 0 ? 1 : 0);\n if (futureLength > MAX_TRACE_STATE_LEN) {\n continue;\n }\n\n // All good, add it\n vendorEntries.set(key, value);\n currentLength = futureLength;\n\n // Check if we reached the max items\n if (vendorEntries.size >= MAX_TRACE_STATE_ITEMS) {\n break;\n }\n }\n\n // Now we set the length & the Map in the right order\n this._length = currentLength;\n this._internalState = new Map(\n Array.from(vendorEntries.entries()).reverse()\n );\n return this._internalState;\n }\n\n private _fromState(state: Map<string, string>, length: number): TraceState {\n const traceState = Object.create(TraceState.prototype) as TraceState;\n traceState._internalState = state;\n traceState._length = length;\n return traceState;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\nimport { isSpanContextValid, trace, TraceFlags } from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Span } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst RPC_METADATA_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key RPC_METADATA'\n);\n\nexport enum RPCType {\n HTTP = 'http',\n}\n\ntype HTTPMetadata = {\n type: RPCType.HTTP;\n route?: string;\n span: Span;\n};\n\n/**\n * Allows for future rpc metadata to be used with this mechanism\n */\nexport type RPCMetadata = HTTPMetadata;\n\nexport function setRPCMetadata(context: Context, meta: RPCMetadata): Context {\n return context.setValue(RPC_METADATA_KEY, meta);\n}\n\nexport function deleteRPCMetadata(context: Context): Context {\n return context.deleteValue(RPC_METADATA_KEY);\n}\n\nexport function getRPCMetadata(context: Context): RPCMetadata | undefined {\n return context.getValue(RPC_METADATA_KEY) as RPCMetadata | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n continue;\n }\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n continue;\n }\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport function urlMatches(url: string, urlToMatch: string | RegExp): boolean {\n if (typeof urlToMatch === 'string') {\n return url === urlToMatch;\n } else {\n return !!url.match(urlToMatch);\n }\n}\n/**\n * Check if {@param url} should be ignored when comparing against {@param ignoredUrls}\n * @param url\n * @param ignoredUrls\n */\nexport function isUrlIgnored(\n url: string,\n ignoredUrls?: Array<string | RegExp>\n): boolean {\n if (!ignoredUrls) {\n return false;\n }\n\n for (const ignoreUrl of ignoredUrls) {\n if (urlMatches(url, ignoreUrl)) {\n return true;\n }\n }\n return false;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag, DiagLogLevel } from '@opentelemetry/api';\n\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Convert a string to a {@link DiagLogLevel}, defaults to {@link DiagLogLevel} if the log level does not exist or undefined if the input is undefined.\n * @param value\n */\nexport function diagLogLevelFromString(\n value: string | undefined\n): DiagLogLevel | undefined {\n if (value == null) {\n // don't fall back to default - no value set has different semantics for ús than an incorrect value (do not set vs. fall back to default)\n return undefined;\n }\n\n const resolvedLogLevel = logLevelMap[value.toUpperCase()];\n\n if (resolvedLogLevel == null) {\n diag.warn(\n `Unknown log level \"${value}\", expected one of ${Object.keys(logLevelMap)}, using default`\n );\n return DiagLogLevel.INFO;\n }\n\n return resolvedLogLevel;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { context } from '@opentelemetry/api';\nimport type { ExportResult } from '../ExportResult';\nimport { suppressTracing } from '../trace/suppress-tracing';\n\nexport interface Exporter<T> {\n export(arg: T, resultCallback: (result: ExportResult) => void): void;\n}\n\n/**\n * @internal\n * Shared functionality used by Exporters while exporting data, including suppression of Traces.\n */\nexport function _export<T>(\n exporter: Exporter<T>,\n arg: T\n): Promise<ExportResult> {\n return new Promise(resolve => {\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n exporter.export(arg, resolve);\n });\n });\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { W3CBaggagePropagator } from './baggage/propagation/W3CBaggagePropagator';\nexport { AnchoredClock } from './common/anchored-clock';\nexport type { Clock } from './common/anchored-clock';\nexport { isAttributeValue, sanitizeAttributes } from './common/attributes';\nexport {\n globalErrorHandler,\n setGlobalErrorHandler,\n} from './common/global-error-handler';\nexport { loggingErrorHandler } from './common/logging-error-handler';\nexport {\n addHrTimes,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n hrTimeToMicroseconds,\n hrTimeToMilliseconds,\n hrTimeToNanoseconds,\n hrTimeToSeconds,\n hrTimeToTimeStamp,\n isTimeInput,\n isTimeInputHrTime,\n millisToHrTime,\n timeInputToHrTime,\n} from './common/time';\nexport { unrefTimer } from './common/timer-util';\nexport type { ErrorHandler, InstrumentationScope } from './common/types';\nexport { ExportResultCode } from './ExportResult';\nexport type { ExportResult } from './ExportResult';\nexport { parseKeyPairsIntoRecord } from './baggage/utils';\nexport {\n SDK_INFO,\n _globalThis,\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n otperformance,\n} from './platform';\nexport { CompositePropagator } from './propagation/composite';\nexport type { CompositePropagatorConfig } from './propagation/composite';\nexport {\n TRACE_PARENT_HEADER,\n TRACE_STATE_HEADER,\n W3CTraceContextPropagator,\n parseTraceParent,\n} from './trace/W3CTraceContextPropagator';\nexport {\n RPCType,\n deleteRPCMetadata,\n getRPCMetadata,\n setRPCMetadata,\n} from './trace/rpc-metadata';\nexport type { RPCMetadata } from './trace/rpc-metadata';\nexport {\n isTracingSuppressed,\n suppressTracing,\n unsuppressTracing,\n} from './trace/suppress-tracing';\nexport { TraceState } from './trace/TraceState';\nexport { merge } from './utils/merge';\nexport { TimeoutError, callWithTimeout } from './utils/timeout';\nexport { isUrlIgnored, urlMatches } from './utils/url';\nexport { BindOnceFuture } from './utils/callback';\nexport { diagLogLevelFromString } from './utils/configuration';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport type { Resource } from './Resource';\nimport { emptyResource, resourceFromDetectedResource } from './ResourceImpl';\nimport type { ResourceDetectionConfig } from './config';\n\n/**\n * Runs all resource detectors and returns the results merged into a single Resource.\n *\n * @param config Configuration for resource detection\n */\nexport const detectResources = (\n config: ResourceDetectionConfig = {}\n): Resource => {\n const resources: Resource[] = (config.detectors || []).map(d => {\n try {\n const resource = resourceFromDetectedResource(d.detect(config));\n diag.debug(`${d.constructor.name} found resource.`, resource);\n return resource;\n } catch (e) {\n diag.debug(`${d.constructor.name} failed: ${e.message}`);\n return emptyResource();\n }\n });\n\n return resources.reduce(\n (acc, resource) => acc.merge(resource),\n emptyResource()\n );\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The cloud account ID the resource is assigned to.\n *\n * @example 111111111111\n * @example opentelemetry\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CLOUD_ACCOUNT_ID = 'cloud.account.id' as const;\n\n/**\n * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running.\n *\n * @example us-east-1c\n *\n * @note Availability zones are called \"zones\" on Alibaba Cloud and Google Cloud.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone' as const;\n\n/**\n * Name of the cloud provider.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CLOUD_PROVIDER = 'cloud.provider' as const;\n\n/**\n * The geographical region the resource is running.\n *\n * @example us-central1\n * @example us-east-1\n *\n * @note Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/global-infrastructure/geographies/), [Google Cloud regions](https://cloud.google.com/about/locations), or [Tencent Cloud regions](https://www.tencentcloud.com/document/product/213/6091).\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CLOUD_REGION = 'cloud.region' as const;\n\n/**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated.\n *\n * @example a3bf90e006b2\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CONTAINER_ID = 'container.id' as const;\n\n/**\n * Name of the image the container was built on.\n *\n * @example gcr.io/opentelemetry/operator\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CONTAINER_IMAGE_NAME = 'container.image.name' as const;\n\n/**\n * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). Should be only the `<tag>` section of the full name for example from `registry.example.com/my-org/my-image:<tag>`.\n *\n * @example [\"v1.27.1\", \"3.5.7-0\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CONTAINER_IMAGE_TAGS = 'container.image.tags' as const;\n\n/**\n * Container name used by container runtime.\n *\n * @example opentelemetry-autoconf\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_CONTAINER_NAME = 'container.name' as const;\n\n/**\n * The CPU architecture the host system is running on.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_ARCH = 'host.arch' as const;\n\n/**\n * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. For non-containerized systems, this should be the `machine-id`. See the table below for the sources to use to determine the `machine-id` based on operating system.\n *\n * @example fdbf79e8af94cb7f9e8df36789187052\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_ID = 'host.id' as const;\n\n/**\n * VM image ID or host OS image ID. For Cloud, this value is from the provider.\n *\n * @example ami-07b06b442921831e5\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_IMAGE_ID = 'host.image.id' as const;\n\n/**\n * Name of the VM image or OS install the host was instantiated from.\n *\n * @example infra-ami-eks-worker-node-7d4ec78312\n * @example CentOS-8-x86_64-1905\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_IMAGE_NAME = 'host.image.name' as const;\n\n/**\n * The version string of the VM image or host OS as defined in [Version Attributes](/docs/resource/README.md#version-attributes).\n *\n * @example 0.1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_IMAGE_VERSION = 'host.image.version' as const;\n\n/**\n * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user.\n *\n * @example opentelemetry-test\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_NAME = 'host.name' as const;\n\n/**\n * Type of host. For Cloud, this must be the machine type.\n *\n * @example n1-standard-1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HOST_TYPE = 'host.type' as const;\n\n/**\n * The name of the cluster.\n *\n * @example opentelemetry-cluster\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_K8S_CLUSTER_NAME = 'k8s.cluster.name' as const;\n\n/**\n * The name of the Deployment.\n *\n * @example opentelemetry\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name' as const;\n\n/**\n * The name of the namespace that the pod is running in.\n *\n * @example default\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_K8S_NAMESPACE_NAME = 'k8s.namespace.name' as const;\n\n/**\n * The name of the Pod.\n *\n * @example opentelemetry-pod-autoconf\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_K8S_POD_NAME = 'k8s.pod.name' as const;\n\n/**\n * The operating system type.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OS_TYPE = 'os.type' as const;\n\n/**\n * The version string of the operating system as defined in [Version Attributes](/docs/resource/README.md#version-attributes).\n *\n * @example 14.2.1\n * @example 18.04.1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OS_VERSION = 'os.version' as const;\n\n/**\n * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`.\n *\n * @example cmd/otelcol\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_COMMAND = 'process.command' as const;\n\n/**\n * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`.\n *\n * @example [\"cmd/otecol\", \"--config=config.yaml\"]\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_COMMAND_ARGS = 'process.command_args' as const;\n\n/**\n * The name of the process executable. On Linux based systems, this **SHOULD** be set to the base name of the target of `/proc/[pid]/exe`. On Windows, this **SHOULD** be set to the base name of `GetProcessImageFileNameW`.\n *\n * @example otelcol\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_EXECUTABLE_NAME = 'process.executable.name' as const;\n\n/**\n * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`.\n *\n * @example /usr/bin/cmd/otelcol\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_EXECUTABLE_PATH = 'process.executable.path' as const;\n\n/**\n * The username of the user that owns the process.\n *\n * @example root\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_OWNER = 'process.owner' as const;\n\n/**\n * Process identifier (PID).\n *\n * @example 1234\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_PID = 'process.pid' as const;\n\n/**\n * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment.\n *\n * @example \"Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0\"\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_DESCRIPTION =\n 'process.runtime.description' as const;\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n\n/**\n * The version of the runtime of this process, as returned by the runtime without modification.\n *\n * @example \"14.0.2\"\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_VERSION = 'process.runtime.version' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * Additional description of the web engine (e.g. detailed version and edition information).\n *\n * @example WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - 2.2.2.Final\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEBENGINE_DESCRIPTION = 'webengine.description' as const;\n\n/**\n * The name of the web engine.\n *\n * @example WildFly\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEBENGINE_NAME = 'webengine.name' as const;\n\n/**\n * The version of the web engine.\n *\n * @example 21.0.0\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEBENGINE_VERSION = 'webengine.version' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as process from 'process';\n\nlet getMachineIdImpl: undefined | (() => Promise<string | undefined>);\n\nexport async function getMachineId(): Promise<string | undefined> {\n if (!getMachineIdImpl) {\n switch (process.platform) {\n case 'darwin':\n getMachineIdImpl = (await import('./getMachineId-darwin.js'))\n .getMachineId;\n break;\n case 'linux':\n getMachineIdImpl = (await import('./getMachineId-linux.js'))\n .getMachineId;\n break;\n case 'freebsd':\n getMachineIdImpl = (await import('./getMachineId-bsd.js')).getMachineId;\n break;\n case 'win32':\n getMachineIdImpl = (await import('./getMachineId-win.js')).getMachineId;\n break;\n default:\n getMachineIdImpl = (await import('./getMachineId-unsupported.js'))\n .getMachineId;\n break;\n }\n }\n\n return getMachineIdImpl();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport const normalizeArch = (nodeArchString: string): string => {\n // Maps from https://nodejs.org/api/os.html#osarch to arch values in spec:\n // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/host.md\n switch (nodeArchString) {\n case 'arm':\n return 'arm32';\n case 'ppc':\n return 'ppc32';\n case 'x64':\n return 'amd64';\n default:\n return nodeArchString;\n }\n};\n\nexport const normalizeType = (nodePlatform: string): string => {\n // Maps from https://nodejs.org/api/os.html#osplatform to arch values in spec:\n // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/os.md\n switch (nodePlatform) {\n case 'sunos':\n return 'solaris';\n case 'win32':\n return 'windows';\n default:\n return nodePlatform;\n }\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ATTR_HOST_ARCH, ATTR_HOST_ID, ATTR_HOST_NAME } from '../../../semconv';\nimport { arch, hostname } from 'os';\nimport type { ResourceDetectionConfig } from '../../../config';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n ResourceDetector,\n} from '../../../types';\nimport { getMachineId } from './machine-id/getMachineId';\nimport { normalizeArch } from './utils';\n\n/**\n * HostDetector detects the resources related to the host current process is\n * running on. Currently only non-cloud-based attributes are included.\n */\nclass HostDetector implements ResourceDetector {\n detect(_config?: ResourceDetectionConfig): DetectedResource {\n const attributes: DetectedResourceAttributes = {\n [ATTR_HOST_NAME]: hostname(),\n [ATTR_HOST_ARCH]: normalizeArch(arch()),\n [ATTR_HOST_ID]: getMachineId(),\n };\n\n return { attributes };\n }\n}\n\nexport const hostDetector = new HostDetector();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { hostDetector } from './HostDetector';\nexport { osDetector } from './OSDetector';\nexport { processDetector } from './ProcessDetector';\nexport { serviceInstanceIdDetector } from './ServiceInstanceIdDetector';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport {\n hostDetector,\n osDetector,\n processDetector,\n serviceInstanceIdDetector,\n} from './node';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { envDetector } from './EnvDetector';\nexport {\n hostDetector,\n osDetector,\n processDetector,\n serviceInstanceIdDetector,\n} from './platform';\nexport { noopDetector } from './NoopDetector';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type { ResourceDetectionConfig } from './config';\nexport { detectResources } from './detect-resources';\nexport {\n envDetector,\n hostDetector,\n osDetector,\n processDetector,\n serviceInstanceIdDetector,\n} from './detectors';\nexport type { Resource } from './Resource';\nexport {\n resourceFromAttributes,\n defaultResource,\n emptyResource,\n} from './ResourceImpl';\nexport { defaultServiceName } from './default-service-name';\nexport type {\n ResourceDetector,\n DetectedResource,\n DetectedResourceAttributes,\n RawResourceAttribute,\n MaybePromise,\n} from './types';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ContextManager, Context } from '@opentelemetry/api';\nimport { EventEmitter } from 'events';\n\ntype Func<T> = (...args: unknown[]) => T;\n\n/**\n * Store a map for each event of all original listeners and their \"patched\"\n * version. So when a listener is removed by the user, the corresponding\n * patched function will be also removed.\n */\ninterface PatchMap {\n [name: string]: WeakMap<Func<void>, Func<void>>;\n}\n\nconst ADD_LISTENER_METHODS = [\n 'addListener' as const,\n 'on' as const,\n 'once' as const,\n 'prependListener' as const,\n 'prependOnceListener' as const,\n];\n\nexport abstract class AbstractAsyncHooksContextManager\n implements ContextManager\n{\n abstract active(): Context;\n\n abstract with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F>;\n\n abstract enable(): this;\n\n abstract disable(): this;\n\n /**\n * Binds a the certain context or the active one to the target function and then returns the target\n * @param context A context (span) to be bind to target\n * @param target a function or event emitter. When target or one of its callbacks is called,\n * the provided context will be used as the active context for the duration of the call.\n */\n bind<T>(context: Context, target: T): T {\n if (target instanceof EventEmitter) {\n return this._bindEventEmitter(context, target);\n }\n\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n private _bindFunction<T extends Function>(context: Context, target: T): T {\n const manager = this;\n const contextWrapper = function (this: never, ...args: unknown[]) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n /**\n * It isn't possible to tell Typescript that contextWrapper is the same as T\n * so we forced to cast as any here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return contextWrapper as any;\n }\n\n /**\n * By default, EventEmitter call their callback with their context, which we do\n * not want, instead we will bind a specific context to all callbacks that\n * go through it.\n * @param context the context we want to bind\n * @param ee EventEmitter an instance of EventEmitter to patch\n */\n private _bindEventEmitter<T extends EventEmitter>(\n context: Context,\n ee: T\n ): T {\n const map = this._getPatchMap(ee);\n if (map !== undefined) return ee;\n this._createPatchMap(ee);\n\n // patch methods that add a listener to propagate context\n ADD_LISTENER_METHODS.forEach(methodName => {\n if (ee[methodName] === undefined) return;\n ee[methodName] = this._patchAddListener(ee, ee[methodName], context);\n });\n // patch methods that remove a listener\n if (typeof ee.removeListener === 'function') {\n ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);\n }\n if (typeof ee.off === 'function') {\n ee.off = this._patchRemoveListener(ee, ee.off);\n }\n // patch method that remove all listeners\n if (typeof ee.removeAllListeners === 'function') {\n ee.removeAllListeners = this._patchRemoveAllListeners(\n ee,\n ee.removeAllListeners\n );\n }\n return ee;\n }\n\n /**\n * Patch methods that remove a given listener so that we match the \"patched\"\n * version of that listener (the one that propagate context).\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveListener(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n const events = contextManager._getPatchMap(ee)?.[event];\n if (events === undefined) {\n return original.call(this, event, listener);\n }\n const patchedListener = events.get(listener);\n return original.call(this, event, patchedListener || listener);\n };\n }\n\n /**\n * Patch methods that remove all listeners so we remove our\n * internal references for a given event.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveAllListeners(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string) {\n const map = contextManager._getPatchMap(ee);\n if (map !== undefined) {\n if (arguments.length === 0) {\n contextManager._createPatchMap(ee);\n } else if (map[event] !== undefined) {\n delete map[event];\n }\n }\n return original.apply(this, arguments);\n };\n }\n\n /**\n * Patch methods on an event emitter instance that can add listeners so we\n * can force them to propagate a given context.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n * @param [context] context to propagate when calling listeners\n */\n private _patchAddListener(\n ee: EventEmitter,\n original: Function,\n context: Context\n ) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n /**\n * This check is required to prevent double-wrapping the listener.\n * The implementation for ee.once wraps the listener and calls ee.on.\n * Without this check, we would wrap that wrapped listener.\n * This causes an issue because ee.removeListener depends on the onceWrapper\n * to properly remove the listener. If we wrap their wrapper, we break\n * that detection.\n */\n if (contextManager._wrapped) {\n return original.call(this, event, listener);\n }\n let map = contextManager._getPatchMap(ee);\n if (map === undefined) {\n map = contextManager._createPatchMap(ee);\n }\n let listeners = map[event];\n if (listeners === undefined) {\n listeners = new WeakMap();\n map[event] = listeners;\n }\n const patchedListener = contextManager.bind(context, listener);\n // store a weak reference of the user listener to ours\n listeners.set(listener, patchedListener);\n\n /**\n * See comment at the start of this function for the explanation of this property.\n */\n contextManager._wrapped = true;\n try {\n return original.call(this, event, patchedListener);\n } finally {\n contextManager._wrapped = false;\n }\n };\n }\n\n private _createPatchMap(ee: EventEmitter): PatchMap {\n const map = Object.create(null);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (ee as any)[this._kOtListeners] = map;\n return map;\n }\n private _getPatchMap(ee: EventEmitter): PatchMap | undefined {\n return (ee as never)[this._kOtListeners];\n }\n\n private readonly _kOtListeners = Symbol('OtListeners');\n private _wrapped = false;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { ROOT_CONTEXT } from '@opentelemetry/api';\nimport * as asyncHooks from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\n/**\n * @deprecated Use AsyncLocalStorageContextManager instead.\n */\nexport class AsyncHooksContextManager extends AbstractAsyncHooksContextManager {\n private _asyncHook: asyncHooks.AsyncHook;\n private _contexts: Map<number, Context> = new Map();\n private _stack: Array<Context | undefined> = [];\n\n constructor() {\n super();\n this._asyncHook = asyncHooks.createHook({\n init: this._init.bind(this),\n before: this._before.bind(this),\n after: this._after.bind(this),\n destroy: this._destroy.bind(this),\n promiseResolve: this._destroy.bind(this),\n });\n }\n\n active(): Context {\n return this._stack[this._stack.length - 1] ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n this._enterContext(context);\n try {\n return fn.call(thisArg!, ...args);\n } finally {\n this._exitContext();\n }\n }\n\n enable(): this {\n this._asyncHook.enable();\n return this;\n }\n\n disable(): this {\n this._asyncHook.disable();\n this._contexts.clear();\n this._stack = [];\n return this;\n }\n\n /**\n * Init hook will be called when userland create a async context, setting the\n * context as the current one if it exist.\n * @param uid id of the async context\n * @param type the resource type\n */\n private _init(uid: number, type: string) {\n // ignore TIMERWRAP as they combine timers with same timeout which can lead to\n // false context propagation. TIMERWRAP has been removed in node 11\n // every timer has it's own `Timeout` resource anyway which is used to propagate\n // context.\n if (type === 'TIMERWRAP') return;\n\n const context = this._stack[this._stack.length - 1];\n if (context !== undefined) {\n this._contexts.set(uid, context);\n }\n }\n\n /**\n * Destroy hook will be called when a given context is no longer used so we can\n * remove its attached context.\n * @param uid uid of the async context\n */\n private _destroy(uid: number) {\n this._contexts.delete(uid);\n }\n\n /**\n * Before hook is called just before executing a async context.\n * @param uid uid of the async context\n */\n private _before(uid: number) {\n const context = this._contexts.get(uid);\n if (context !== undefined) {\n this._enterContext(context);\n }\n }\n\n /**\n * After hook is called just after completing the execution of a async context.\n */\n private _after() {\n this._exitContext();\n }\n\n /**\n * Set the given context as active\n */\n private _enterContext(context: Context) {\n this._stack.push(context);\n }\n\n /**\n * Remove the context at the root of the stack\n */\n private _exitContext() {\n this._stack.pop();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { ROOT_CONTEXT } from '@opentelemetry/api';\nimport type { ContextManagementToken } from './types';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\n/**\n * Wrapper around a token and _asyncLocalStorage to mirror the behavior of\n * a Node.js RunScope\n *\n * @internal not intended for direct public consumption. Will be removed once\n * withScope is available on all supported Node.js versions\n */\nclass DisposeOnceToken implements ContextManagementToken {\n private _isDisposed = false;\n private readonly _previousContext: Context;\n private readonly _asyncLocalStorage: AsyncLocalStorage<Context>;\n\n constructor(\n previousContext: Context,\n asyncLocalStorage: AsyncLocalStorage<Context>\n ) {\n this._previousContext = previousContext;\n this._asyncLocalStorage = asyncLocalStorage;\n }\n\n dispose() {\n if (this._isDisposed) {\n return;\n }\n\n this._asyncLocalStorage.enterWith(this._previousContext);\n this._isDisposed = true;\n }\n}\n\nexport class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager {\n private _asyncLocalStorage: AsyncLocalStorage<Context>;\n\n constructor() {\n super();\n this._asyncLocalStorage = new AsyncLocalStorage();\n }\n\n active(): Context {\n return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n const cb = thisArg == null ? fn : fn.bind(thisArg);\n return this._asyncLocalStorage.run(context, cb as never, ...args);\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n this._asyncLocalStorage.disable();\n return this;\n }\n\n /**\n * Imperatively sets `context` as active for the current async execution chain\n * and operations spawned from it. Returns a {@link ContextManagementToken} whose `dispose()`\n * restores the previous context (see {@link ContextManager.attach}).\n *\n * On Node.js 25.9+, delegates to `AsyncLocalStorage.withScope()` which returns\n * a native `RunScope`. On older Node.js versions, falls back to `enterWith()` with\n * a manual token.\n *\n * **Caveat for async functions:** Both `withScope()` and `enterWith()` affect the\n * entire current async execution chain. If `attach()` is called inside an async\n * function before the first `await`, the context change will leak into the caller's\n * context and remain active there until something else restores it. Prefer `with()`\n * for async code.\n *\n * @experimental This API is experimental and may change in minor releases without prior notice.\n */\n attach(context: Context): ContextManagementToken {\n // Node.js 25.9+: withScope() returns a RunScope with dispose()\n const withScope = (\n this._asyncLocalStorage as AsyncLocalStorage<Context> & {\n withScope?: (value: Context) => ContextManagementToken;\n }\n ).withScope;\n if (withScope) {\n return withScope.call(this._asyncLocalStorage, context);\n }\n\n // Fallback for older Node.js - this can be dropped when the minimum supported\n // Node.js version of this package is 25.9 or higher.\n const previousContext = this.active();\n this._asyncLocalStorage.enterWith(context);\n return new DisposeOnceToken(previousContext, this._asyncLocalStorage);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { AsyncHooksContextManager } from './AsyncHooksContextManager';\nexport { AsyncLocalStorageContextManager } from './AsyncLocalStorageContextManager';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource: Resource): Attributes {\n const attrs: Attributes = {};\n for (const [k, v] of resource.getRawAttributes()) {\n if (typeof (v as Partial<PromiseLike<unknown>>)?.then === 'function') {\n continue;\n }\n if (v != null) {\n attrs[k] ??= v as AttributeValue;\n }\n }\n return attrs;\n}\n\nexport type InspectFn = (value: unknown, options: unknown) => string;\n\nexport interface InspectStylizeOptions {\n depth?: number | null;\n stylize?: (text: string, styleType: string) => string;\n}\n\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(\n className: string,\n payload: object,\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n): unknown {\n if (typeof depth === 'number' && depth < 0) {\n const tag = `[${className}]`;\n return options?.stylize ? options.stylize(tag, 'special') : tag;\n }\n if (typeof inspect !== 'function' || !options) {\n return payload;\n }\n const childOptions = {\n ...options,\n depth: options.depth == null ? options.depth : options.depth - 1,\n };\n return `${className} ${inspect(payload, childOptions)}`;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n name: this.name,\n kind: this.kind,\n spanContext: this._spanContext,\n parentSpanContext: this.parentSpanContext,\n status: this.status,\n startTime: this.startTime,\n endTime: this.endTime,\n duration: this._duration,\n ended: this._ended,\n attributes: this.attributes,\n events: this.events,\n links: this.links,\n droppedAttributesCount: this._droppedAttributesCount,\n droppedEventsCount: this._droppedEventsCount,\n droppedLinksCount: this._droppedLinksCount,\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this.resource) },\n };\n return formatInspect('SpanImpl', payload, depth, options, inspect);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * A name uniquely identifying the instance of the OpenTelemetry component within its containing SDK instance.\n *\n * @example otlp_grpc_span_exporter/0\n * @example custom-name\n *\n * @note Implementations **SHOULD** ensure a low cardinality for this attribute, even across application or SDK restarts.\n * E.g. implementations **MUST NOT** use UUIDs as values for this attribute.\n *\n * Implementations **MAY** achieve these goals by following a `<otel.component.type>/<instance-counter>` pattern, e.g. `batching_span_processor/0`.\n * Hereby `otel.component.type` refers to the corresponding attribute value of the component.\n *\n * The value of `instance-counter` **MAY** be automatically assigned by the component and uniqueness within the enclosing SDK instance **MUST** be guaranteed.\n * For example, `<instance-counter>` **MAY** be implemented by using a monotonically increasing counter (starting with `0`), which is incremented every time an\n * instance of the given component type is started.\n *\n * With this implementation, for example the first Batching Span Processor would have `batching_span_processor/0`\n * as `otel.component.name`, the second one `batching_span_processor/1` and so on.\n * These values will therefore be reused in the case of an application restart.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_NAME = 'otel.component.name' as const;\n\n/**\n * A name identifying the type of the OpenTelemetry component.\n *\n * @example batching_span_processor\n * @example com.example.MySpanExporter\n *\n * @note If none of the standardized values apply, implementations **SHOULD** use the language-defined name of the type.\n * E.g. for Java the fully qualified classname **SHOULD** be used in this case.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_TYPE = 'otel.component.type' as const;\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of spans for which the processing has finished, either successful or failed.\n *\n * @note For successful processing, `error.type` **MUST NOT** be set. For failed processing, `error.type` **MUST** contain the failure cause.\n * For the SDK Simple and Batching Span Processor a span is considered to be processed already when it has been submitted to the exporter, not when the corresponding export call has finished.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED =\n 'otel.sdk.processor.span.processed' as const;\n\n/**\n * The maximum number of spans the queue of a given instance of an SDK span processor can hold.\n *\n * @note Only applies to span processors which use a queue, e.g. the SDK Batching Span Processor.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY =\n 'otel.sdk.processor.span.queue.capacity' as const;\n\n/**\n * The number of spans in the queue of a given instance of an SDK span processor.\n *\n * @note Only applies to span processors which use a queue, e.g. the SDK Batching Span Processor.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE =\n 'otel.sdk.processor.span.queue.size' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n\n/**\n * Enum value \"batching_span_processor\" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}.\n *\n * The builtin SDK batching span processor\n *\n * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR =\n 'batching_span_processor' as const;\n\n/**\n * Enum value \"simple_span_processor\" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}.\n *\n * The builtin SDK simple span processor\n *\n * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR =\n 'simple_span_processor' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.12.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { SpanLimits, TracerOptions } from './types';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n options: TracerOptions\n ) {\n this.instrumentationScope = instrumentationScope;\n this._sampler = options.sampler;\n this._spanLimits = options.spanLimits;\n this._resource = options.resource;\n this._idGenerator = options.idGenerator;\n this._spanProcessor = options.spanProcessor;\n\n const meter = options.meterProvider.getMeter(\n '@opentelemetry/sdk-trace',\n VERSION\n );\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * **Important**: The callback function is responsible for calling `span.end()`\n * to finish the span. Unlike some other OpenTelemetry implementations, the span\n * is NOT automatically ended when the callback returns. If `span.end()` is not\n * called, the span will never be exported and will be silently lost.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const payload = {\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this._resource) },\n spanLimits: this._spanLimits,\n };\n return formatInspect('Tracer', payload, depth, options, inspect);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Attributes,\n Counter,\n Meter,\n ObservableCallback,\n ObservableUpDownCounter,\n} from '@opentelemetry/api';\nimport { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_OTEL_COMPONENT_NAME,\n ATTR_OTEL_COMPONENT_TYPE,\n METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED,\n METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY,\n METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE,\n} from '../semconv';\n\nconst componentCounter = new Map<string, number>();\n\ninterface QueueConfig {\n capacity: number;\n getQueueSize: () => number;\n}\n\nexport class SpanProcessorMetrics {\n private readonly processedSpans: Counter;\n private readonly queueSize: ObservableUpDownCounter | undefined;\n private readonly queueSizeCallback: ObservableCallback | undefined;\n\n private readonly standardAttrs: Attributes;\n private readonly droppedAttrs: Attributes;\n\n constructor(componentType: string, meter: Meter, queueConfig?: QueueConfig) {\n const counter = componentCounter.get(componentType) ?? 0;\n componentCounter.set(componentType, counter + 1);\n\n this.standardAttrs = {\n [ATTR_OTEL_COMPONENT_TYPE]: componentType,\n [ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}`,\n };\n\n this.droppedAttrs = {\n ...this.standardAttrs,\n [ATTR_ERROR_TYPE]: 'queue_full',\n };\n\n this.processedSpans = meter.createCounter(\n METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED,\n {\n unit: '{span}',\n description:\n 'The number of spans for which the processing has finished, either successful or failed.',\n }\n );\n\n if (queueConfig) {\n const { capacity, getQueueSize } = queueConfig;\n const queueCapacity = meter.createUpDownCounter(\n METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY,\n {\n unit: '{span}',\n description:\n 'The maximum number of spans the queue of a given instance of an SDK span processor can hold.',\n }\n );\n queueCapacity.add(capacity, this.standardAttrs);\n\n this.queueSize = meter.createObservableUpDownCounter(\n METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE,\n {\n unit: '{span}',\n description:\n 'The number of spans in the queue of a given instance of an SDK span processor.',\n }\n );\n this.queueSizeCallback = result =>\n result.observe(getQueueSize(), this.standardAttrs);\n this.queueSize.addCallback(this.queueSizeCallback);\n }\n }\n\n dropSpans(count: number) {\n this.processedSpans.add(count, this.droppedAttrs);\n }\n\n finishSpans(count: number, error: Error | undefined) {\n if (!error) {\n this.processedSpans.add(count, this.standardAttrs);\n return;\n }\n\n const attrs = {\n ...this.standardAttrs,\n [ATTR_ERROR_TYPE]: error.name,\n };\n this.processedSpans.add(count, attrs);\n }\n\n shutdown() {\n if (this.queueSize && this.queueSizeCallback) {\n this.queueSize.removeCallback(this.queueSizeCallback);\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, createNoopMeter, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BatchSpanProcessorOptions } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\nimport { SpanProcessorMetrics } from './SpanProcessorMetrics';\nimport { OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR } from '../semconv';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<\n T extends BatchSpanProcessorOptions,\n> implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n private readonly _metrics: SpanProcessorMetrics;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(options: T) {\n this._exporter = options.exporter;\n this._maxExportBatchSize = options.maxExportBatchSize ?? 512;\n this._maxQueueSize = options.maxQueueSize ?? 2048;\n this._scheduledDelayMillis = options.scheduledDelayMillis ?? 5000;\n this._exportTimeoutMillis = options.exportTimeoutMillis ?? 30000;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n\n const meter = options.selfObsMeterProvider\n ? options.selfObsMeterProvider.getMeter('@opentelemetry/sdk-trace')\n : createNoopMeter();\n this._metrics = new SpanProcessorMetrics(\n OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR,\n meter,\n {\n capacity: this._maxQueueSize,\n getQueueSize: () => this._finishedSpans.length,\n }\n );\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n this._metrics.shutdown();\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n this._metrics.dropSpans(1);\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n this._metrics.finishSpans(spans.length, result.error);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BatchSpanProcessorOptions } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorOptions> {\n protected onShutdown(): void {}\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n TracerProvider as ApiTracerProvider,\n Tracer as ApiTracer,\n} from '@opentelemetry/api';\nimport { createNoopMeter } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type {\n ForceFlushOptions,\n TracerProviderOptions,\n TracerOptions,\n} from './types';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { RandomIdGenerator } from './platform';\nimport type { InspectFn, InspectStylizeOptions } from './inspect';\nimport {\n formatInspect,\n inspectCustom,\n settledResourceAttributes,\n} from './inspect';\n\nenum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class TracerProvider implements ApiTracerProvider {\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n private readonly _forceFlushTimeoutMillis: number;\n private readonly _tracerOptions: TracerOptions;\n private readonly _tracers: Map<string, Tracer> = new Map();\n\n constructor(options: TracerProviderOptions = {}) {\n this._forceFlushTimeoutMillis = options.forceFlushTimeoutMillis ?? 30000;\n this._resource = options.resource ?? defaultResource();\n const spanProcessors = options.spanProcessors ?? [];\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n\n this._tracerOptions = {\n resource: this._resource,\n sampler:\n options.sampler ??\n new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n }),\n spanLimits: {\n attributeCountLimit: options.spanLimits?.attributeCountLimit ?? 128,\n attributeValueLengthLimit:\n options.spanLimits?.attributeValueLengthLimit ?? Infinity,\n eventCountLimit: options.spanLimits?.eventCountLimit ?? 128,\n linkCountLimit: options.spanLimits?.linkCountLimit ?? 128,\n attributePerEventCountLimit:\n options.spanLimits?.attributePerEventCountLimit ?? 128,\n attributePerLinkCountLimit:\n options.spanLimits?.attributePerLinkCountLimit ?? 128,\n },\n idGenerator: options.idGenerator || new RandomIdGenerator(),\n spanProcessor: this._activeSpanProcessor,\n meterProvider: options.meterProvider ?? {\n getMeter() {\n return createNoopMeter();\n },\n },\n };\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._tracerOptions\n )\n );\n }\n\n return this._tracers.get(key)!;\n }\n\n forceFlush(options?: ForceFlushOptions): Promise<void> {\n const timeout = options?.timeoutMillis ?? this._forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n\n [inspectCustom](\n depth: number,\n options: InspectStylizeOptions | undefined,\n inspect: InspectFn | undefined\n ): unknown {\n const processors = this._activeSpanProcessor[\n '_spanProcessors'\n ] as SpanProcessor[];\n const payload = {\n resource: { attributes: settledResourceAttributes(this._resource) },\n tracers: Array.from(this._tracers.keys()),\n spanProcessors: processors.map(\n p => p.constructor?.name ?? 'SpanProcessor'\n ),\n };\n return formatInspect('TracerProvider', payload, depth, options, inspect);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationScope,\n traceId: span.spanContext().traceId,\n parentSpanContext: span.parentSpanContext,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from './SpanExporter';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createNoopMeter, TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { SimpleSpanProcessorOptions } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\nimport { SpanProcessorMetrics } from './SpanProcessorMetrics';\nimport { OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR } from '../semconv';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private readonly _exporter: SpanExporter;\n private readonly _metrics: SpanProcessorMetrics;\n private _shutdownOnce: BindOnceFuture<void>;\n private _pendingExports: Set<Promise<void>>;\n\n constructor(options: SimpleSpanProcessorOptions) {\n this._exporter = options.exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._pendingExports = new Set<Promise<void>>();\n\n const meter = options.selfObsMeterProvider\n ? options.selfObsMeterProvider.getMeter('@opentelemetry/sdk-trace')\n : createNoopMeter();\n this._metrics = new SpanProcessorMetrics(\n OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR,\n meter\n );\n }\n\n async forceFlush(): Promise<void> {\n let pendingExportError: unknown;\n let pendingExportRejected = false;\n try {\n await Promise.all(Array.from(this._pendingExports));\n } catch (err) {\n pendingExportError = err;\n pendingExportRejected = true;\n }\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n if (pendingExportRejected) {\n throw pendingExportError;\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const pendingExport = this._doExport(span);\n // Enqueue this export to the pending list so it can be flushed by the user.\n this._pendingExports.add(pendingExport);\n void pendingExport.then(\n () => {\n this._pendingExports.delete(pendingExport);\n },\n err => {\n globalErrorHandler(err);\n this._pendingExports.delete(pendingExport);\n }\n );\n }\n\n private async _doExport(span: ReadableSpan): Promise<void> {\n if (span.resource.asyncAttributesPending) {\n // Ensure resource is fully resolved before exporting.\n await span.resource.waitForAsyncAttributes?.();\n }\n\n const result = await internal._export(this._exporter, [span]);\n this._metrics.finishSpans(1, result.error);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw (\n result.error ??\n new Error(`SimpleSpanProcessor: span export failed (status ${result})`)\n );\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n this._metrics.shutdown();\n return this._exporter.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound =\n this._ratio === 1 ? 0x100000000 : Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < 32; i += 8) {\n let part = 0;\n for (let j = 0; j < 8; j++) {\n const c = traceId.charCodeAt(i + j);\n // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n part = (part << 4) | v;\n }\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { StackContextManager } from './StackContextManager';\nexport { TracerProvider } from './TracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport type { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport type { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { createAlwaysRecordSampler } from './sampler/AlwaysRecordSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { SamplingDecision } from './Sampler';\nexport type { Sampler, SamplingResult } from './Sampler';\nexport type { Span } from './Span';\nexport type { SpanProcessor } from './SpanProcessor';\nexport type { TimedEvent } from './TimedEvent';\nexport type {\n BatchSpanProcessorOptions,\n BatchSpanProcessorBrowserOptions,\n ForceFlushOptions,\n SimpleSpanProcessorOptions,\n SpanLimits,\n SpanProcessorOptions,\n TracerProviderOptions,\n} from './types';\nexport type { IdGenerator } from './IdGenerator';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from '@opentelemetry/sdk-trace';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerConfig } from './types-shim';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { merge } from '@opentelemetry/core';\nimport { loadDefaultConfig } from './config';\nimport type { TracerConfig } from './types-shim';\nimport { reconfigureLimits } from './utility';\nimport { TracerProvider } from '@opentelemetry/sdk-trace';\n\n/**\n * A TracerProvider implementation that reads configuration defaults from\n * OTEL_* environment variables per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BasicTracerProvider extends TracerProvider {\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n delete mergedConfig.generalLimits;\n super(mergedConfig);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getNumberFromEnv } from '@opentelemetry/core';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { BatchSpanProcessor as BatchSpanProcessNoEnvConfig } from '@opentelemetry/sdk-trace';\nimport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n} from './types-shim';\n\n/**\n * A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per\n * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/\n */\nexport class BatchSpanProcessor extends BatchSpanProcessNoEnvConfig {\n constructor(\n exporter: SpanExporter,\n config?: BufferConfig | BatchSpanProcessorBrowserConfig\n ) {\n if (!config) {\n config = {};\n }\n const envFallbacks: [keyof BufferConfig, string][] = [\n ['maxExportBatchSize', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE'],\n ['maxQueueSize', 'OTEL_BSP_MAX_QUEUE_SIZE'],\n ['scheduledDelayMillis', 'OTEL_BSP_SCHEDULE_DELAY'],\n ['exportTimeoutMillis', 'OTEL_BSP_EXPORT_TIMEOUT'],\n ];\n for (const [configName, envName] of envFallbacks) {\n if (config[configName] === undefined) {\n const envFallback = getNumberFromEnv(envName);\n if (envFallback !== undefined) {\n config[configName] = envFallback;\n }\n }\n }\n\n super({ exporter, ...config });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanExporter } from '@opentelemetry/sdk-trace';\nimport { SimpleSpanProcessor as SdkTraceSimpleSpanProcessor } from '@opentelemetry/sdk-trace';\n\n/**\n * A SimpleSpanProcessor with the old constructor call signature that\n * takes just a single exporter argument. This version does not support\n * the additional options that the SimpleSpanProcessor in sdk-trace does.\n */\nexport class SimpleSpanProcessor extends SdkTraceSimpleSpanProcessor {\n constructor(exporter: SpanExporter) {\n super({ exporter });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider-shim';\nexport type {\n BufferConfig,\n BatchSpanProcessorBrowserConfig,\n GeneralLimits,\n TracerConfig,\n SDKRegistrationConfig,\n} from './types-shim';\nexport { BatchSpanProcessor } from './BatchSpanProcessor-shim';\nexport { SimpleSpanProcessor } from './SimpleSpanProcessor-shim';\n\nexport {\n ConsoleSpanExporter,\n RandomIdGenerator,\n InMemorySpanExporter,\n NoopSpanProcessor,\n AlwaysOffSampler,\n AlwaysOnSampler,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n SamplingDecision,\n} from '@opentelemetry/sdk-trace';\nexport type {\n ReadableSpan,\n SpanExporter,\n Sampler,\n SamplingResult,\n Span,\n SpanProcessor,\n TimedEvent,\n SpanLimits,\n IdGenerator,\n} from '@opentelemetry/sdk-trace';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport type { SDKRegistrationConfig } from '@opentelemetry/sdk-trace-base';\nimport { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport type { NodeTracerConfig } from './config';\nimport type { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport { context, propagation, trace } from '@opentelemetry/api';\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from '@opentelemetry/core';\n\nfunction setupContextManager(\n contextManager: ContextManager | null | undefined\n) {\n // null means 'do not register'\n if (contextManager === null) {\n return;\n }\n\n // undefined means 'register default'\n if (contextManager === undefined) {\n const defaultContextManager = new AsyncLocalStorageContextManager();\n defaultContextManager.enable();\n context.setGlobalContextManager(defaultContextManager);\n return;\n }\n\n contextManager.enable();\n context.setGlobalContextManager(contextManager);\n}\n\nfunction setupPropagator(propagator: TextMapPropagator | null | undefined) {\n // null means 'do not register'\n if (propagator === null) {\n return;\n }\n\n // undefined means 'register default'\n if (propagator === undefined) {\n propagation.setGlobalPropagator(\n new CompositePropagator({\n propagators: [\n new W3CTraceContextPropagator(),\n new W3CBaggagePropagator(),\n ],\n })\n );\n return;\n }\n\n propagation.setGlobalPropagator(propagator);\n}\n\n/**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\nexport class NodeTracerProvider extends BasicTracerProvider {\n constructor(config: NodeTracerConfig = {}) {\n super(config);\n }\n\n /**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\n register(config: SDKRegistrationConfig = {}): void {\n trace.setGlobalTracerProvider(this);\n setupContextManager(config.contextManager);\n setupPropagator(config.propagator);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type { NodeTracerConfig } from './config';\nexport { NodeTracerProvider } from './NodeTracerProvider';\nexport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n BasicTracerProvider,\n BatchSpanProcessor,\n ConsoleSpanExporter,\n InMemorySpanExporter,\n NoopSpanProcessor,\n ParentBasedSampler,\n RandomIdGenerator,\n SamplingDecision,\n SimpleSpanProcessor,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace-base';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n IdGenerator,\n ReadableSpan,\n Sampler,\n SamplingResult,\n SDKRegistrationConfig,\n Span,\n SpanExporter,\n SpanLimits,\n SpanProcessor,\n TimedEvent,\n TracerConfig,\n} from '@opentelemetry/sdk-trace-base';\n", "/**\n * Telemetry names read outside the file that writes them: semconv and `integritystudio.*` attribute keys,\n * span names, metric names and histogram buckets. A key one handler writes and nothing else reads may stay a\n * literal there; move it here once a second file names it.\n */\n\n// ---- Semantic-convention keys ----\n\n/*\n * GenAI semconv source for every `gen_ai.*` name in the hooks (the one place this is dated):\n * https://github.com/open-telemetry/semantic-conventions-genai, release v0.1.0 (published 2026-11-21 UTC,\n * built on semantic-conventions v1.45.0). Doc paths and both bucket advisories checked against main\n * 2026-11-21 UTC. Every `gen_ai.*` convention is Development stability.\n * opentelemetry.io and the main semconv repo are stale stubs for `gen_ai.*`.\n * Attribute registry: docs/registry/attributes/gen-ai.md. Each definition below cites its own doc.\n */\n\n/** OTel `error.type` (core registry, stable). Set only on failure; absence means success. */\nexport const ERROR_TYPE_ATTR = 'error.type';\n/** `error.type` for a failure no pattern classifies. */\nexport const UNKNOWN_ERROR_TYPE = 'unknown';\n\n/** OTel `file.path` (core registry). */\nexport const FILE_PATH_ATTR = 'file.path';\n\nexport const GENAI_TOOL_NAME_ATTR = 'gen_ai.tool.name';\nexport const GENAI_TOOL_CALL_ID_ATTR = 'gen_ai.tool.call.id';\n\n/** GenAI agent-span keys: semantic-conventions-genai docs/gen-ai/gen-ai-agent-spans.md (source dated above). */\nexport const GENAI_AGENT_ATTRIBUTES = {\n AGENT_ID: 'gen_ai.agent.id',\n AGENT_NAME: 'gen_ai.agent.name',\n OPERATION_NAME: 'gen_ai.operation.name',\n /** Required on `create_agent` spans. */\n PROVIDER_NAME: 'gen_ai.provider.name',\n /** Not `gen_ai.request.model`, which SHOULD NOT be set with dynamic model selection. */\n RESPONSE_MODEL: 'gen_ai.response.model',\n} as const;\n\n/** Client calls only; never on agent spans, which use `AGENT_ATTRS.REQUESTED_MODEL`. */\nexport const GENAI_REQUEST_MODEL_ATTR = 'gen_ai.request.model';\n\nexport const GENAI_OPERATION = {\n INVOKE_AGENT: 'invoke_agent',\n CREATE_AGENT: 'create_agent',\n /** The judge's `gen_ai.client.operation` span. */\n CHAT: 'chat',\n /** The judge's token and cost counters. */\n EVALUATE: 'evaluate',\n} as const;\n\n/** `gen_ai.provider.name` values from docs/registry/attributes/gen-ai.md (xAI is `x_ai`; source dated above). */\nexport const GENAI_PROVIDER_NAMES = {\n ANTHROPIC: 'anthropic',\n OPENAI: 'openai',\n XAI: 'x_ai',\n} as const;\n\n/** CONVERSATION_ID comes only from a genuine thread id, never a path; PROJECT_SLUG groups conversations and must not shadow it. */\nexport const SESSION_ATTRIBUTES = {\n SESSION_ID: 'session.id',\n /** Standardized GenAI thread id (Development stability). */\n CONVERSATION_ID: 'gen_ai.conversation.id',\n PROJECT_SLUG: 'integritystudio.project.slug',\n PROJECT_NAME: 'integritystudio.project.name',\n PREVIOUS_ID: 'session.previous_id',\n} as const;\n\n/** Registered `vcs.*` keys (core semconv, release candidate). */\nexport const VCS_ATTRIBUTES = {\n REF_HEAD_NAME: 'vcs.ref.head.name',\n /** The repository alone; SHOULD NOT include the owner. */\n REPOSITORY_NAME: 'vcs.repository.name',\n OWNER_NAME: 'vcs.owner.name',\n} as const;\n\n/** Registered `process.*` keys (core semconv, release candidate). */\nexport const PROCESS_ATTRIBUTES = {\n PID: 'process.pid',\n RUNTIME_VERSION: 'process.runtime.version',\n WORKING_DIRECTORY: 'process.working_directory',\n} as const;\n\n// ---- Vendor keys (integritystudio.*) ----\n\n/** Hook span keys; here rather than otel-monitor.ts so modules can name them without importing the monitor. */\nexport const HOOK_NAME_ATTR = 'integritystudio.hook.name';\nexport const HOOK_TYPE_ATTR = 'integritystudio.hook.type';\nexport const HOOK_STATUS_ATTR = 'integritystudio.hook.status';\n/** Seeded on handler spans only. */\nexport const HOOK_TRIGGER_ATTR = 'integritystudio.hook.trigger';\nexport const HOOK_INSTRUMENTATION_ATTR = 'integritystudio.hook.instrumentation';\nexport const HOOK_INSTRUMENTATION_INTERNAL = 'internal';\nexport const UNKNOWN_HOOK_TYPE = 'unknown';\n/** Every `instrumentHook` name; report readers select spans by them, and the span name is `hookSpanName(name)`. */\nexport const HOOK_NAMES = {\n SESSION_START: 'session-start',\n SESSION_END: 'session-end',\n SKILL_ACTIVATION_PROMPT: 'skill-activation-prompt',\n NOTIFICATION: 'notification',\n PRE_COMPACT: 'pre-compact',\n POST_COMPACT: 'post-compact',\n BUILTIN_PRE_TOOL: 'builtin-pre-tool',\n MCP_PRE_TOOL: 'mcp-pre-tool',\n PLUGIN_PRE_TOOL: 'plugin-pre-tool',\n BUILTIN_POST_TOOL: 'builtin-post-tool',\n MCP_POST_TOOL: 'mcp-post-tool',\n PLUGIN_POST_TOOL: 'plugin-post-tool',\n POST_TOOL_FAILURE: 'post-tool-failure',\n UNKNOWN_TOOL: 'unknown-tool',\n TASK_STATE: 'builtin.task-state',\n CODE_STRUCTURE: 'code-structure',\n CHANGELOG_VERSION_BUMP: 'changelog-version-bump',\n POST_COMMIT_REVIEW: 'post-commit-review',\n AGENT_PREPARE: 'agent.operation.prepare',\n AGENT_FINALIZE: 'agent.operation.finalize',\n SUBAGENT_START: 'subagent-start',\n SUBAGENT_STOP: 'subagent-stop',\n TOKEN_METRICS: 'token-metrics-extraction',\n MCP_SERVER_FAILURE: 'mcp-server-failure',\n MCP_SESSION_FAILURE_SUMMARY: 'mcp-session-failure-summary',\n TELEMETRY_ALERT_EVALUATION: 'telemetry-alert-evaluation',\n ERROR_HANDLING_REMINDER: 'error-handling-reminder',\n QUALITY_EVALUATION_QUEUE: 'quality-evaluation-queue',\n QUALITY_EVALUATION: 'quality-evaluation-t2',\n} as const;\nexport type HookName = (typeof HOOK_NAMES)[keyof typeof HOOK_NAMES];\nexport const HOOK_SPAN_PREFIX = 'hook:';\nexport function hookSpanName<Name extends string>(hookName: Name): `${typeof HOOK_SPAN_PREFIX}${Name}` {\n return `${HOOK_SPAN_PREFIX}${hookName}`;\n}\n/** `hook.type` values; `instrumentHook` requires one, so a new handler cannot ship an unclassified span. */\nexport type HookTypeValue =\n | 'agent' | 'alert-evaluation' | 'builtin' | 'changelog-version-bump' | 'code-structure' | 'compaction' | 'error'\n | 'mcp' | 'mcp-init' | 'mcp-session-failure-summary' | 'notification' | 'plugin' | 'post-commit-review' | 'prompt'\n | 'quality-evaluation' | 'session' | 'task-state' | 'token-metrics' | 'tool-failure' | typeof UNKNOWN_HOOK_TYPE;\n\nexport const TOOL_ATTRS = {\n CATEGORY: 'integritystudio.tool.category',\n /** Where the tool's work ran (a Bash command's leading `cd`, else the event `cwd`), not the hook process's cwd. */\n WORKING_DIRECTORY: 'integritystudio.tool.working_directory',\n SUCCESS: 'integritystudio.tool.success',\n OUTPUT_SIZE: 'integritystudio.tool.output_size',\n HAS_ERROR: 'integritystudio.tool.has_error',\n ERROR_TYPE: 'integritystudio.tool.error_type',\n ERROR_CATEGORY: 'integritystudio.tool.error_category',\n RESULT_COUNT: 'integritystudio.tool.result_count',\n ROUTER_CATEGORY: 'integritystudio.tool.router_category',\n IS_INTERRUPT: 'integritystudio.tool.is_interrupt',\n ERROR: 'integritystudio.tool.error',\n /** Claude Code's own timing of a failed call; the only measured tool duration. */\n DURATION_MS: 'integritystudio.tool.duration_ms',\n /** A wait the `execute_tool.duration` sample is known to contain; absent means unobservable, e.g. permission prompts. */\n WAIT_KIND: 'integritystudio.tool.wait_kind',\n} as const;\n\n/** The MCP keys the pre- and post-tool spans, logs and metrics join on. */\nexport const MCP_ATTRS = {\n SERVER: 'integritystudio.mcp.server',\n TOOL: 'integritystudio.mcp.tool',\n FULL_NAME: 'integritystudio.mcp.full_name',\n SUCCESS: 'integritystudio.mcp.success',\n /** Where the server is configured; a metric label as well as a span key. */\n SCOPE: 'integritystudio.mcp.scope',\n OUTPUT_SIZE: 'integritystudio.mcp.output_size',\n HAS_ERROR: 'integritystudio.mcp.has_error',\n ERROR_TYPE: 'integritystudio.mcp.error_type',\n ERROR_CATEGORY: 'integritystudio.mcp.error_category',\n /** The output looks like it came from a different project than the event `cwd`. */\n CONTEXT_MISMATCH: 'integritystudio.mcp.context_mismatch',\n SUGGESTION: 'integritystudio.mcp.suggestion',\n} as const;\n\n/** Span attribute and metric name alike. */\nexport const CODE_STRUCTURE_SCORE = 'integritystudio.code.structure.score';\n\nexport const TASK_ATTRS = {\n ID: 'integritystudio.task.id',\n STATUS: 'integritystudio.task.status',\n} as const;\n\nexport const ALERT_ATTRS = {\n NAME: 'integritystudio.alert.name',\n MESSAGE: 'integritystudio.alert.message',\n SEVERITY: 'integritystudio.alert.severity',\n} as const;\n\n/** Session token totals on the Stop hook's token-metrics span. */\nexport const TOKEN_ATTRS = {\n FOUND: 'integritystudio.tokens.found',\n UNCHANGED: 'integritystudio.tokens.unchanged',\n INPUT: 'integritystudio.tokens.input',\n OUTPUT: 'integritystudio.tokens.output',\n CACHE_READ: 'integritystudio.tokens.cache_read',\n CACHE_CREATION: 'integritystudio.tokens.cache_creation',\n MESSAGES: 'integritystudio.tokens.messages',\n MODEL: 'integritystudio.tokens.model',\n} as const;\n\n/** The plugin keys invocations and completions join on. */\nexport const PLUGIN_ATTRS = {\n NAME: 'integritystudio.plugin.name',\n NAMESPACE: 'integritystudio.plugin.namespace',\n} as const;\n\nexport const TOOL_WAIT_KIND = {\n INTERACTIVE: 'interactive',\n /** Result in a later turn than the call; observable only through the Stop checkpoint. */\n CROSS_TURN: 'cross_turn',\n} as const;\n\nexport const AGENT_ATTRS = {\n TYPE: 'integritystudio.agent.type',\n CATEGORY: 'integritystudio.agent.category',\n SOURCE_TYPE: 'integritystudio.agent.source_type',\n /** The harness's per-run `agent_id`; `gen_ai.agent.id` is the stable identity (`composeAgentId`). */\n INSTANCE_ID: 'integritystudio.agent.instance_id',\n IS_RESUME: 'integritystudio.agent.is_resume',\n IS_BACKGROUND: 'integritystudio.agent.is_background',\n OUTPUT_SIZE: 'integritystudio.agent.output_size',\n HAS_ERROR: 'integritystudio.agent.has_error',\n HAS_RATE_LIMIT: 'integritystudio.agent.has_rate_limit',\n OUTPUT_MENTIONS_ERROR: 'integritystudio.agent.output_mentions_error',\n OUTPUT_HAS_STRUCTURE: 'integritystudio.agent.output.has_structure',\n OUTPUT_HAS_CODE: 'integritystudio.agent.output.has_code',\n OUTPUT_TRUNCATED: 'integritystudio.agent.output.truncated',\n OUTPUT_EMPTY: 'integritystudio.agent.output.empty',\n OUTPUT_HAS_ACTIONS: 'integritystudio.agent.output.has_actions',\n TRANSCRIPT_PATH: 'integritystudio.agent.transcript_path',\n HAS_TRANSCRIPT: 'integritystudio.agent.has_transcript',\n STOP_HOOK_ACTIVE: 'integritystudio.agent.stop_hook_active',\n LAST_MESSAGE_LENGTH: 'integritystudio.agent.last_message_length',\n /** Shared by the pre/post hook spans and the synthetic span, so Q4 pairs by exact id. */\n INVOCATION_ID: 'integritystudio.agent.invocation_id',\n /** Per-call model override, in place of `gen_ai.request.model`. */\n REQUESTED_MODEL: 'integritystudio.agent.requested_model',\n /** Set only when the agent ships inside a skill. */\n PARENT_SKILL: 'integritystudio.agent.parent_skill',\n TASK_DESCRIPTION: 'integritystudio.agent.task_description',\n} as const;\n\n/** Labels the cross-trace link from a synthetic `invoke_agent` span back to its dispatching span. */\nexport const AGENT_LINK_ATTRIBUTES = {\n LINK_KIND: 'integritystudio.link.kind',\n} as const;\n\nexport const AGENT_LINK_KIND_DISPATCH = 'agent_dispatch';\n\n/** Vendor keys on the SDK Resource only, never on spans or logs; the file exporters drop them. */\nexport const RESOURCE_ATTRIBUTES = {\n /** The hook process's own cwd basename. */\n PROJECT_DIRECTORY: 'integritystudio.project.directory',\n} as const;\n\nexport const CONTEXT_ATTRIBUTES = {\n ESTIMATED_TOKENS: 'integritystudio.context.estimated_tokens',\n UTILIZATION_PERCENT: 'integritystudio.context.utilization_percent',\n FREE_SPACE: 'integritystudio.context.free_space',\n TRANSCRIPT_SIZE: 'integritystudio.context.transcript_size',\n MESSAGE_COUNT: 'integritystudio.context.message_count',\n IS_RESUME: 'integritystudio.context.is_resume',\n /** Which `CONTEXT_TYPE` a `SESSION_METRICS.CONTEXT_BY_TYPE` sample measures. */\n TYPE: 'integritystudio.context.type',\n CACHE_HIT_RATE: 'integritystudio.context.cache_hit_rate',\n CACHE_EFFICIENCY: 'integritystudio.context.cache_efficiency',\n} as const;\n\n/** `integritystudio.git.*` keys; a commit SHA belongs in semconv `vcs.ref.head.revision`, not here. */\nexport const GIT_ATTRIBUTES = {\n UNCOMMITTED: 'integritystudio.git.uncommitted',\n COMMAND: 'integritystudio.git.command',\n FILES_CHANGED: 'integritystudio.git.files_changed',\n /** One Bash command can make several commits (/git-commit-smart) */\n COMMIT_COUNT: 'integritystudio.git.commit_count',\n FILES_OUTCOME: 'integritystudio.git.files_outcome',\n DOCS_ONLY: 'integritystudio.git.docs_only',\n /** Repo-relative, capped; FILES_TRUNCATED marks the cap */\n FILES: 'integritystudio.git.files',\n FILES_TRUNCATED: 'integritystudio.git.files_truncated',\n /** Why the post-commit review was not requested: `docs_only` or `already_reviewed`; older rows also carry `generated_only` */\n REVIEW_SKIP_REASON: 'integritystudio.git.review_skip_reason',\n} as const;\n\n/** Anything else means the payload changed. */\nexport const COMPACTION_TRIGGERS = {\n MANUAL: 'manual',\n AUTO: 'auto',\n} as const;\n\nexport const COMPACTION_ATTRIBUTES = {\n TRIGGER: 'integritystudio.compaction.trigger',\n TRIGGER_RAW: 'integritystudio.compaction.trigger_raw',\n HAS_CUSTOM_INSTRUCTIONS: 'integritystudio.compaction.has_custom_instructions',\n CUSTOM_INSTRUCTIONS_LENGTH: 'integritystudio.compaction.custom_instructions_length',\n SUMMARY_LENGTH: 'integritystudio.compaction.summary_length',\n} as const;\n\n// ---- Metric names and histogram buckets ----\n\n/** The one instrument with an exponential-histogram View in otel.ts. Spec: docs/gen-ai/execute-tool.md. */\nexport const GENAI_EXECUTE_TOOL_DURATION_METRIC = 'gen_ai.execute_tool.duration';\n/** In seconds, unlike every other duration here. Spec: docs/gen-ai/gen-ai-metrics.md. */\nexport const GENAI_INVOKE_AGENT_DURATION_METRIC = 'gen_ai.invoke_agent.duration';\n/** The judge's span, one per outbound model call. */\nexport const GENAI_CLIENT_OPERATION_SPAN = 'gen_ai.client.operation';\n/**\n * The judge's call duration, with `error.type` on failure. Spec: docs/gen-ai/client-inference.md\n * (semantic-conventions-genai #521, merged 2026-10-06), which replaced `gen_ai.client.operation.duration` for inference.\n */\nexport const GENAI_CLIENT_INFERENCE_DURATION_METRIC = 'gen_ai.client.inference.duration';\n\n/**\n * GenAI semconv bucket advisories in seconds, verbatim from semantic-conventions-genai\n * docs/gen-ai/execute-tool.md (TOOL) and docs/gen-ai/gen-ai-metrics.md (AGENT); source dated above.\n * Without them the SDK's millisecond-shaped defaults put every sample in the first bucket.\n * Instruments register once per name, so every call site must pass the same list.\n */\nexport const GENAI_DURATION_BUCKETS_S: Readonly<Record<'TOOL' | 'AGENT', readonly number[]>> = {\n /** `gen_ai.execute_tool.duration` and `gen_ai.client.inference.duration`. */\n TOOL: [0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92],\n /** `gen_ai.invoke_agent.duration`, up to 24 hours. Rows before 2026-11-21 (UTC) stop at 409.6. */\n AGENT: [0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 12.8, 25.6, 51.2, 102.4, 204.8, 409.6, 900, 1800, 3600, 7200, 14400, 43200, 86400],\n};\n\nexport const MCP_METRICS = {\n COMPLETIONS: 'integritystudio.mcp.completions',\n /** Same name as the span key. */\n OUTPUT_SIZE: MCP_ATTRS.OUTPUT_SIZE,\n} as const;\n\n/** `runHandlers` rejections; only PostToolUse fans out handler groups. */\nexport const POST_TOOL_HANDLER_ATTRS = {\n GROUP: 'integritystudio.post_tool.handler_group',\n INDEX: 'integritystudio.post_tool.handler_index',\n} as const;\n\nexport const POST_TOOL_METRICS = {\n HANDLER_REJECTIONS: 'integritystudio.post_tool.handler_rejections',\n} as const;\n\nexport const GIT_METRICS = {\n COMMITS_REVIEWED: 'integritystudio.git.commits_reviewed',\n COMMITS_REVIEW_SKIPPED: 'integritystudio.git.commits_review_skipped',\n} as const;\n\nexport const CONTEXT_METRICS = {\n COMPACTIONS: 'integritystudio.context.compactions',\n COMPACTION_SUMMARY_SIZE: 'integritystudio.context.compaction_summary_size',\n COMPACTIONS_COMPLETED: 'integritystudio.context.compactions_completed',\n /** Per-prompt snapshot; its own instrument because `SESSION_METRICS.CACHE_HIT_RATE` is the Stop hook's cumulative ratio. */\n CACHE_HIT_RATE: CONTEXT_ATTRIBUTES.CACHE_HIT_RATE,\n} as const;\n\n/**\n * Whole-session figures: Stop totals and context-window gauges. No model label, since a\n * `/model` switch makes them belong to neither. Vendor-prefixed: semconv owns `session.*`.\n */\nexport const SESSION_METRICS = {\n TOTAL_TOKENS: 'integritystudio.session.total_tokens',\n CACHE_HIT_RATE: 'integritystudio.session.cache_hit_rate',\n CACHE_EFFICIENCY: 'integritystudio.session.cache_efficiency',\n CONTEXT_SIZE: 'integritystudio.session.context.size',\n CONTEXT_UTILIZATION: 'integritystudio.session.context.utilization',\n CONTEXT_BY_TYPE: 'integritystudio.session.context.by_type',\n FREE_SPACE: 'integritystudio.session.free_space',\n STARTS: 'integritystudio.session.starts',\n} as const;\n", "/** Side-effect import: loads a bash-style .envrc into process.env with `$VAR` expansion. */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { SHELL_IDENTIFIER_SOURCE } from './regex.js';\n\n// NOT constants.CLAUDE_HOME: otel.ts imports this before constants.js so\n// TELEMETRY_DIR is set before constants.TELEMETRY_DIR is computed.\nconst ENVRC_PATH = path.join(process.env.HOME ?? '', '.claude', '.envrc');\n\nconst EXPORT_LINE_PATTERN = new RegExp(`^export\\\\s+(${SHELL_IDENTIFIER_SOURCE})=(.*)$`);\nconst BRACED_VARIABLE_PATTERN = new RegExp(`\\\\$\\\\{(${SHELL_IDENTIFIER_SOURCE})\\\\}`, 'g');\nconst BARE_VARIABLE_PATTERN = new RegExp(`\\\\$(${SHELL_IDENTIFIER_SOURCE})`, 'g');\n\nlet loaded = false;\n\n/** Load .envrc once per process. */\nexport function loadEnvrc(envrcPath = ENVRC_PATH): void {\n if (loaded) return;\n\n if (!fs.existsSync(envrcPath)) {\n console.warn(`[load-envrc] File not found: ${envrcPath}`);\n return;\n }\n\n const content = fs.readFileSync(envrcPath, 'utf-8');\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const match = trimmed.match(EXPORT_LINE_PATTERN);\n if (!match) continue;\n\n const [, key, rawValue] = match;\n if (key === undefined || rawValue === undefined || process.env[key] !== undefined) continue;\n\n const { value, singleQuoted } = parseValue(rawValue);\n const expanded = singleQuoted ? value : expandVariables(value);\n process.env[key] = expanded;\n }\n\n loaded = true;\n}\n\n/**\n * In an unquoted value, `#` opens a comment only when whitespace precedes it,\n * following shell word-splitting: `export C=#4B0082` and `export U=host/#frag`\n * keep their `#`, while `export U=host # note` drops the note.\n */\nconst INLINE_COMMENT_PATTERN = /\\s#/;\n\nfunction parseValue(raw: string): { value: string; singleQuoted: boolean } {\n const trimmed = raw.trim();\n\n // Match the closing quote, not the line end, so a trailing comment cannot embed the quotes.\n const quote = trimmed[0];\n if (quote === '\"' || quote === \"'\") {\n const closing = trimmed.indexOf(quote, 1);\n if (closing !== -1) {\n return { value: trimmed.slice(1, closing), singleQuoted: quote === \"'\" };\n }\n }\n\n const commentIndex = trimmed.search(INLINE_COMMENT_PATTERN);\n return {\n value: commentIndex === -1 ? trimmed : trimmed.slice(0, commentIndex).trim(),\n singleQuoted: false,\n };\n}\n\nfunction expandVariables(value: string): string {\n let result = value.replace(BRACED_VARIABLE_PATTERN, (_, varName: string) => {\n return process.env[varName] ?? '';\n });\n result = result.replace(BARE_VARIABLE_PATTERN, (_, varName: string) => {\n return process.env[varName] ?? '';\n });\n return result;\n}\n\n// Auto-load on import if not in test mode\nif (process.env.NODE_ENV !== 'test') {\n loadEnvrc();\n}\n", "/**\n * OTel bootstrap for the spawn-per-event hook process: file-only export to\n * traces/logs/metrics-*.jsonl, forwarded by the detached shipper (span-shipper.ts).\n * Deliberately shares no code with the MCP server's NodeSDK bootstrap (INF-1):\n * see docs/architecture/HOOKS_ARCHITECTURE.md \u00A7 Bootstrap before changing.\n */\n\nimport '../core/load-envrc.js';\n\nimport * as path from 'node:path';\nimport * as api from '@opentelemetry/api';\nimport { DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport * as logsApi from '@opentelemetry/api-logs';\nimport { diagLogLevelFromString } from '@opentelemetry/core';\nimport {\n detectResources,\n resourceFromAttributes,\n} from '@opentelemetry/resources';\nimport type { Resource } from '@opentelemetry/resources';\nimport { LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { MeterProvider, PeriodicExportingMetricReader, AggregationType } from '@opentelemetry/sdk-metrics';\nimport { NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';\nimport { memoizeIn } from '../core/file-utils.js';\nimport { writeStderr } from '../core/format-utils.js';\nimport { DURATION_MS } from '../core/units.js';\nimport { getGitHubRepo, splitOwnerRepo } from '../git/git-cache.js';\nimport { GENAI_EXECUTE_TOOL_DURATION_METRIC, PROCESS_ATTRIBUTES, VCS_ATTRIBUTES, RESOURCE_ATTRIBUTES } from './attributes.js';\nimport { FileLogExporter, FileMetricExporter, FileSpanExporter } from './file-exporters.js';\nimport { hostResourceDetector } from './host-resource.js';\nimport { getServiceName, SERVICE_VERSION } from './service-identity.js';\n\nconst SHUTDOWN_SIGNALS = ['SIGTERM', 'SIGINT'] as const;\n\n/** `OTEL_LOG_LEVEL` sets the verbosity of the SDK's own diagnostics; the severity of records written by `log()` is `LogLevelKey`. */\nconst OTEL_LOG_LEVEL = process.env.OTEL_LOG_LEVEL?.toLowerCase();\nif (OTEL_LOG_LEVEL) {\n const diagLevel = diagLogLevelFromString(OTEL_LOG_LEVEL) ?? DiagLogLevel.INFO;\n api.diag.setLogger(new DiagConsoleLogger(), diagLevel);\n if (diagLevel >= DiagLogLevel.DEBUG) {\n // stderr: on SessionStart/UserPromptSubmit stdout is injected into Claude's context.\n writeStderr(`OpenTelemetry: Debug mode enabled (level: ${OTEL_LOG_LEVEL})`);\n }\n}\n\n// File-only export: an inline OTLP flush held each hook process open 1.4\u20132.8 s (H12).\n// Module scope, so it resolves after the load-envrc side-effect import.\nconst SERVICE_NAME = getServiceName();\n\nlet tracerProvider: NodeTracerProvider | null = null;\nlet meterProvider: MeterProvider | null = null;\nlet loggerProvider: LoggerProvider | null = null;\nlet initialized = false;\nlet signalHandlersRegistered = false;\nlet shutdownInProgress = false;\n\nfunction buildResource(): Resource {\n const githubRepo = getGitHubRepo();\n const repo = githubRepo ? splitOwnerRepo(githubRepo) : undefined;\n\n // Only metrics-*.jsonl carries these (the span and log exporters project the resource\n // down to service name/version). `process.pid` alone, not processDetector: its argv,\n // executable path and runtime keys repeat on every metrics line and nothing reads them.\n // No env detector: Claude Code strips OTEL_RESOURCE_ATTRIBUTES from hooks.\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: SERVICE_NAME,\n [ATTR_SERVICE_VERSION]: SERVICE_VERSION,\n // The cwd's name, not the package.json name the session-start span records separately.\n [RESOURCE_ATTRIBUTES.PROJECT_DIRECTORY]: path.basename(process.cwd()),\n [PROCESS_ATTRIBUTES.PID]: process.pid,\n ...(repo && { [VCS_ATTRIBUTES.REPOSITORY_NAME]: repo.name }),\n ...(repo?.owner && { [VCS_ATTRIBUTES.OWNER_NAME]: repo.owner }),\n }).merge(detectResources({ detectors: [hostResourceDetector] }));\n}\n\nfunction registerShutdownSignalHandlers(): void {\n if (signalHandlersRegistered) return;\n for (const signal of SHUTDOWN_SIGNALS) {\n process.on(signal, () => {\n void shutdownTelemetry();\n });\n }\n signalHandlersRegistered = true;\n}\n\nexport function initTelemetry(): void {\n if (initialized) return;\n\n const resource = buildResource();\n\n // Simple processors: a hook process is too short-lived for batching. Metrics\n // collect at shutdown; the reader's interval never elapses inside one process.\n const spanProcessors = [new SimpleSpanProcessor(new FileSpanExporter())];\n const metricReader = new PeriodicExportingMetricReader({\n exporter: new FileMetricExporter(),\n exportIntervalMillis: DURATION_MS.TEN_SECONDS,\n });\n const logProcessors = [new SimpleLogRecordProcessor({ exporter: new FileLogExporter() })];\n\n loggerProvider = new LoggerProvider({ resource, processors: logProcessors });\n logsApi.logs.setGlobalLoggerProvider(loggerProvider);\n\n // Providers registered directly, not via NodeSDK: its env auto-configuration read\n // OTEL_*_EXPORTER and stood OTLP exporters up against localhost:4318, a retry loop\n // that held every hook process open 2.7\u20134.7 s (H10/H12). otel-exporter-env.test.ts\n // guards both the env vars and the exit latency.\n tracerProvider = new NodeTracerProvider({ resource, spanProcessors });\n tracerProvider.register();\n\n // OBP13b: execute_tool.duration spans five orders of magnitude (0.3 s p50 \u2192 40,426 s\n // tail). A View with a non-default aggregation overrides the instrument's bucket\n // advisory, which stays in place as the fallback.\n meterProvider = new MeterProvider({\n resource,\n readers: [metricReader],\n views: [\n {\n instrumentName: GENAI_EXECUTE_TOOL_DURATION_METRIC,\n aggregation: { type: AggregationType.EXPONENTIAL_HISTOGRAM },\n },\n ],\n });\n api.metrics.setGlobalMeterProvider(meterProvider);\n\n initialized = true;\n\n registerShutdownSignalHandlers();\n}\n\nasync function shutdownProviders(): Promise<void> {\n if (shutdownInProgress) return;\n shutdownInProgress = true;\n try {\n // Settled independently: one failed provider must not skip the meter, whose metrics land only at its shutdown.\n const results = await Promise.allSettled(\n [loggerProvider, tracerProvider, meterProvider].map(async (provider) => provider?.shutdown())\n );\n const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (failure) throw failure.reason;\n } finally {\n loggerProvider = null;\n tracerProvider = null;\n meterProvider = null;\n initialized = false;\n shutdownInProgress = false;\n }\n}\n\n/**\n * Never rejects, so a failed provider shutdown cannot cost the caller its exit code\n * (HTR1). A caller about to process.exit() must await it: metrics are collected only\n * at meter shutdown and are not on disk before then.\n */\nexport function shutdownTelemetry(): Promise<void> {\n return shutdownProviders().catch((err: unknown) => {\n if (OTEL_LOG_LEVEL === 'debug') writeStderr('[otel] shutdown error:', err);\n });\n}\n\nexport function getTracer(): api.Tracer {\n return api.trace.getTracer(SERVICE_NAME, SERVICE_VERSION);\n}\n\n/** `parentContext` (e.g. restored from the session-start span) makes the span a child of a remote parent. */\nexport function withSpan<T>(\n name: string,\n attributes: api.Attributes = {},\n fn: (span: api.Span) => T | Promise<T>,\n parentContext?: api.Context\n): Promise<T> {\n const ctx = parentContext ?? api.context.active();\n return getTracer().startActiveSpan(name, { attributes }, ctx, runInSpan(fn));\n}\n\nfunction runInSpan<T>(fn: (span: api.Span) => T | Promise<T>) {\n return async (span: api.Span): Promise<T> => {\n try {\n return await fn(span);\n } catch (error) {\n const exception = error instanceof Error ? error : new Error(String(error));\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: exception.message });\n span.recordException(exception);\n throw error;\n } finally {\n span.end();\n }\n };\n}\n\nexport interface SpanLinkInput {\n span: api.Span;\n attributes?: api.Attributes;\n}\n\nexport function withLinkedSpan<T>(\n name: string,\n linkedSpans: SpanLinkInput[],\n attributes: api.Attributes = {},\n fn: (span: api.Span) => T | Promise<T>\n): Promise<T> {\n const links = toSpanLinks(linkedSpans);\n return getTracer().startActiveSpan(name, { attributes, links }, runInSpan(fn));\n}\n\nfunction toSpanLinks(linkedSpans: SpanLinkInput[]): api.Link[] {\n return linkedSpans.map(({ span, attributes }) => ({\n context: span.spanContext(),\n attributes,\n }));\n}\n\n/** Caller must end the span. */\nexport function startLinkedSpan(\n name: string,\n linkedSpans: SpanLinkInput[],\n attributes: api.Attributes = {}\n): api.Span {\n return getTracer().startSpan(name, { attributes, links: toSpanLinks(linkedSpans) });\n}\n\nexport function createLinkFromContext(\n traceId: string,\n spanId: string,\n attributes?: api.Attributes\n): api.Link {\n return {\n context: {\n traceId,\n spanId,\n traceFlags: api.TraceFlags.SAMPLED,\n },\n attributes,\n };\n}\n\nexport function getTraceId(): string | null {\n return api.trace.getActiveSpan()?.spanContext().traceId ?? null;\n}\n\nexport function addEvent(name: string, attributes: api.Attributes = {}): void {\n api.trace.getActiveSpan()?.addEvent(name, attributes);\n}\n\nfunction getMeter(): api.Meter {\n return api.metrics.getMeter(SERVICE_NAME, SERVICE_VERSION);\n}\n\nconst histogramCache = new Map<string, api.Histogram>();\nconst counterCache = new Map<string, api.Counter>();\n\nexport interface InstrumentOptions {\n description?: string;\n unit?: string;\n /**\n * The `ExplicitBucketBoundaries` advisory parameter\n * (https://opentelemetry.io/docs/specs/otel/metrics/api/#instrument-advisory-parameters),\n * applied by the SDK with this precedence\n * (https://opentelemetry.io/docs/specs/otel/metrics/sdk/#instrument-advisory-parameters):\n * \"If no View matches, or if a matching View selects the default aggregation, the\n * ExplicitBucketBoundaries advisory parameter MUST be used.\" Omitted, the SDK's\n * millisecond-shaped defaults apply (see `GENAI_DURATION_BUCKETS_S`).\n */\n boundaries?: readonly number[];\n}\n\n/**\n * The single owner of histogram creation: two same-named instruments differing in\n * unit or description export two streams and split the series. Options apply on\n * first registration only.\n */\nexport function getHistogram(name: string, options?: InstrumentOptions): api.Histogram {\n return memoizeIn(histogramCache, name, () =>\n getMeter().createHistogram(name, {\n description: options?.description,\n unit: options?.unit,\n ...(options?.boundaries ? { advice: { explicitBucketBoundaries: [...options.boundaries] } } : {}),\n })\n );\n}\n\n/** Same single-owner rule as getHistogram. */\nexport function getCounter(name: string, options?: InstrumentOptions): api.Counter {\n return memoizeIn(counterCache, name, () =>\n getMeter().createCounter(name, {\n description: options?.description,\n unit: options?.unit,\n })\n );\n}\n\n/** Counter sibling of {@link recordMetric}. Neither initializes telemetry: without `initTelemetry` they record into the no-op meter. */\nexport function recordCounter(\n name: string,\n value: number,\n attributes: api.Attributes = {},\n options?: InstrumentOptions\n): void {\n getCounter(name, options).add(value, attributes);\n}\n\nexport function recordMetric(\n name: string,\n value: number,\n attributes: api.Attributes = {},\n options?: InstrumentOptions\n): void {\n getHistogram(name, options).record(value, attributes);\n}\n\n/** Each key is also the `SeverityNumber` member it maps to. */\nexport type LogLevelKey = 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL';\n\nexport function log(\n level: LogLevelKey,\n message: string,\n attributes: api.Attributes = {}\n): void {\n // The SDK stamps the active span context; a spanContext passed here is silently ignored.\n logsApi.logs.getLogger(SERVICE_NAME, SERVICE_VERSION).emit({\n severityNumber: SeverityNumber[level],\n severityText: level,\n body: message,\n attributes,\n });\n}\n\nexport { api as otelApi };\nexport type { Span, Attributes } from '@opentelemetry/api';\n\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type {\n LoggerProvider as ILoggerProvider,\n LoggerOptions as ILoggerOptions,\n Logger as ILogger,\n} from '@opentelemetry/api-logs';\nimport { createNoopLogger } from '@opentelemetry/api-logs';\nimport { defaultResource } from '@opentelemetry/resources';\nimport { BindOnceFuture } from '@opentelemetry/core';\n\nimport type { ForceFlushOptions, LoggerProviderOptions } from './types';\nimport { Logger } from './Logger';\nimport {\n DEFAULT_LOGGER_CONFIGURATOR,\n LoggerProviderSharedState,\n} from './internal/LoggerProviderSharedState';\nimport {\n getInstrumentationScopeKey,\n type LogInstrumentationScope,\n} from './internal/utils';\nimport { normalizeScopeAttributes } from './utils/validation';\n\nexport const DEFAULT_LOGGER_NAME = 'unknown';\n\nexport class LoggerProvider implements ILoggerProvider {\n private _shutdownOnce: BindOnceFuture<void>;\n private readonly _sharedState: LoggerProviderSharedState;\n\n constructor(config: LoggerProviderOptions = {}) {\n const mergedConfig = {\n resource: config.resource ?? defaultResource(),\n logRecordLimits: {\n attributeCountLimit: config.logRecordLimits?.attributeCountLimit ?? 128,\n attributeValueLengthLimit:\n config.logRecordLimits?.attributeValueLengthLimit ?? Infinity,\n },\n loggerConfigurator:\n config.loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR,\n processors: config.processors ?? [],\n meterProvider: config.meterProvider,\n };\n this._sharedState = new LoggerProviderSharedState(\n mergedConfig.resource,\n mergedConfig.logRecordLimits,\n mergedConfig.processors,\n mergedConfig.loggerConfigurator,\n mergedConfig.meterProvider\n );\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n }\n\n /**\n * Get a logger with the configuration of the LoggerProvider.\n */\n public getLogger(\n name: string,\n version?: string,\n options?: ILoggerOptions\n ): ILogger {\n if (this._shutdownOnce.isCalled) {\n diag.warn('A shutdown LoggerProvider cannot provide a Logger');\n return createNoopLogger();\n }\n\n if (!name) {\n diag.warn('Logger requested without instrumentation scope name.');\n }\n const loggerName = name || DEFAULT_LOGGER_NAME;\n const instrumentationScope: LogInstrumentationScope = {\n name: loggerName,\n version,\n schemaUrl: options?.schemaUrl,\n ...normalizeScopeAttributes(\n this._sharedState.logRecordLimits,\n options?.attributes\n ),\n };\n const key = getInstrumentationScopeKey(instrumentationScope);\n if (!this._sharedState.loggers.has(key)) {\n this._sharedState.loggers.set(\n key,\n new Logger(instrumentationScope, this._sharedState)\n );\n }\n\n return this._sharedState.loggers.get(key)!;\n }\n\n /**\n * Notifies all registered LogRecordProcessor to flush any buffered data.\n *\n * Returns a promise which is resolved when all flushes are complete.\n */\n public forceFlush(options?: ForceFlushOptions): Promise<void> {\n // do not flush after shutdown\n if (this._shutdownOnce.isCalled) {\n diag.warn('invalid attempt to force flush after LoggerProvider shutdown');\n return this._shutdownOnce.promise;\n }\n return this._sharedState.activeProcessor.forceFlush(options);\n }\n\n /**\n * Flush all buffered data and shut down the LoggerProvider and all registered\n * LogRecordProcessor.\n *\n * Returns a promise which is resolved when all flushes are complete.\n */\n public shutdown(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n diag.warn('shutdown may only be called once per LoggerProvider');\n return this._shutdownOnce.promise;\n }\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n this._sharedState.hasShutdown = true;\n return this._sharedState.activeProcessor.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.10.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Distinguish between a relative performance.now() value and an absolute\n // epoch-millisecond timestamp.\n //\n // performance.timeOrigin uses a monotonic clock that may be slightly ahead\n // of Date.now() due to clock adjustments (see MDN docs). This means a\n // real epoch-ms value (e.g. Date.now()) can land just below\n // performance.timeOrigin, causing it to be misclassified as a relative\n // performance.now() reading and doubled when timeOrigin is added.\n //\n // A genuine performance.now() value represents elapsed time since the\n // document/process started, so it is bounded by system uptime. No real\n // system has been running long enough for performance.now() to reach half\n // the current epoch time (~1994 in ms terms). We therefore treat any value\n // below half of performance.timeOrigin as a relative performance.now()\n // reading, and everything else as an absolute epoch-millisecond timestamp.\n if (time < performance.timeOrigin / 2) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { context } from '@opentelemetry/api';\nimport type { ExportResult } from '../ExportResult';\nimport { suppressTracing } from '../trace/suppress-tracing';\n\nexport interface Exporter<T> {\n export(arg: T, resultCallback: (result: ExportResult) => void): void;\n}\n\n/**\n * @internal\n * Shared functionality used by Exporters while exporting data, including suppression of Traces.\n */\nexport function _export<T>(\n exporter: Exporter<T>,\n arg: T\n): Promise<ExportResult> {\n return new Promise(resolve => {\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n exporter.export(arg, resolve);\n });\n });\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { W3CBaggagePropagator } from './baggage/propagation/W3CBaggagePropagator';\nexport { AnchoredClock } from './common/anchored-clock';\nexport type { Clock } from './common/anchored-clock';\nexport { isAttributeValue, sanitizeAttributes } from './common/attributes';\nexport {\n globalErrorHandler,\n setGlobalErrorHandler,\n} from './common/global-error-handler';\nexport { loggingErrorHandler } from './common/logging-error-handler';\nexport {\n addHrTimes,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n hrTimeToMicroseconds,\n hrTimeToMilliseconds,\n hrTimeToNanoseconds,\n hrTimeToSeconds,\n hrTimeToTimeStamp,\n isTimeInput,\n isTimeInputHrTime,\n millisToHrTime,\n timeInputToHrTime,\n} from './common/time';\nexport { unrefTimer } from './common/timer-util';\nexport type { ErrorHandler, InstrumentationScope } from './common/types';\nexport { ExportResultCode } from './ExportResult';\nexport type { ExportResult } from './ExportResult';\nexport { parseKeyPairsIntoRecord } from './baggage/utils';\nexport {\n SDK_INFO,\n _globalThis,\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n otperformance,\n} from './platform';\nexport { CompositePropagator } from './propagation/composite';\nexport type { CompositePropagatorConfig } from './propagation/composite';\nexport {\n TRACE_PARENT_HEADER,\n TRACE_STATE_HEADER,\n W3CTraceContextPropagator,\n parseTraceParent,\n} from './trace/W3CTraceContextPropagator';\nexport {\n RPCType,\n deleteRPCMetadata,\n getRPCMetadata,\n setRPCMetadata,\n} from './trace/rpc-metadata';\nexport type { RPCMetadata } from './trace/rpc-metadata';\nexport {\n isTracingSuppressed,\n suppressTracing,\n unsuppressTracing,\n} from './trace/suppress-tracing';\nexport { TraceState } from './trace/TraceState';\nexport { merge } from './utils/merge';\nexport { TimeoutError, callWithTimeout } from './utils/timeout';\nexport { isUrlIgnored, urlMatches } from './utils/url';\nexport { BindOnceFuture } from './utils/callback';\nexport { diagLogLevelFromString } from './utils/configuration';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Logger as ILogger, LogRecord } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Context } from '@opentelemetry/api';\nimport {\n context,\n trace,\n TraceFlags,\n isSpanContextValid,\n} from '@opentelemetry/api';\n\nimport { LogRecordImpl } from './LogRecordImpl';\nimport type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';\nimport type { LoggerConfig } from './types';\nimport type { LogInstrumentationScope } from './internal/utils';\n\nexport class Logger implements ILogger {\n private readonly _instrumentationScope: LogInstrumentationScope;\n private readonly _sharedState: LoggerProviderSharedState;\n private readonly _loggerConfig: Required<LoggerConfig>;\n\n constructor(\n instrumentationScope: LogInstrumentationScope,\n sharedState: LoggerProviderSharedState\n ) {\n this._instrumentationScope = instrumentationScope;\n this._sharedState = sharedState;\n // Cache the logger configuration at construction time\n // Since we don't support re-configuration, this avoids map lookups\n // and string allocations on each emit() call\n this._loggerConfig = this._sharedState.getLoggerConfig(\n this._instrumentationScope\n );\n }\n\n public emit(logRecord: LogRecord): void {\n const currentContext = logRecord.context || context.active();\n if (!this.enabled(logRecord)) {\n return;\n }\n\n /**\n * If a Logger was obtained with include_trace_context=true,\n * the LogRecords it emits MUST automatically include the Trace Context from the active Context,\n * if Context has not been explicitly set.\n */\n const logRecordInstance = new LogRecordImpl(\n this._sharedState,\n this._instrumentationScope,\n {\n context: currentContext,\n ...logRecord,\n }\n );\n this._sharedState.loggerMetrics.emitLog();\n /**\n * the explicitly passed Context,\n * the current Context, or an empty Context if the Logger was obtained with include_trace_context=false\n */\n this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);\n /**\n * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.\n * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.\n */\n logRecordInstance._makeReadonly();\n }\n\n public enabled(options?: {\n context?: Context;\n severityNumber?: SeverityNumber;\n eventName?: string;\n }): boolean {\n if (this._sharedState.hasShutdown) {\n return false;\n }\n\n const loggerConfig = this._loggerConfig;\n\n if (loggerConfig.disabled) {\n return false;\n }\n\n // Severity number given and lower than the min configured\n const severityNumber = options?.severityNumber;\n if (\n typeof severityNumber === 'number' &&\n severityNumber !== SeverityNumber.UNSPECIFIED &&\n severityNumber < loggerConfig.minimumSeverity\n ) {\n return false;\n }\n\n const currentContext = options?.context || context.active();\n // Trace based: the context (given or the active) has a unsampled Span\n if (loggerConfig.traceBased) {\n const spanContext = trace.getSpanContext(currentContext);\n if (spanContext && isSpanContextValid(spanContext)) {\n const isSampled =\n (spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED;\n if (!isSampled) {\n return false;\n }\n }\n }\n\n // Lastly check if there is any enabled processor\n const enabledOpts = {\n context: currentContext,\n instrumentationScope: this._instrumentationScope,\n severityNumber: options?.severityNumber,\n eventName: options?.eventName,\n };\n for (const processor of this._sharedState.processors) {\n if (!processor.enabled || processor.enabled(enabledOpts)) {\n return true;\n }\n }\n return false;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n AnyValue,\n LogAttributes,\n LogBody,\n LogRecord,\n SeverityNumber,\n} from '@opentelemetry/api-logs';\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { timeInputToHrTime } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableLogRecord } from './export/ReadableLogRecord';\nimport type { LogRecordLimits } from './types';\nimport type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';\nimport { addAttribute, AddAttributeDecision } from './utils/validation';\n\nexport class LogRecordImpl implements ReadableLogRecord {\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope & {\n attributes?: LogAttributes;\n droppedAttributesCount?: number;\n };\n readonly attributes: LogAttributes = {};\n private _hrTime: api.HrTime;\n private _hrTimeObserved: api.HrTime;\n private _spanContext?: api.SpanContext;\n private _severityText?: string;\n private _severityNumber?: SeverityNumber;\n private _body?: LogBody;\n private _eventName?: string;\n private _attributesCount: number = 0;\n private _droppedAttributesCount: number = 0;\n\n private _isReadonly: boolean = false;\n private readonly _logRecordLimits: Required<LogRecordLimits>;\n\n get hrTime(): api.HrTime {\n return this._hrTime;\n }\n set hrTime(hrTime: api.HrTime) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._hrTime = hrTime;\n }\n\n get hrTimeObserved(): api.HrTime {\n return this._hrTimeObserved;\n }\n set hrTimeObserved(hrTimeObserved: api.HrTime) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._hrTimeObserved = hrTimeObserved;\n }\n\n get spanContext(): api.SpanContext | undefined {\n return this._spanContext;\n }\n set spanContext(spanContext: api.SpanContext | undefined) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._spanContext = spanContext;\n }\n\n set severityText(severityText: string | undefined) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._severityText = severityText;\n }\n get severityText(): string | undefined {\n return this._severityText;\n }\n\n set severityNumber(severityNumber: SeverityNumber | undefined) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._severityNumber = severityNumber;\n }\n get severityNumber(): SeverityNumber | undefined {\n return this._severityNumber;\n }\n\n set body(body: LogBody | undefined) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._body = body;\n }\n get body(): LogBody | undefined {\n return this._body;\n }\n\n get eventName(): string | undefined {\n return this._eventName;\n }\n set eventName(eventName: string | undefined) {\n if (this._isLogRecordReadonly()) {\n return;\n }\n this._eventName = eventName;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n constructor(\n _sharedState: LoggerProviderSharedState,\n instrumentationScope: InstrumentationScope,\n logRecord: LogRecord\n ) {\n const {\n timestamp,\n observedTimestamp,\n eventName,\n severityNumber,\n severityText,\n body,\n attributes = {},\n exception,\n context,\n } = logRecord;\n\n const now = Date.now();\n this._hrTime = timeInputToHrTime(timestamp ?? now);\n this._hrTimeObserved = timeInputToHrTime(observedTimestamp ?? now);\n\n if (context) {\n const spanContext = api.trace.getSpanContext(context);\n if (spanContext && api.isSpanContextValid(spanContext)) {\n this._spanContext = spanContext;\n }\n }\n this.severityNumber = severityNumber;\n this.severityText = severityText;\n this.body = body;\n this.resource = _sharedState.resource;\n this.instrumentationScope = instrumentationScope;\n this._logRecordLimits = _sharedState.logRecordLimits;\n this._eventName = eventName;\n this.setAttributes(attributes);\n if (exception != null) {\n this._setException(exception);\n }\n }\n\n public setAttribute(key: string, value?: AnyValue) {\n if (this._isLogRecordReadonly()) {\n return this;\n }\n\n const decision = addAttribute(\n this.attributes,\n this._logRecordLimits,\n this._attributesCount,\n key,\n value\n );\n\n if (decision === AddAttributeDecision.DROP_LIMIT_REACHED) {\n this._droppedAttributesCount++;\n if (this._droppedAttributesCount === 1) {\n // Only warn once per LogRecord to avoid log spam\n api.diag.warn('Dropping extra attributes.');\n }\n } else if (decision === AddAttributeDecision.ADD_NEW) {\n this._attributesCount++;\n }\n\n return this;\n }\n\n public setAttributes(attributes: LogAttributes) {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n public setBody(body: LogBody) {\n this.body = body;\n return this;\n }\n\n public setEventName(eventName: string) {\n this.eventName = eventName;\n return this;\n }\n\n public setSeverityNumber(severityNumber: SeverityNumber) {\n this.severityNumber = severityNumber;\n return this;\n }\n\n public setSeverityText(severityText: string) {\n this.severityText = severityText;\n return this;\n }\n\n /**\n * @internal\n * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.\n * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.\n */\n _makeReadonly() {\n this._isReadonly = true;\n }\n\n private _setException(exception: unknown): void {\n let hasMinimumAttributes = false;\n\n if (typeof exception === 'string' || typeof exception === 'number') {\n if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {\n this.setAttribute(ATTR_EXCEPTION_MESSAGE, String(exception));\n }\n hasMinimumAttributes = true;\n } else if (exception && typeof exception === 'object') {\n const exceptionObj = exception as {\n code?: string | number;\n name?: string;\n message?: string;\n stack?: string;\n };\n\n if (exceptionObj.code) {\n if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {\n this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.code.toString());\n }\n hasMinimumAttributes = true;\n } else if (exceptionObj.name) {\n if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {\n this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.name);\n }\n hasMinimumAttributes = true;\n }\n\n if (exceptionObj.message) {\n if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {\n this.setAttribute(ATTR_EXCEPTION_MESSAGE, exceptionObj.message);\n }\n hasMinimumAttributes = true;\n }\n\n if (exceptionObj.stack) {\n if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_STACKTRACE)) {\n this.setAttribute(ATTR_EXCEPTION_STACKTRACE, exceptionObj.stack);\n }\n hasMinimumAttributes = true;\n }\n }\n\n if (!hasMinimumAttributes) {\n api.diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n private _isLogRecordReadonly(): boolean {\n if (this._isReadonly) {\n api.diag.warn('Can not execute the operation on emitted log record');\n }\n return this._isReadonly;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport type { AnyValue, LogAttributes } from '@opentelemetry/api-logs';\nimport type { LogRecordLimits } from '../types';\n\n/**\n * Validates if a value is a valid AnyValue for Log Attributes according to OpenTelemetry spec.\n * Log Attributes support a superset of standard Attributes and must support:\n * - Scalar values: string, boolean, signed 64-bit integer, or double precision floating point\n * - Byte arrays (Uint8Array)\n * - Arrays of any values (heterogeneous arrays allowed)\n * - Maps from string to any value (nested objects)\n * - Empty values (null/undefined)\n *\n * @param val - The value to validate\n * @returns true if the value is a valid AnyValue, false otherwise\n */\nexport function isLogAttributeValue(val: unknown): val is AnyValue {\n return isLogAttributeValueInternal(val, new WeakSet());\n}\n\nfunction isLogAttributeValueInternal(\n val: unknown,\n visited: WeakSet<object>\n): val is AnyValue {\n // null and undefined are explicitly allowed\n if (val == null) {\n return true;\n }\n\n // Scalar values\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return true;\n }\n\n // Byte arrays\n if (val instanceof Uint8Array) {\n return true;\n }\n\n // For objects and arrays, check for circular references\n if (typeof val === 'object') {\n if (visited.has(val as object)) {\n // Circular reference detected - reject it\n return false;\n }\n visited.add(val as object);\n\n // Arrays (can contain any AnyValue, including heterogeneous)\n if (Array.isArray(val)) {\n for (const item of val) {\n if (!isLogAttributeValueInternal(item, visited)) {\n return false;\n }\n }\n return true;\n }\n\n // Only accept plain objects (not built-in objects like Date, RegExp, Error, etc.)\n // Check if it's a plain object by verifying its constructor is Object or it has no constructor\n const obj = val as Record<string, unknown>;\n if (obj.constructor !== Object && obj.constructor !== undefined) {\n return false;\n }\n\n // Objects/Maps (including empty objects)\n // All object properties must be valid AnyValues\n for (const key in obj) {\n if (\n Object.prototype.hasOwnProperty.call(obj, key) &&\n !isLogAttributeValueInternal(obj[key], visited)\n ) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n}\n\nexport const enum AddAttributeDecision {\n DROP_INVALID = 0,\n DROP_LIMIT_REACHED = 1,\n ADD_NEW = 2,\n ADD_OVERWRITE_EXISTING = 3,\n}\n\nexport function addAttribute(\n attributes: LogAttributes,\n limits: Readonly<Required<LogRecordLimits>>,\n currentAttributesCount: number,\n key: string,\n value?: AnyValue\n): AddAttributeDecision {\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return AddAttributeDecision.DROP_INVALID;\n }\n if (!isLogAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return AddAttributeDecision.DROP_INVALID;\n }\n const isNewKey = !Object.prototype.hasOwnProperty.call(attributes, key);\n if (isNewKey && currentAttributesCount >= limits.attributeCountLimit) {\n return AddAttributeDecision.DROP_LIMIT_REACHED;\n }\n\n attributes[key] = truncateToSize(value, limits.attributeValueLengthLimit);\n if (isNewKey) {\n return AddAttributeDecision.ADD_NEW;\n }\n return AddAttributeDecision.ADD_OVERWRITE_EXISTING;\n}\n\nfunction truncateToSize(value: AnyValue, limit: number): AnyValue {\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // null/undefined - no truncation needed\n if (value == null) {\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n // Byte arrays - no truncation needed\n if (value instanceof Uint8Array) {\n return value;\n }\n\n // Arrays (can contain any AnyValue types)\n if (Array.isArray(value)) {\n return value.map(val => truncateToSize(val, limit));\n }\n\n // Objects/Maps - recursively truncate nested values\n if (typeof value === 'object') {\n const truncatedObj: Record<string, AnyValue> = {};\n for (const [k, v] of Object.entries(value as Record<string, AnyValue>)) {\n truncatedObj[k] = truncateToSize(v, limit);\n }\n return truncatedObj;\n }\n\n // Other types (number, boolean), no need to apply value length limit\n return value;\n}\n\n/**\n * Normalize attributes for use on the instrumentation scope. Drops invalid attributes and keeps track of\n * how many were dropped.\n *\n * @param limits\n * @param attributes\n */\nexport function normalizeScopeAttributes(\n limits: Readonly<Required<LogRecordLimits>>,\n attributes?: LogAttributes\n): {\n readonly attributes?: LogAttributes;\n readonly droppedAttributesCount?: number;\n} {\n if (attributes == null) {\n return {};\n }\n\n const normalizedAttributes: LogAttributes = {};\n let currentAttributesCount = 0;\n let droppedAttributesCount = 0;\n\n for (const [key, value] of Object.entries(attributes)) {\n const decision = addAttribute(\n normalizedAttributes,\n limits,\n currentAttributesCount,\n key,\n value\n );\n\n if (decision === AddAttributeDecision.ADD_NEW) {\n currentAttributesCount += 1;\n } else if (decision === AddAttributeDecision.DROP_INVALID) {\n droppedAttributesCount += 1;\n } else if (decision === AddAttributeDecision.DROP_LIMIT_REACHED) {\n droppedAttributesCount += 1;\n } else {\n // do nothing\n }\n }\n\n return {\n attributes: currentAttributesCount > 0 ? normalizedAttributes : undefined,\n droppedAttributesCount,\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { type MeterProvider, createNoopMeter } from '@opentelemetry/api';\nimport type { Logger } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type {\n LogRecordLimits,\n LoggerConfig,\n LoggerConfigurator,\n} from '../types';\nimport { NoopLogRecordProcessor } from '../export/NoopLogRecordProcessor';\nimport { MultiLogRecordProcessor } from '../MultiLogRecordProcessor';\nimport { getInstrumentationScopeKey } from './utils';\nimport { LoggerMetrics } from '../LoggerMetrics';\nimport { VERSION } from '../version';\n\nconst DEFAULT_LOGGER_CONFIG: Required<LoggerConfig> = {\n disabled: false,\n minimumSeverity: SeverityNumber.UNSPECIFIED,\n traceBased: false,\n};\n\n/**\n * Default LoggerConfigurator that returns the default config for all loggers\n */\nexport const DEFAULT_LOGGER_CONFIGURATOR: LoggerConfigurator = () => ({\n ...DEFAULT_LOGGER_CONFIG,\n});\n\nexport class LoggerProviderSharedState {\n readonly loggers: Map<string, Logger> = new Map();\n activeProcessor: LogRecordProcessor;\n readonly registeredLogRecordProcessors: LogRecordProcessor[] = [];\n readonly resource: Resource;\n readonly logRecordLimits: Required<LogRecordLimits>;\n readonly processors: LogRecordProcessor[];\n readonly loggerMetrics: LoggerMetrics;\n hasShutdown = false;\n private _loggerConfigurator: LoggerConfigurator;\n private _loggerConfigs: Map<string, Required<LoggerConfig>> = new Map();\n\n constructor(\n resource: Resource,\n logRecordLimits: Required<LogRecordLimits>,\n processors: LogRecordProcessor[],\n loggerConfigurator?: LoggerConfigurator,\n meterProvider?: MeterProvider\n ) {\n this.resource = resource;\n this.logRecordLimits = logRecordLimits;\n this.processors = processors;\n if (processors.length > 0) {\n this.registeredLogRecordProcessors = processors;\n this.activeProcessor = new MultiLogRecordProcessor(\n this.registeredLogRecordProcessors\n );\n } else {\n this.activeProcessor = new NoopLogRecordProcessor();\n }\n\n this._loggerConfigurator =\n loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR;\n\n const meter = meterProvider\n ? meterProvider.getMeter('@opentelemetry/sdk-logs', VERSION)\n : createNoopMeter();\n this.loggerMetrics = new LoggerMetrics(meter);\n }\n\n /**\n * Get the LoggerConfig for a given instrumentation scope.\n * Uses the LoggerConfigurator function to compute the config on first access\n * and caches the result.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n getLoggerConfig(\n instrumentationScope: InstrumentationScope\n ): Required<LoggerConfig> {\n const key = getInstrumentationScopeKey(instrumentationScope);\n\n // Return cached config if available\n let config = this._loggerConfigs.get(key);\n if (config) {\n return config;\n }\n\n // Compute config using the configurator\n // The configurator always returns a complete config\n config = this._loggerConfigurator(instrumentationScope);\n\n // Cache the result\n this._loggerConfigs.set(key, config);\n\n return config;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type { SdkLogRecord } from '../export/SdkLogRecord';\nimport type { SeverityNumber } from '@opentelemetry/api-logs';\n\nexport class NoopLogRecordProcessor implements LogRecordProcessor {\n public forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n public onEmit(_logRecord: SdkLogRecord, _context: Context): void {}\n\n public shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n public enabled(_options: {\n context: Context;\n instrumentationScope: InstrumentationScope;\n severityNumber?: SeverityNumber;\n eventName?: string;\n }): boolean {\n return false;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { callWithTimeout } from '@opentelemetry/core';\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from './LogRecordProcessor';\nimport type { SdkLogRecord } from './export/SdkLogRecord';\nimport type { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { ForceFlushOptions } from './types';\n\n/**\n * Implementation of the {@link LogRecordProcessor} that simply forwards all\n * received events to a list of {@link LogRecordProcessor}s.\n */\nexport class MultiLogRecordProcessor implements LogRecordProcessor {\n public readonly processors: LogRecordProcessor[];\n constructor(processors: LogRecordProcessor[]) {\n this.processors = processors;\n }\n\n public async forceFlush(options?: ForceFlushOptions): Promise<void> {\n const timeout = options?.timeoutMillis ?? 30000;\n await Promise.all(\n this.processors.map(processor =>\n callWithTimeout(processor.forceFlush(), timeout)\n )\n );\n }\n\n public onEmit(logRecord: SdkLogRecord, context?: Context): void {\n this.processors.forEach(processors =>\n processors.onEmit(logRecord, context)\n );\n }\n\n public async shutdown(): Promise<void> {\n await Promise.all(this.processors.map(processor => processor.shutdown()));\n }\n\n public enabled(options: {\n context: Context;\n instrumentationScope: InstrumentationScope;\n severityNumber?: SeverityNumber;\n eventName?: string;\n }): boolean {\n for (const processor of this.processors) {\n if (!processor.enabled || processor.enabled(options)) {\n return true;\n }\n }\n return false;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AnyValue, LogAttributes } from '@opentelemetry/api-logs';\nimport type { InstrumentationScope } from '@opentelemetry/core';\n\nexport type LogInstrumentationScope = InstrumentationScope & {\n readonly attributes?: LogAttributes;\n readonly droppedAttributesCount?: number;\n};\n\n/**\n * Normalizes an AnyValue to a JSON-serializable [typeTag, payload] tuple.\n *\n * Using a type tag as the first element guarantees that two values can only\n * produce the same tuple when they have the same type AND the same data,\n * avoiding cross-type collisions such as:\n * - null vs NaN vs Infinity (all become JSON `null` via JSON.stringify)\n * - -0 vs 0 (both become JSON `0` via JSON.stringify)\n * - string \"null\" vs the value null\n *\n * Object keys are sorted so that attribute maps with the same entries but\n * different insertion orders produce the same key.\n */\nfunction normalizeAnyValue(value: AnyValue): [string, unknown] {\n if (value === undefined) {\n return ['u', null];\n }\n if (value === null) {\n return ['n', null];\n }\n\n const valueType = typeof value;\n if (valueType === 'string') {\n return ['s', value];\n }\n if (valueType === 'boolean') {\n return ['b', value];\n }\n if (valueType === 'number') {\n if (Number.isNaN(value)) return ['nan', null];\n if (value === Infinity) return ['inf', null];\n if (value === -Infinity) return ['-inf', null];\n if (Object.is(value, -0)) return ['n0', null];\n return ['d', value];\n }\n if (value instanceof Uint8Array) {\n return ['bytes', Array.from(value)];\n }\n if (Array.isArray(value)) {\n return ['arr', value.map(normalizeAnyValue)];\n }\n // AnyValueMap — sort keys for insertion-order independence\n return [\n 'map',\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => [k, normalizeAnyValue(v)]),\n ];\n}\n\n/**\n * Converting the instrumentation scope object to a unique identifier string.\n * @param scope - The instrumentation scope to convert\n * @returns A unique string identifier for the scope\n */\nexport function getInstrumentationScopeKey(\n scope: LogInstrumentationScope\n): string {\n return JSON.stringify([\n scope.name,\n scope.version || '',\n scope.schemaUrl || '',\n normalizeAnyValue(scope.attributes),\n // we include the dropped attributes count to avoid collisions between scopes with the same identifying\n // characteristics, but different dropped counts. While there still can be collisions this is the best we can do if\n // we want to resolve the same logger without relying on object identity.\n scope.droppedAttributesCount ?? 0,\n ]);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The number of logs submitted to enabled SDK Loggers.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_LOG_CREATED = 'otel.sdk.log.created' as const;\n\n/**\n * The number of log records for which the processing has finished, either successful or failed.\n *\n * @note For successful processing, `error.type` **MUST NOT** be set. For failed processing, `error.type` **MUST** contain the failure cause.\n * For the SDK Simple and Batching Log Record Processor a log record is considered to be processed already when it has been submitted to the exporter,\n * not when the corresponding export call has finished.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_LOG_PROCESSED =\n 'otel.sdk.processor.log.processed' as const;\n\n/**\n * The maximum number of log records the queue of a given instance of an SDK Log Record processor can hold.\n *\n * @note Only applies to Log Record processors which use a queue, e.g. the SDK Batching Log Record Processor.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY =\n 'otel.sdk.processor.log.queue.capacity' as const;\n\n/**\n * The number of log records in the queue of a given instance of an SDK log processor.\n *\n * @note Only applies to log record processors which use a queue, e.g. the SDK Batching Log Record Processor.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE =\n 'otel.sdk.processor.log.queue.size' as const;\n\n/**\n * A name uniquely identifying the instance of the OpenTelemetry component within its containing SDK instance.\n *\n * @example otlp_grpc_span_exporter/0\n * @example custom-name\n *\n * @note Implementations **SHOULD** ensure a low cardinality for this attribute, even across application or SDK restarts.\n * E.g. implementations **MUST NOT** use UUIDs as values for this attribute.\n *\n * Implementations **MAY** achieve these goals by following a `<otel.component.type>/<instance-counter>` pattern, e.g. `batching_span_processor/0`.\n * Hereby `otel.component.type` refers to the corresponding attribute value of the component.\n *\n * The value of `instance-counter` **MAY** be automatically assigned by the component and uniqueness within the enclosing SDK instance **MUST** be guaranteed.\n * For example, `<instance-counter>` **MAY** be implemented by using a monotonically increasing counter (starting with `0`), which is incremented every time an\n * instance of the given component type is started.\n *\n * With this implementation, for example the first Batching Span Processor would have `batching_span_processor/0`\n * as `otel.component.name`, the second one `batching_span_processor/1` and so on.\n * These values will therefore be reused in the case of an application restart.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_NAME = 'otel.component.name' as const;\n\n/**\n * A name identifying the type of the OpenTelemetry component.\n *\n * @example batching_span_processor\n * @example com.example.MySpanExporter\n *\n * @note If none of the standardized values apply, implementations **SHOULD** use the language-defined name of the type.\n * E.g. for Java the fully qualified classname **SHOULD** be used in this case.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_TYPE = 'otel.component.type' as const;\n\n/**\n * Enum value \"batching_log_processor\" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}.\n *\n * The builtin SDK batching log record processor\n *\n * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const OTEL_COMPONENT_TYPE_VALUE_BATCHING_LOG_PROCESSOR =\n 'batching_log_processor' as const;\n\n/**\n * Enum value \"simple_log_processor\" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}.\n *\n * The builtin SDK simple log record processor\n *\n * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const OTEL_COMPONENT_TYPE_VALUE_SIMPLE_LOG_PROCESSOR =\n 'simple_log_processor' as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Counter, Meter } from '@opentelemetry/api';\nimport { METRIC_OTEL_SDK_LOG_CREATED } from './semconv';\n\n/**\n * Generates `otel.sdk.log.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#log-metrics\n */\nexport class LoggerMetrics {\n private readonly createdLogs: Counter;\n\n constructor(meter: Meter) {\n this.createdLogs = meter.createCounter(METRIC_OTEL_SDK_LOG_CREATED, {\n unit: '{log_record}',\n description: 'The number of logs submitted to enabled SDK Loggers.',\n });\n }\n\n emitLog() {\n this.createdLogs.add(1);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.221.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createNoopMeter } from '@opentelemetry/api';\nimport type { ExportResult } from '@opentelemetry/core';\nimport {\n BindOnceFuture,\n ExportResultCode,\n globalErrorHandler,\n internal,\n} from '@opentelemetry/core';\nimport type { LogRecordExporter } from './LogRecordExporter';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type { SdkLogRecord } from './SdkLogRecord';\nimport { OTEL_COMPONENT_TYPE_VALUE_SIMPLE_LOG_PROCESSOR } from '../semconv';\nimport { LogRecordProcessorMetrics } from './LogRecordProcessorMetrics';\nimport type { Context } from '@opentelemetry/api';\nimport type { SimpleLogRecordProcessorOptions } from '../types';\n\n/**\n * An implementation of the {@link LogRecordProcessor} interface that exports\n * each {@link LogRecord} as it is emitted.\n *\n * NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord}\n * individually instead of batching them together, which can cause significant\n * performance overhead with most exporters. For production use, please consider\n * using the {@link BatchLogRecordProcessor} instead.\n */\nexport class SimpleLogRecordProcessor implements LogRecordProcessor {\n private readonly _exporter: LogRecordExporter;\n private readonly _metrics: LogRecordProcessorMetrics;\n private _shutdownOnce: BindOnceFuture<void>;\n private _unresolvedExports: Set<Promise<void>>;\n\n constructor(options: SimpleLogRecordProcessorOptions) {\n this._exporter = options.exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._unresolvedExports = new Set<Promise<void>>();\n\n const meter = options?.selfObsMeterProvider\n ? options.selfObsMeterProvider.getMeter('@opentelemetry/sdk-logs')\n : createNoopMeter();\n this._metrics = new LogRecordProcessorMetrics(\n OTEL_COMPONENT_TYPE_VALUE_SIMPLE_LOG_PROCESSOR,\n meter\n );\n }\n\n public onEmit(logRecord: SdkLogRecord, _context?: Context): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n const doExport = () =>\n internal\n ._export(this._exporter, [logRecord])\n .then((result: ExportResult) => {\n this._metrics.finishLogs(1, result.error);\n if (result.code !== ExportResultCode.SUCCESS) {\n globalErrorHandler(\n result.error ??\n new Error(\n `SimpleLogRecordProcessor: log record export failed (status ${result})`\n )\n );\n }\n })\n .catch(globalErrorHandler);\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (logRecord.resource.asyncAttributesPending) {\n const exportPromise = logRecord.resource\n .waitForAsyncAttributes?.()\n .then(() => {\n // Using TS Non-null assertion operator because exportPromise could not be null in here\n // if waitForAsyncAttributes is not present this code will never be reached\n this._unresolvedExports.delete(exportPromise!);\n return doExport();\n }, globalErrorHandler);\n\n // store the unresolved exports\n if (exportPromise != null) {\n this._unresolvedExports.add(exportPromise);\n }\n } else {\n void doExport();\n }\n }\n\n public async forceFlush(): Promise<void> {\n // await unresolved resources before resolving\n await Promise.all(Array.from(this._unresolvedExports));\n }\n\n public shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n this._metrics.shutdown();\n return this._exporter.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Attributes,\n Counter,\n Meter,\n ObservableCallback,\n ObservableUpDownCounter,\n} from '@opentelemetry/api';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_OTEL_COMPONENT_NAME,\n ATTR_OTEL_COMPONENT_TYPE,\n METRIC_OTEL_SDK_PROCESSOR_LOG_PROCESSED,\n METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY,\n METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE,\n} from '../semconv';\n\nconst componentCounter = new Map<string, number>();\n\ninterface QueueConfig {\n capacity: number;\n getQueueSize: () => number;\n}\n\nexport class LogRecordProcessorMetrics {\n private readonly processedLogs: Counter;\n private readonly queueSize: ObservableUpDownCounter | undefined;\n private readonly queueSizeCallback: ObservableCallback | undefined;\n\n private readonly standardAttrs: Attributes;\n private readonly droppedAttrs: Attributes;\n\n constructor(componentType: string, meter: Meter, queueConfig?: QueueConfig) {\n const counter = componentCounter.get(componentType) ?? 0;\n componentCounter.set(componentType, counter + 1);\n\n this.standardAttrs = {\n [ATTR_OTEL_COMPONENT_TYPE]: componentType,\n [ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}`,\n };\n\n this.droppedAttrs = {\n ...this.standardAttrs,\n [ATTR_ERROR_TYPE]: 'queue_full',\n };\n\n this.processedLogs = meter.createCounter(\n METRIC_OTEL_SDK_PROCESSOR_LOG_PROCESSED,\n {\n unit: '{log_record}',\n description:\n 'The number of log records for which the processing has finished, either successful or failed.',\n }\n );\n\n if (queueConfig) {\n const { capacity, getQueueSize } = queueConfig;\n const queueCapacity = meter.createUpDownCounter(\n METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY,\n {\n unit: '{log_record}',\n description:\n 'The maximum number of log records the queue of a given instance of an SDK log processor can hold.',\n }\n );\n queueCapacity.add(capacity, this.standardAttrs);\n\n this.queueSize = meter.createObservableUpDownCounter(\n METRIC_OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE,\n {\n unit: '{log_record}',\n description:\n 'The number of log records in the queue of a given instance of an SDK log processor.',\n }\n );\n this.queueSizeCallback = result =>\n result.observe(getQueueSize(), this.standardAttrs);\n this.queueSize.addCallback(this.queueSizeCallback);\n }\n }\n\n dropLogs(count: number) {\n this.processedLogs.add(count, this.droppedAttrs);\n }\n\n finishLogs(count: number, error: Error | undefined) {\n if (!error) {\n this.processedLogs.add(count, this.standardAttrs);\n return;\n }\n\n const attrs = {\n ...this.standardAttrs,\n [ATTR_ERROR_TYPE]: error.name,\n };\n this.processedLogs.add(count, attrs);\n }\n\n shutdown() {\n if (this.queueSize && this.queueSizeCallback) {\n this.queueSize.removeCallback(this.queueSizeCallback);\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * AggregationTemporality indicates the way additive quantities are expressed.\n */\nexport enum AggregationTemporality {\n DELTA,\n CUMULATIVE,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes, ValueType } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { AggregationTemporality } from './AggregationTemporality';\nimport type { Histogram, ExponentialHistogram } from '../aggregator/types';\n\n/**\n * Supported types of metric instruments.\n */\nexport enum InstrumentType {\n COUNTER = 'COUNTER',\n GAUGE = 'GAUGE',\n HISTOGRAM = 'HISTOGRAM',\n UP_DOWN_COUNTER = 'UP_DOWN_COUNTER',\n OBSERVABLE_COUNTER = 'OBSERVABLE_COUNTER',\n OBSERVABLE_GAUGE = 'OBSERVABLE_GAUGE',\n OBSERVABLE_UP_DOWN_COUNTER = 'OBSERVABLE_UP_DOWN_COUNTER',\n}\n\nexport interface MetricDescriptor {\n readonly name: string;\n readonly description: string;\n readonly unit: string;\n readonly valueType: ValueType;\n}\n\n/**\n * Basic metric data fields.\n */\ninterface BaseMetricData {\n readonly descriptor: MetricDescriptor;\n readonly aggregationTemporality: AggregationTemporality;\n /**\n * DataPointType of the metric instrument.\n */\n readonly dataPointType: DataPointType;\n}\n\n/**\n * Represents a metric data aggregated by either a LastValueAggregation or\n * SumAggregation.\n */\nexport interface SumMetricData extends BaseMetricData {\n readonly dataPointType: DataPointType.SUM;\n readonly dataPoints: DataPoint<number>[];\n readonly isMonotonic: boolean;\n}\n\nexport interface GaugeMetricData extends BaseMetricData {\n readonly dataPointType: DataPointType.GAUGE;\n readonly dataPoints: DataPoint<number>[];\n}\n\n/**\n * Represents a metric data aggregated by a HistogramAggregation.\n */\nexport interface HistogramMetricData extends BaseMetricData {\n readonly dataPointType: DataPointType.HISTOGRAM;\n readonly dataPoints: DataPoint<Histogram>[];\n}\n\n/**\n * Represents a metric data aggregated by a ExponentialHistogramAggregation.\n */\nexport interface ExponentialHistogramMetricData extends BaseMetricData {\n readonly dataPointType: DataPointType.EXPONENTIAL_HISTOGRAM;\n readonly dataPoints: DataPoint<ExponentialHistogram>[];\n}\n\n/**\n * Represents an aggregated metric data.\n */\nexport type MetricData =\n | SumMetricData\n | GaugeMetricData\n | HistogramMetricData\n | ExponentialHistogramMetricData;\n\nexport interface ScopeMetrics {\n scope: InstrumentationScope;\n metrics: MetricData[];\n}\n\nexport interface ResourceMetrics {\n resource: Resource;\n scopeMetrics: ScopeMetrics[];\n}\n\n/**\n * Represents the collection result of the metrics. If there are any\n * non-critical errors in the collection, like throwing in a single observable\n * callback, these errors are aggregated in the {@link CollectionResult.errors}\n * array and other successfully collected metrics are returned.\n */\nexport interface CollectionResult {\n /**\n * Collected metrics.\n */\n resourceMetrics: ResourceMetrics;\n /**\n * Arbitrary JavaScript exception values.\n */\n errors: unknown[];\n}\n\n/**\n * The aggregated point data type.\n */\nexport enum DataPointType {\n /**\n * A histogram data point contains a histogram statistics of collected\n * values with a list of explicit bucket boundaries and statistics such\n * as min, max, count, and sum of all collected values.\n */\n HISTOGRAM,\n /**\n * An exponential histogram data point contains a histogram statistics of\n * collected values where bucket boundaries are automatically calculated\n * using an exponential function, and statistics such as min, max, count,\n * and sum of all collected values.\n */\n EXPONENTIAL_HISTOGRAM,\n /**\n * A gauge metric data point has only a single numeric value.\n */\n GAUGE,\n /**\n * A sum metric data point has a single numeric value and a\n * monotonicity-indicator.\n */\n SUM,\n}\n\n/**\n * Represents an aggregated point data with start time, end time and their\n * associated attributes and points.\n */\nexport interface DataPoint<T> {\n /**\n * The start epoch timestamp of the DataPoint, usually the time when\n * the metric was created when the preferred AggregationTemporality is\n * CUMULATIVE, or last collection time otherwise.\n */\n readonly startTime: HrTime;\n /**\n * The end epoch timestamp when data were collected, usually it represents\n * the moment when `MetricReader.collect` was called.\n */\n readonly endTime: HrTime;\n /**\n * The attributes associated with this DataPoint.\n */\n readonly attributes: Attributes;\n /**\n * The value for this DataPoint. The type of the value is indicated by the\n * {@link DataPointType}.\n */\n readonly value: T;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { AggregationTemporality } from './AggregationTemporality';\nimport type { MetricProducer } from './MetricProducer';\nimport type { CollectionResult, InstrumentType } from './MetricData';\nimport { callWithTimeout } from '../utils';\nimport type {\n CollectionOptions,\n ForceFlushOptions,\n ShutdownOptions,\n} from '../types';\nimport type {\n AggregationSelector,\n AggregationTemporalitySelector,\n} from './AggregationSelector';\nimport {\n DEFAULT_AGGREGATION_SELECTOR,\n DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,\n} from './AggregationSelector';\nimport type { AggregationOption } from '../view/AggregationOption';\nimport type { CardinalitySelector } from './CardinalitySelector';\nimport { MetricReaderMetrics } from './MetricReaderMetrics';\nimport { VERSION } from '../version';\nimport { hrTime, hrTimeDuration, hrTimeToSeconds } from '@opentelemetry/core';\n\nexport interface MetricReaderOptions {\n /**\n * Aggregation selector based on metric instrument types. If no views are\n * configured for a metric instrument, a per-metric-reader aggregation is\n * selected with this selector.\n *\n * <p> NOTE: the provided function MUST be pure\n */\n aggregationSelector?: AggregationSelector;\n /**\n * Aggregation temporality selector based on metric instrument types. If\n * not configured, cumulative is used for all instruments.\n *\n * <p> NOTE: the provided function MUST be pure\n */\n aggregationTemporalitySelector?: AggregationTemporalitySelector;\n /**\n * Cardinality selector based on metric instrument types. If not configured,\n * a default value is used.\n *\n * <p> NOTE: the provided function MUST be pure\n */\n cardinalitySelector?: CardinalitySelector;\n /**\n * **Note, this option is experimental**. Additional MetricProducers to use as a source of\n * aggregated metric data in addition to the SDK's metric data. The resource returned by\n * these MetricProducers is ignored; the SDK's resource will be used instead.\n * @experimental\n */\n metricProducers?: MetricProducer[];\n /**\n * The component type used for reporting self-observability SDK metrics.\n * @experimental This option is experimental and is subject to breaking changes in minor releases.\n */\n otelComponentType?: string;\n}\n\n/**\n * Reads metrics from the SDK. Implementations MUST follow the Metric Reader Specification as well as the requirements\n * listed in this interface. Consider extending {@link MetricReader} to get a specification-compliant base implementation\n * of this interface\n */\nexport interface IMetricReader {\n /**\n * Set the {@link MetricProducer} used by this instance. **This should only be called once by the\n * SDK and should be considered internal.**\n *\n * <p> NOTE: implementations MUST throw when called more than once\n *\n * @param metricProducer\n */\n setMetricProducer(metricProducer: MetricProducer): void;\n\n /**\n * Select the {@link AggregationOption} for the given {@link InstrumentType} for this\n * reader.\n *\n * <p> NOTE: implementations MUST be pure\n */\n selectAggregation(instrumentType: InstrumentType): AggregationOption;\n\n /**\n * Select the {@link AggregationTemporality} for the given\n * {@link InstrumentType} for this reader.\n *\n * <p> NOTE: implementations MUST be pure\n */\n selectAggregationTemporality(\n instrumentType: InstrumentType\n ): AggregationTemporality;\n\n /**\n * Select the cardinality limit for the given {@link InstrumentType} for this\n * reader.\n *\n * <p> NOTE: implementations MUST be pure\n */\n selectCardinalityLimit(instrumentType: InstrumentType): number;\n\n /**\n * Collect all metrics from the associated {@link MetricProducer}\n */\n collect(options?: CollectionOptions): Promise<CollectionResult>;\n\n /**\n * Shuts down the metric reader, the promise will reject after the optional timeout or resolve after completion.\n *\n * <p> NOTE: this operation MAY continue even after the promise rejects due to a timeout.\n * @param options options with timeout.\n */\n shutdown(options?: ShutdownOptions): Promise<void>;\n\n /**\n * Flushes metrics read by this reader, the promise will reject after the optional timeout or resolve after completion.\n *\n * <p> NOTE: this operation MAY continue even after the promise rejects due to a timeout.\n * @param options options with timeout.\n */\n forceFlush(options?: ForceFlushOptions): Promise<void>;\n}\n\n/**\n * A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global\n * control over metrics.\n */\nexport abstract class MetricReader implements IMetricReader {\n // Tracks the shutdown state.\n // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.\n private _shutdown = false;\n // Additional MetricProducers which will be combined with the SDK's output\n private _metricProducers: MetricProducer[];\n // MetricProducer used by this instance which produces metrics from the SDK\n private _sdkMetricProducer?: MetricProducer;\n // Metrics about the MetricReader itself\n private _selfObsMetrics: MetricReaderMetrics;\n private readonly _aggregationTemporalitySelector: AggregationTemporalitySelector;\n private readonly _aggregationSelector: AggregationSelector;\n private readonly _cardinalitySelector?: CardinalitySelector;\n private readonly _otelComponentType: string;\n\n constructor(options?: MetricReaderOptions) {\n this._aggregationSelector =\n options?.aggregationSelector ?? DEFAULT_AGGREGATION_SELECTOR;\n this._aggregationTemporalitySelector =\n options?.aggregationTemporalitySelector ??\n DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;\n this._metricProducers = options?.metricProducers ?? [];\n this._cardinalitySelector = options?.cardinalitySelector;\n this._otelComponentType =\n options?.otelComponentType ?? this.constructor.name;\n this._selfObsMetrics = new MetricReaderMetrics(\n this._otelComponentType,\n api.createNoopMeter()\n );\n }\n\n setMetricProducer(metricProducer: MetricProducer) {\n if (this._sdkMetricProducer) {\n // This check ensures the following requirement from the spec\n // (https://opentelemetry.io/docs/specs/otel/metrics/sdk/#metricreader):\n // > The SDK MUST NOT allow a `MetricReader` instance to be registered\n // > on more than one `MeterProvider` instance.\n //\n // So while the argument is a `MetricProducer`, the relevant user-level\n // error message is about the **MeterProvider**.\n throw new Error(\n 'MetricReader can not be bound to a MeterProvider again.'\n );\n }\n this._sdkMetricProducer = metricProducer;\n this.onInitialized();\n }\n\n _setSelfObsMeterProvider(meterProvider: api.MeterProvider): void {\n const meter = meterProvider.getMeter('@opentelemetry/sdk-metrics', VERSION);\n this._selfObsMetrics = new MetricReaderMetrics(\n this._otelComponentType,\n meter\n );\n }\n\n selectAggregation(instrumentType: InstrumentType): AggregationOption {\n return this._aggregationSelector(instrumentType);\n }\n\n selectAggregationTemporality(\n instrumentType: InstrumentType\n ): AggregationTemporality {\n return this._aggregationTemporalitySelector(instrumentType);\n }\n\n selectCardinalityLimit(instrumentType: InstrumentType): number {\n return this._cardinalitySelector\n ? this._cardinalitySelector(instrumentType)\n : 2000; // default value if no selector is provided\n }\n\n /**\n * Handle once the SDK has initialized this {@link MetricReader}\n * Overriding this method is optional.\n */\n protected onInitialized(): void {\n // Default implementation is empty.\n }\n\n /**\n * Handle a shutdown signal by the SDK.\n *\n * <p> For push exporters, this should shut down any intervals and close any open connections.\n * @protected\n */\n protected abstract onShutdown(): Promise<void>;\n\n /**\n * Handle a force flush signal by the SDK.\n *\n * <p> In all scenarios metrics should be collected via {@link collect()}.\n * <p> For push exporters, this should collect and report metrics.\n * @protected\n */\n protected abstract onForceFlush(): Promise<void>;\n\n async collect(options?: CollectionOptions): Promise<CollectionResult> {\n if (this._sdkMetricProducer === undefined) {\n throw new Error('MetricReader is not bound to a MetricProducer');\n }\n\n // Subsequent invocations to collect are not allowed. SDKs SHOULD return some failure for these calls.\n if (this._shutdown) {\n throw new Error('MetricReader is shutdown');\n }\n\n const startTime = hrTime();\n const [sdkCollectionResults, ...additionalCollectionResults] =\n await Promise.all([\n this._sdkMetricProducer.collect({\n timeoutMillis: options?.timeoutMillis,\n }),\n ...this._metricProducers.map(producer =>\n producer.collect({\n timeoutMillis: options?.timeoutMillis,\n })\n ),\n ]);\n const endTime = hrTime();\n\n // Merge the results, keeping the SDK's Resource\n const errors = sdkCollectionResults.errors.concat(\n additionalCollectionResults.flatMap(result => result.errors)\n );\n\n const collectDuration = hrTimeToSeconds(hrTimeDuration(startTime, endTime));\n this._selfObsMetrics.recordCollection(\n collectDuration,\n errors.length > 0\n ? ((errors[0] as Error).name ?? 'collect_error')\n : undefined\n );\n\n const resource = sdkCollectionResults.resourceMetrics.resource;\n const scopeMetrics =\n sdkCollectionResults.resourceMetrics.scopeMetrics.concat(\n additionalCollectionResults.flatMap(\n result => result.resourceMetrics.scopeMetrics\n )\n );\n return {\n resourceMetrics: {\n resource,\n scopeMetrics,\n },\n errors,\n };\n }\n\n async shutdown(options?: ShutdownOptions): Promise<void> {\n // Do not call shutdown again if it has already been called.\n if (this._shutdown) {\n api.diag.error('Cannot call shutdown twice.');\n return;\n }\n\n // No timeout if timeoutMillis is undefined or null.\n if (options?.timeoutMillis == null) {\n await this.onShutdown();\n } else {\n await callWithTimeout(this.onShutdown(), options.timeoutMillis);\n }\n\n this._shutdown = true;\n }\n\n async forceFlush(options?: ForceFlushOptions): Promise<void> {\n if (this._shutdown) {\n api.diag.warn('Cannot forceFlush on already shutdown MetricReader.');\n return;\n }\n\n // No timeout if timeoutMillis is undefined or null.\n if (options?.timeoutMillis == null) {\n await this.onForceFlush();\n return;\n }\n\n await callWithTimeout(this.onForceFlush(), options.timeoutMillis);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\n\nexport type Maybe<T> = T | undefined;\n\n/**\n * Converting the unordered attributes into unique identifier string.\n * @param attributes user provided unordered Attributes.\n */\nexport function hashAttributes(attributes: Attributes): string {\n let keys = Object.keys(attributes);\n if (keys.length === 0) return '';\n\n // Return a string that is stable on key orders.\n keys = keys.sort();\n return JSON.stringify(keys.map(key => [key, attributes[key]]));\n}\n\n/**\n * Converting the instrumentation scope object to a unique identifier string.\n * @param instrumentationScope\n */\nexport function instrumentationScopeId(\n instrumentationScope: InstrumentationScope\n): string {\n return `${instrumentationScope.name}:${instrumentationScope.version ?? ''}:${\n instrumentationScope.schemaUrl ?? ''\n }`;\n}\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n\nexport function setEquals(lhs: Set<unknown>, rhs: Set<unknown>): boolean {\n if (lhs.size !== rhs.size) {\n return false;\n }\n for (const item of lhs) {\n if (!rhs.has(item)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Binary search the sorted array to the find upper bound for the value.\n * @param arr\n * @param value\n * @returns\n */\nexport function binarySearchUB(arr: number[], value: number): number {\n let lo = 0;\n let hi = arr.length - 1;\n let ret = arr.length;\n\n while (hi >= lo) {\n const mid = lo + Math.trunc((hi - lo) / 2);\n if (arr[mid] < value) {\n lo = mid + 1;\n } else {\n ret = mid;\n hi = mid - 1;\n }\n }\n\n return ret;\n}\n\nexport function equalsCaseInsensitive(lhs: string, rhs: string): boolean {\n return lhs.toLowerCase() === rhs.toLowerCase();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { Aggregator } from '../aggregator';\nimport {\n SumAggregator,\n DropAggregator,\n LastValueAggregator,\n HistogramAggregator,\n ExponentialHistogramAggregator,\n} from '../aggregator';\nimport type { Accumulation } from '../aggregator/types';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport type { Maybe } from '../utils';\nimport { InstrumentType } from '../export/MetricData';\n\n/**\n * Configures how measurements are combined into metrics for views.\n *\n * Aggregation provides a set of built-in aggregations via static methods.\n */\nexport interface Aggregation {\n createAggregator(\n instrument: InstrumentDescriptor\n ): Aggregator<Maybe<Accumulation>>;\n}\n\n/**\n * The default drop aggregation.\n */\nexport class DropAggregation implements Aggregation {\n private static DEFAULT_INSTANCE = new DropAggregator();\n createAggregator(_instrument: InstrumentDescriptor) {\n return DropAggregation.DEFAULT_INSTANCE;\n }\n}\n\n/**\n * The default sum aggregation.\n */\nexport class SumAggregation implements Aggregation {\n private static MONOTONIC_INSTANCE = new SumAggregator(true);\n private static NON_MONOTONIC_INSTANCE = new SumAggregator(false);\n createAggregator(instrument: InstrumentDescriptor) {\n switch (instrument.type) {\n case InstrumentType.COUNTER:\n case InstrumentType.OBSERVABLE_COUNTER:\n case InstrumentType.HISTOGRAM: {\n return SumAggregation.MONOTONIC_INSTANCE;\n }\n default: {\n return SumAggregation.NON_MONOTONIC_INSTANCE;\n }\n }\n }\n}\n\n/**\n * The default last value aggregation.\n */\nexport class LastValueAggregation implements Aggregation {\n private static DEFAULT_INSTANCE = new LastValueAggregator();\n createAggregator(_instrument: InstrumentDescriptor) {\n return LastValueAggregation.DEFAULT_INSTANCE;\n }\n}\n\n/**\n * The default histogram aggregation.\n\n */\nexport class HistogramAggregation implements Aggregation {\n private static DEFAULT_INSTANCE = new HistogramAggregator(\n [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000],\n true\n );\n createAggregator(_instrument: InstrumentDescriptor) {\n return HistogramAggregation.DEFAULT_INSTANCE;\n }\n}\n\n/**\n * The explicit bucket histogram aggregation.\n */\nexport class ExplicitBucketHistogramAggregation implements Aggregation {\n private _boundaries: number[];\n private readonly _recordMinMax: boolean;\n\n /**\n * @param boundaries the bucket boundaries of the histogram aggregation\n * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.\n */\n constructor(boundaries: number[], recordMinMax = true) {\n if (boundaries == null) {\n throw new Error(\n 'ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array'\n );\n }\n // Copy the boundaries array for modification.\n boundaries = boundaries.concat();\n // We need to an ordered set to be able to correctly compute count for each\n // boundary since we'll iterate on each in order.\n boundaries = boundaries.sort((a, b) => a - b);\n // Remove all Infinity from the boundaries.\n const minusInfinityIndex = boundaries.lastIndexOf(-Infinity);\n let infinityIndex: number | undefined = boundaries.indexOf(Infinity);\n if (infinityIndex === -1) {\n infinityIndex = undefined;\n }\n this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex);\n this._recordMinMax = recordMinMax;\n }\n\n createAggregator(_instrument: InstrumentDescriptor) {\n return new HistogramAggregator(this._boundaries, this._recordMinMax);\n }\n}\n\nexport class ExponentialHistogramAggregation implements Aggregation {\n private readonly _maxSize: number;\n private readonly _recordMinMax: boolean;\n\n constructor(maxSize = 160, recordMinMax = true) {\n this._maxSize = maxSize;\n this._recordMinMax = recordMinMax;\n }\n createAggregator(_instrument: InstrumentDescriptor) {\n return new ExponentialHistogramAggregator(\n this._maxSize,\n this._recordMinMax\n );\n }\n}\n\n/**\n * The default aggregation.\n */\nexport class DefaultAggregation implements Aggregation {\n private _resolve(instrument: InstrumentDescriptor): Aggregation {\n // cast to unknown to disable complaints on the (unreachable) fallback.\n switch (instrument.type as unknown) {\n case InstrumentType.COUNTER:\n case InstrumentType.UP_DOWN_COUNTER:\n case InstrumentType.OBSERVABLE_COUNTER:\n case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: {\n return SUM_AGGREGATION;\n }\n case InstrumentType.GAUGE:\n case InstrumentType.OBSERVABLE_GAUGE: {\n return LAST_VALUE_AGGREGATION;\n }\n case InstrumentType.HISTOGRAM: {\n if (instrument.advice.explicitBucketBoundaries) {\n return new ExplicitBucketHistogramAggregation(\n instrument.advice.explicitBucketBoundaries\n );\n }\n return HISTOGRAM_AGGREGATION;\n }\n }\n api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`);\n return DROP_AGGREGATION;\n }\n\n createAggregator(\n instrument: InstrumentDescriptor\n ): Aggregator<Maybe<Accumulation>> {\n return this._resolve(instrument).createAggregator(instrument);\n }\n}\n\nexport const DROP_AGGREGATION = new DropAggregation();\nexport const SUM_AGGREGATION = new SumAggregation();\nexport const LAST_VALUE_AGGREGATION = new LastValueAggregation();\nexport const HISTOGRAM_AGGREGATION = new HistogramAggregation();\nexport const EXPONENTIAL_HISTOGRAM_AGGREGATION =\n new ExponentialHistogramAggregation();\nexport const DEFAULT_AGGREGATION = new DefaultAggregation();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes } from '@opentelemetry/api';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { MetricData } from '../export/MetricData';\nimport type { Maybe } from '../utils';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\n/** The kind of aggregator. */\nexport enum AggregatorKind {\n DROP,\n SUM,\n LAST_VALUE,\n HISTOGRAM,\n EXPONENTIAL_HISTOGRAM,\n}\n\n/** DataPoint value type for SumAggregation. */\nexport type Sum = number;\n\n/** DataPoint value type for LastValueAggregation. */\nexport type LastValue = number;\n\n/** DataPoint value type for HistogramAggregation. */\nexport interface Histogram {\n /**\n * Buckets are implemented using two different arrays:\n * - boundaries: contains every finite bucket boundary, which are inclusive upper bounds\n * - counts: contains event counts for each bucket\n *\n * Note that we'll always have n+1 buckets, where n is the number of boundaries.\n * This is because we need to count events that are higher than the upper boundary.\n *\n * Example: if we measure the values: [5, 30, 5, 40, 5, 15, 15, 15, 25]\n * with the boundaries [ 10, 20, 30 ], we will have the following state:\n *\n * buckets: {\n *\tboundaries: [10, 20, 30],\n *\tcounts: [3, 3, 2, 1],\n * }\n */\n buckets: {\n boundaries: number[];\n counts: number[];\n };\n sum?: number;\n count: number;\n min?: number;\n max?: number;\n}\n\n/** DataPoint value type for ExponentialHistogramAggregation. */\nexport interface ExponentialHistogram {\n count: number;\n sum?: number;\n scale: number;\n zeroCount: number;\n positive: {\n offset: number;\n bucketCounts: number[];\n };\n negative: {\n offset: number;\n bucketCounts: number[];\n };\n min?: number;\n max?: number;\n}\n\n/**\n * An Aggregator accumulation state.\n */\nexport interface Accumulation {\n setStartTime(startTime: HrTime): void;\n record(value: number): void;\n}\n\nexport type AccumulationRecord<T> = [Attributes, T];\n\n/**\n * Base interface for aggregators. Aggregators are responsible for holding\n * aggregated values and taking a snapshot of these values upon export.\n */\nexport interface Aggregator<T> {\n /** The kind of the aggregator. */\n kind: AggregatorKind;\n\n /**\n * Create a clean state of accumulation.\n */\n createAccumulation(startTime: HrTime): T;\n\n /**\n * Returns the result of the merge of the given accumulations.\n *\n * This should always assume that the accumulations do not overlap and merge together for a new\n * cumulative report.\n *\n * @param previous the previously captured accumulation\n * @param delta the newly captured (delta) accumulation\n * @returns the result of the merge of the given accumulations\n */\n merge(previous: T, delta: T): T;\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n *\n * @param previous the previously captured accumulation\n * @param current the newly captured (cumulative) accumulation\n * @returns The resulting delta accumulation\n */\n diff(previous: T, current: T): T;\n\n /**\n * Returns the {@link MetricData} that this {@link Aggregator} will produce.\n *\n * @param descriptor the metric descriptor.\n * @param aggregationTemporality the temporality of the resulting {@link MetricData}\n * @param accumulationByAttributes the array of attributes and accumulation pairs.\n * @param endTime the end time of the metric data.\n * @return the {@link MetricData} that this {@link Aggregator} will produce.\n */\n toMetricData(\n descriptor: InstrumentDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<T>[],\n endTime: HrTime\n ): Maybe<MetricData>;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { MetricData, MetricDescriptor } from '../export/MetricData';\nimport type { Maybe } from '../utils';\nimport type { Aggregator, AccumulationRecord } from './types';\nimport { AggregatorKind } from './types';\n\n/** Basic aggregator for None which keeps no recorded value. */\nexport class DropAggregator implements Aggregator<undefined> {\n kind: AggregatorKind.DROP = AggregatorKind.DROP;\n\n createAccumulation() {\n return undefined;\n }\n\n merge(_previous: undefined, _delta: undefined) {\n return undefined;\n }\n\n diff(_previous: undefined, _current: undefined) {\n return undefined;\n }\n\n toMetricData(\n _descriptor: MetricDescriptor,\n _aggregationTemporality: AggregationTemporality,\n _accumulationByAttributes: AccumulationRecord<undefined>[],\n _endTime: HrTime\n ): Maybe<MetricData> {\n return undefined;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Accumulation, AccumulationRecord, Aggregator } from './types';\nimport { AggregatorKind } from './types';\nimport type { HistogramMetricData } from '../export/MetricData';\nimport { DataPointType, InstrumentType } from '../export/MetricData';\nimport type { HrTime } from '@opentelemetry/api';\nimport type { Maybe } from '../utils';\nimport { binarySearchUB } from '../utils';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\n/**\n * Internal value type for HistogramAggregation.\n * Differs from the exported type as undefined sum/min/max complicate arithmetic\n * performed by this aggregation, but are required to be undefined in the exported types.\n */\ninterface InternalHistogram {\n buckets: {\n boundaries: number[];\n counts: number[];\n };\n sum: number;\n count: number;\n hasMinMax: boolean;\n min: number;\n max: number;\n}\n\nfunction createNewEmptyCheckpoint(boundaries: number[]): InternalHistogram {\n const counts = boundaries.map(() => 0);\n counts.push(0);\n return {\n buckets: {\n boundaries,\n counts,\n },\n sum: 0,\n count: 0,\n hasMinMax: false,\n min: Infinity,\n max: -Infinity,\n };\n}\n\nexport class HistogramAccumulation implements Accumulation {\n public startTime;\n private readonly _boundaries;\n private _recordMinMax;\n private _current;\n\n constructor(\n startTime: HrTime,\n boundaries: number[],\n recordMinMax = true,\n current: InternalHistogram = createNewEmptyCheckpoint(boundaries)\n ) {\n this.startTime = startTime;\n this._boundaries = boundaries;\n this._recordMinMax = recordMinMax;\n this._current = current;\n }\n\n record(value: number): void {\n // NaN does not fall into any bucket, is not zero and should not be counted,\n // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do.\n if (Number.isNaN(value)) {\n return;\n }\n\n this._current.count += 1;\n this._current.sum += value;\n\n if (this._recordMinMax) {\n this._current.min = Math.min(value, this._current.min);\n this._current.max = Math.max(value, this._current.max);\n this._current.hasMinMax = true;\n }\n\n const idx = binarySearchUB(this._boundaries, value);\n this._current.buckets.counts[idx] += 1;\n }\n\n setStartTime(startTime: HrTime): void {\n this.startTime = startTime;\n }\n\n toPointValue(): InternalHistogram {\n return this._current;\n }\n}\n\n/**\n * Basic aggregator which observes events and counts them in pre-defined buckets\n * and provides the total sum and count of all observations.\n */\nexport class HistogramAggregator implements Aggregator<HistogramAccumulation> {\n public kind: AggregatorKind.HISTOGRAM = AggregatorKind.HISTOGRAM;\n private readonly _boundaries: number[];\n private readonly _recordMinMax: boolean;\n\n /**\n * @param _boundaries sorted upper bounds of recorded values.\n * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.\n */\n constructor(boundaries: number[], recordMinMax: boolean) {\n this._boundaries = boundaries;\n this._recordMinMax = recordMinMax;\n }\n\n createAccumulation(startTime: HrTime) {\n return new HistogramAccumulation(\n startTime,\n this._boundaries,\n this._recordMinMax\n );\n }\n\n /**\n * Return the result of the merge of two histogram accumulations. As long as one Aggregator\n * instance produces all Accumulations with constant boundaries we don't need to worry about\n * merging accumulations with different boundaries.\n */\n merge(\n previous: HistogramAccumulation,\n delta: HistogramAccumulation\n ): HistogramAccumulation {\n const previousValue = previous.toPointValue();\n const deltaValue = delta.toPointValue();\n\n const previousCounts = previousValue.buckets.counts;\n const deltaCounts = deltaValue.buckets.counts;\n\n const mergedCounts = new Array(previousCounts.length);\n for (let idx = 0; idx < previousCounts.length; idx++) {\n mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx];\n }\n\n let min = Infinity;\n let max = -Infinity;\n\n if (this._recordMinMax) {\n if (previousValue.hasMinMax && deltaValue.hasMinMax) {\n min = Math.min(previousValue.min, deltaValue.min);\n max = Math.max(previousValue.max, deltaValue.max);\n } else if (previousValue.hasMinMax) {\n min = previousValue.min;\n max = previousValue.max;\n } else if (deltaValue.hasMinMax) {\n min = deltaValue.min;\n max = deltaValue.max;\n }\n }\n\n return new HistogramAccumulation(\n previous.startTime,\n previousValue.buckets.boundaries,\n this._recordMinMax,\n {\n buckets: {\n boundaries: previousValue.buckets.boundaries,\n counts: mergedCounts,\n },\n count: previousValue.count + deltaValue.count,\n sum: previousValue.sum + deltaValue.sum,\n hasMinMax:\n this._recordMinMax &&\n (previousValue.hasMinMax || deltaValue.hasMinMax),\n min: min,\n max: max,\n }\n );\n }\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n */\n diff(\n previous: HistogramAccumulation,\n current: HistogramAccumulation\n ): HistogramAccumulation {\n const previousValue = previous.toPointValue();\n const currentValue = current.toPointValue();\n\n const previousCounts = previousValue.buckets.counts;\n const currentCounts = currentValue.buckets.counts;\n\n const diffedCounts = new Array(previousCounts.length);\n for (let idx = 0; idx < previousCounts.length; idx++) {\n diffedCounts[idx] = currentCounts[idx] - previousCounts[idx];\n }\n\n return new HistogramAccumulation(\n current.startTime,\n previousValue.buckets.boundaries,\n this._recordMinMax,\n {\n buckets: {\n boundaries: previousValue.buckets.boundaries,\n counts: diffedCounts,\n },\n count: currentValue.count - previousValue.count,\n sum: currentValue.sum - previousValue.sum,\n hasMinMax: false,\n min: Infinity,\n max: -Infinity,\n }\n );\n }\n\n toMetricData(\n descriptor: InstrumentDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<HistogramAccumulation>[],\n endTime: HrTime\n ): Maybe<HistogramMetricData> {\n return {\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.HISTOGRAM,\n dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {\n const pointValue = accumulation.toPointValue();\n\n // determine if instrument allows negative values.\n const allowsNegativeValues =\n descriptor.type === InstrumentType.GAUGE ||\n descriptor.type === InstrumentType.UP_DOWN_COUNTER ||\n descriptor.type === InstrumentType.OBSERVABLE_GAUGE ||\n descriptor.type === InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;\n\n return {\n attributes,\n startTime: accumulation.startTime,\n endTime,\n value: {\n min: pointValue.hasMinMax ? pointValue.min : undefined,\n max: pointValue.hasMinMax ? pointValue.max : undefined,\n sum: !allowsNegativeValues ? pointValue.sum : undefined,\n buckets: pointValue.buckets,\n count: pointValue.count,\n },\n };\n }),\n };\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n ExponentialHistogram,\n} from './types';\nimport { AggregatorKind } from './types';\nimport type { ExponentialHistogramMetricData } from '../export/MetricData';\nimport { DataPointType, InstrumentType } from '../export/MetricData';\nimport type { HrTime } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { Maybe } from '../utils';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { Buckets } from './exponential-histogram/Buckets';\nimport { getMapping } from './exponential-histogram/mapping/getMapping';\nimport type { Mapping } from './exponential-histogram/mapping/types';\nimport { nextGreaterSquare } from './exponential-histogram/util';\n\n/**\n * Internal value type for ExponentialHistogramAggregation.\n * Differs from the exported type as undefined sum/min/max complicate arithmetic\n * performed by this aggregation, but are required to be undefined in the exported types.\n */\ninterface InternalHistogram extends ExponentialHistogram {\n hasMinMax: boolean;\n min: number;\n max: number;\n sum: number;\n}\n\n// HighLow is a utility class used for computing a common scale for\n// two exponential histogram accumulations\nclass HighLow {\n static combine(h1: HighLow, h2: HighLow): HighLow {\n return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high));\n }\n\n public low: number;\n public high: number;\n constructor(low: number, high: number) {\n this.low = low;\n this.high = high;\n }\n}\n\nconst MAX_SCALE = 20;\nconst DEFAULT_MAX_SIZE = 160;\nconst MIN_MAX_SIZE = 2;\n\nexport class ExponentialHistogramAccumulation implements Accumulation {\n public startTime;\n private _maxSize;\n private _recordMinMax;\n private _sum;\n private _count;\n private _zeroCount;\n private _min;\n private _max;\n private _positive;\n private _negative;\n private _mapping;\n\n constructor(\n startTime: HrTime,\n maxSize = DEFAULT_MAX_SIZE,\n recordMinMax = true,\n sum = 0,\n count = 0,\n zeroCount = 0,\n min = Number.POSITIVE_INFINITY,\n max = Number.NEGATIVE_INFINITY,\n positive = new Buckets(),\n negative = new Buckets(),\n mapping: Mapping = getMapping(MAX_SCALE)\n ) {\n this.startTime = startTime;\n this._maxSize = maxSize;\n this._recordMinMax = recordMinMax;\n this._sum = sum;\n this._count = count;\n this._zeroCount = zeroCount;\n this._min = min;\n this._max = max;\n this._positive = positive;\n this._negative = negative;\n this._mapping = mapping;\n\n if (this._maxSize < MIN_MAX_SIZE) {\n diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \\\n changing to the minimum size of: ${MIN_MAX_SIZE}`);\n this._maxSize = MIN_MAX_SIZE;\n }\n }\n\n /**\n * record updates a histogram with a single count\n * @param {Number} value\n */\n record(value: number) {\n this.updateByIncrement(value, 1);\n }\n\n /**\n * Sets the start time for this accumulation\n * @param {HrTime} startTime\n */\n setStartTime(startTime: HrTime): void {\n this.startTime = startTime;\n }\n\n /**\n * Returns the datapoint representation of this accumulation\n * @param {HrTime} startTime\n */\n toPointValue(): InternalHistogram {\n return {\n hasMinMax: this._recordMinMax,\n min: this.min,\n max: this.max,\n sum: this.sum,\n positive: {\n offset: this.positive.offset,\n bucketCounts: this.positive.counts(),\n },\n negative: {\n offset: this.negative.offset,\n bucketCounts: this.negative.counts(),\n },\n count: this.count,\n scale: this.scale,\n zeroCount: this.zeroCount,\n };\n }\n\n /**\n * @returns {Number} The sum of values recorded by this accumulation\n */\n get sum(): number {\n return this._sum;\n }\n\n /**\n * @returns {Number} The minimum value recorded by this accumulation\n */\n get min(): number {\n return this._min;\n }\n\n /**\n * @returns {Number} The maximum value recorded by this accumulation\n */\n get max(): number {\n return this._max;\n }\n\n /**\n * @returns {Number} The count of values recorded by this accumulation\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * @returns {Number} The number of 0 values recorded by this accumulation\n */\n get zeroCount(): number {\n return this._zeroCount;\n }\n\n /**\n * @returns {Number} The scale used by this accumulation\n */\n get scale(): number {\n if (this._count === this._zeroCount) {\n // all zeros! scale doesn't matter, use zero\n return 0;\n }\n return this._mapping.scale;\n }\n\n /**\n * positive holds the positive values\n * @returns {Buckets}\n */\n get positive(): Buckets {\n return this._positive;\n }\n\n /**\n * negative holds the negative values by their absolute value\n * @returns {Buckets}\n */\n get negative(): Buckets {\n return this._negative;\n }\n\n /**\n * updateByIncr supports updating a histogram with a non-negative\n * increment.\n * @param value\n * @param increment\n */\n updateByIncrement(value: number, increment: number) {\n // Drop NaN and ±Infinity: they belong in no bucket, are not zero, and would\n // corrupt sum/min/max.\n if (!Number.isFinite(value)) {\n return;\n }\n\n if (value > this._max) {\n this._max = value;\n }\n if (value < this._min) {\n this._min = value;\n }\n\n this._count += increment;\n\n if (value === 0) {\n this._zeroCount += increment;\n return;\n }\n\n this._sum += value * increment;\n\n if (value > 0) {\n this._updateBuckets(this._positive, value, increment);\n } else {\n this._updateBuckets(this._negative, -value, increment);\n }\n }\n\n /**\n * merge combines data from previous value into self\n * @param {ExponentialHistogramAccumulation} previous\n */\n merge(previous: ExponentialHistogramAccumulation) {\n if (this._count === 0) {\n this._min = previous.min;\n this._max = previous.max;\n } else if (previous.count !== 0) {\n if (previous.min < this.min) {\n this._min = previous.min;\n }\n if (previous.max > this.max) {\n this._max = previous.max;\n }\n }\n\n this.startTime = previous.startTime;\n this._sum += previous.sum;\n this._count += previous.count;\n this._zeroCount += previous.zeroCount;\n\n const minScale = this._minScale(previous);\n\n this._downscale(this.scale - minScale);\n\n this._mergeBuckets(this.positive, previous, previous.positive, minScale);\n this._mergeBuckets(this.negative, previous, previous.negative, minScale);\n }\n\n /**\n * diff subtracts other from self\n * @param {ExponentialHistogramAccumulation} other\n */\n diff(other: ExponentialHistogramAccumulation) {\n this._min = Infinity;\n this._max = -Infinity;\n this._sum -= other.sum;\n this._count -= other.count;\n this._zeroCount -= other.zeroCount;\n\n const minScale = this._minScale(other);\n\n this._downscale(this.scale - minScale);\n\n this._diffBuckets(this.positive, other, other.positive, minScale);\n this._diffBuckets(this.negative, other, other.negative, minScale);\n }\n\n /**\n * clone returns a deep copy of self\n * @returns {ExponentialHistogramAccumulation}\n */\n clone(): ExponentialHistogramAccumulation {\n return new ExponentialHistogramAccumulation(\n this.startTime,\n this._maxSize,\n this._recordMinMax,\n this._sum,\n this._count,\n this._zeroCount,\n this._min,\n this._max,\n this.positive.clone(),\n this.negative.clone(),\n this._mapping\n );\n }\n\n /**\n * _updateBuckets maps the incoming value to a bucket index for the current\n * scale. If the bucket index is outside of the range of the backing array,\n * it will rescale the backing array and update the mapping for the new scale.\n */\n private _updateBuckets(buckets: Buckets, value: number, increment: number) {\n let index = this._mapping.mapToIndex(value);\n\n // rescale the mapping if needed\n let rescalingNeeded = false;\n let high = 0;\n let low = 0;\n\n if (buckets.length === 0) {\n buckets.indexStart = index;\n buckets.indexEnd = buckets.indexStart;\n buckets.indexBase = buckets.indexStart;\n } else if (\n index < buckets.indexStart &&\n buckets.indexEnd - index >= this._maxSize\n ) {\n rescalingNeeded = true;\n low = index;\n high = buckets.indexEnd;\n } else if (\n index > buckets.indexEnd &&\n index - buckets.indexStart >= this._maxSize\n ) {\n rescalingNeeded = true;\n low = buckets.indexStart;\n high = index;\n }\n\n // rescale and compute index at new scale\n if (rescalingNeeded) {\n const change = this._changeScale(high, low);\n this._downscale(change);\n index = this._mapping.mapToIndex(value);\n }\n\n this._incrementIndexBy(buckets, index, increment);\n }\n\n /**\n * _incrementIndexBy increments the count of the bucket specified by `index`.\n * If the index is outside of the range [buckets.indexStart, buckets.indexEnd]\n * the boundaries of the backing array will be adjusted and more buckets will\n * be added if needed.\n */\n private _incrementIndexBy(\n buckets: Buckets,\n index: number,\n increment: number\n ) {\n if (increment === 0) {\n // nothing to do for a zero increment, can happen during a merge operation\n return;\n }\n\n if (buckets.length === 0) {\n buckets.indexStart = buckets.indexEnd = buckets.indexBase = index;\n }\n\n if (index < buckets.indexStart) {\n const span = buckets.indexEnd - index;\n if (span >= buckets.backing.length) {\n this._grow(buckets, span + 1);\n }\n buckets.indexStart = index;\n } else if (index > buckets.indexEnd) {\n const span = index - buckets.indexStart;\n if (span >= buckets.backing.length) {\n this._grow(buckets, span + 1);\n }\n buckets.indexEnd = index;\n }\n\n let bucketIndex = index - buckets.indexBase;\n if (bucketIndex < 0) {\n bucketIndex += buckets.backing.length;\n }\n buckets.incrementBucket(bucketIndex, increment);\n }\n\n /**\n * grow resizes the backing array by doubling in size up to maxSize.\n * This extends the array with a bunch of zeros and copies the\n * existing counts to the same position.\n */\n private _grow(buckets: Buckets, needed: number) {\n const size = buckets.backing.length;\n const bias = buckets.indexBase - buckets.indexStart;\n const oldPositiveLimit = size - bias;\n let newSize = nextGreaterSquare(needed);\n if (newSize > this._maxSize) {\n newSize = this._maxSize;\n }\n const newPositiveLimit = newSize - bias;\n buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit);\n }\n\n /**\n * _changeScale computes how much downscaling is needed by shifting the\n * high and low values until they are separated by no more than size.\n */\n private _changeScale(high: number, low: number): number {\n let change = 0;\n while (high - low >= this._maxSize) {\n high >>= 1;\n low >>= 1;\n change++;\n }\n return change;\n }\n\n /**\n * _downscale subtracts `change` from the current mapping scale.\n */\n private _downscale(change: number) {\n if (change === 0) {\n return;\n }\n if (change < 0) {\n // Note: this should be impossible. If we get here it's because\n // there is a bug in the implementation.\n throw new Error(`impossible change of scale: ${this.scale}`);\n }\n const newScale = this._mapping.scale - change;\n\n this._positive.downscale(change);\n this._negative.downscale(change);\n\n this._mapping = getMapping(newScale);\n }\n\n /**\n * _minScale is used by diff and merge to compute an ideal combined scale\n */\n private _minScale(other: ExponentialHistogramAccumulation): number {\n const minScale = Math.min(this.scale, other.scale);\n\n const highLowPos = HighLow.combine(\n this._highLowAtScale(this.positive, this.scale, minScale),\n this._highLowAtScale(other.positive, other.scale, minScale)\n );\n\n const highLowNeg = HighLow.combine(\n this._highLowAtScale(this.negative, this.scale, minScale),\n this._highLowAtScale(other.negative, other.scale, minScale)\n );\n\n return Math.min(\n minScale - this._changeScale(highLowPos.high, highLowPos.low),\n minScale - this._changeScale(highLowNeg.high, highLowNeg.low)\n );\n }\n\n /**\n * _highLowAtScale is used by diff and merge to compute an ideal combined scale.\n */\n private _highLowAtScale(\n buckets: Buckets,\n currentScale: number,\n newScale: number\n ): HighLow {\n if (buckets.length === 0) {\n return new HighLow(0, -1);\n }\n const shift = currentScale - newScale;\n return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift);\n }\n\n /**\n * _mergeBuckets translates index values from another histogram and\n * adds the values into the corresponding buckets of this histogram.\n */\n private _mergeBuckets(\n ours: Buckets,\n other: ExponentialHistogramAccumulation,\n theirs: Buckets,\n scale: number\n ) {\n const theirOffset = theirs.offset;\n const theirChange = other.scale - scale;\n\n for (let i = 0; i < theirs.length; i++) {\n this._incrementIndexBy(\n ours,\n (theirOffset + i) >> theirChange,\n theirs.at(i)\n );\n }\n }\n\n /**\n * _diffBuckets translates index values from another histogram and\n * subtracts the values in the corresponding buckets of this histogram.\n */\n private _diffBuckets(\n ours: Buckets,\n other: ExponentialHistogramAccumulation,\n theirs: Buckets,\n scale: number\n ) {\n const theirOffset = theirs.offset;\n const theirChange = other.scale - scale;\n\n for (let i = 0; i < theirs.length; i++) {\n const ourIndex = (theirOffset + i) >> theirChange;\n let bucketIndex = ourIndex - ours.indexBase;\n if (bucketIndex < 0) {\n bucketIndex += ours.backing.length;\n }\n ours.decrementBucket(bucketIndex, theirs.at(i));\n }\n\n ours.trim();\n }\n}\n\n/**\n * Aggregator for ExponentialHistogramAccumulations\n */\nexport class ExponentialHistogramAggregator\n implements Aggregator<ExponentialHistogramAccumulation>\n{\n public kind: AggregatorKind.EXPONENTIAL_HISTOGRAM =\n AggregatorKind.EXPONENTIAL_HISTOGRAM;\n\n readonly _maxSize: number;\n private readonly _recordMinMax: boolean;\n /**\n * @param _maxSize Maximum number of buckets for each of the positive\n * and negative ranges, exclusive of the zero-bucket.\n * @param _recordMinMax If set to true, min and max will be recorded.\n * Otherwise, min and max will not be recorded.\n */\n constructor(maxSize: number, recordMinMax: boolean) {\n this._maxSize = maxSize;\n this._recordMinMax = recordMinMax;\n }\n\n createAccumulation(startTime: HrTime) {\n return new ExponentialHistogramAccumulation(\n startTime,\n this._maxSize,\n this._recordMinMax\n );\n }\n\n /**\n * Return the result of the merge of two exponential histogram accumulations.\n */\n merge(\n previous: ExponentialHistogramAccumulation,\n delta: ExponentialHistogramAccumulation\n ): ExponentialHistogramAccumulation {\n const result = delta.clone();\n result.merge(previous);\n\n return result;\n }\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n */\n diff(\n previous: ExponentialHistogramAccumulation,\n current: ExponentialHistogramAccumulation\n ): ExponentialHistogramAccumulation {\n const result = current.clone();\n result.diff(previous);\n\n return result;\n }\n\n toMetricData(\n descriptor: InstrumentDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<ExponentialHistogramAccumulation>[],\n endTime: HrTime\n ): Maybe<ExponentialHistogramMetricData> {\n return {\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.EXPONENTIAL_HISTOGRAM,\n dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {\n const pointValue = accumulation.toPointValue();\n\n // determine if instrument allows negative values.\n const allowsNegativeValues =\n descriptor.type === InstrumentType.GAUGE ||\n descriptor.type === InstrumentType.UP_DOWN_COUNTER ||\n descriptor.type === InstrumentType.OBSERVABLE_GAUGE ||\n descriptor.type === InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;\n\n return {\n attributes,\n startTime: accumulation.startTime,\n endTime,\n value: {\n min: pointValue.hasMinMax ? pointValue.min : undefined,\n max: pointValue.hasMinMax ? pointValue.max : undefined,\n sum: !allowsNegativeValues ? pointValue.sum : undefined,\n positive: {\n offset: pointValue.positive.offset,\n bucketCounts: pointValue.positive.bucketCounts,\n },\n negative: {\n offset: pointValue.negative.offset,\n bucketCounts: pointValue.negative.bucketCounts,\n },\n count: pointValue.count,\n scale: pointValue.scale,\n zeroCount: pointValue.zeroCount,\n },\n };\n }),\n };\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport class Buckets {\n public backing;\n public indexBase;\n public indexStart;\n public indexEnd;\n /**\n * The term index refers to the number of the exponential histogram bucket\n * used to determine its boundaries. The lower boundary of a bucket is\n * determined by base ** index and the upper boundary of a bucket is\n * determined by base ** (index + 1). index values are signed to account\n * for values less than or equal to 1.\n *\n * indexBase is the index of the 0th position in the\n * backing array, i.e., backing[0] is the count\n * in the bucket with index `indexBase`.\n *\n * indexStart is the smallest index value represented\n * in the backing array.\n *\n * indexEnd is the largest index value represented in\n * the backing array.\n */\n constructor(\n backing = new BucketsBacking(),\n indexBase = 0,\n indexStart = 0,\n indexEnd = 0\n ) {\n this.backing = backing;\n this.indexBase = indexBase;\n this.indexStart = indexStart;\n this.indexEnd = indexEnd;\n }\n\n /**\n * Offset is the bucket index of the smallest entry in the counts array\n * @returns {number}\n */\n get offset(): number {\n return this.indexStart;\n }\n\n /**\n * Buckets is a view into the backing array.\n * @returns {number}\n */\n get length(): number {\n if (this.backing.length === 0) {\n return 0;\n }\n\n if (this.indexEnd === this.indexStart && this.at(0) === 0) {\n return 0;\n }\n\n return this.indexEnd - this.indexStart + 1;\n }\n\n /**\n * An array of counts, where count[i] carries the count\n * of the bucket at index (offset+i). count[i] is the count of\n * values greater than base^(offset+i) and less than or equal to\n * base^(offset+i+1).\n * @returns {number} The logical counts based on the backing array\n */\n counts(): number[] {\n return Array.from({ length: this.length }, (_, i) => this.at(i));\n }\n\n /**\n * At returns the count of the bucket at a position in the logical\n * array of counts.\n * @param position\n * @returns {number}\n */\n at(position: number): number {\n const bias = this.indexBase - this.indexStart;\n if (position < bias) {\n position += this.backing.length;\n }\n\n position -= bias;\n return this.backing.countAt(position);\n }\n\n /**\n * incrementBucket increments the backing array index by `increment`\n * @param bucketIndex\n * @param increment\n */\n incrementBucket(bucketIndex: number, increment: number) {\n this.backing.increment(bucketIndex, increment);\n }\n\n /**\n * decrementBucket decrements the backing array index by `decrement`\n * if decrement is greater than the current value, it's set to 0.\n * @param bucketIndex\n * @param decrement\n */\n decrementBucket(bucketIndex: number, decrement: number) {\n this.backing.decrement(bucketIndex, decrement);\n }\n\n /**\n * trim removes leading and / or trailing zero buckets (which can occur\n * after diffing two histos) and rotates the backing array so that the\n * smallest non-zero index is in the 0th position of the backing array\n */\n trim() {\n for (let i = 0; i < this.length; i++) {\n if (this.at(i) !== 0) {\n this.indexStart += i;\n break;\n } else if (i === this.length - 1) {\n //the entire array is zeroed out\n this.indexStart = this.indexEnd = this.indexBase = 0;\n return;\n }\n }\n\n for (let i = this.length - 1; i >= 0; i--) {\n if (this.at(i) !== 0) {\n this.indexEnd -= this.length - i - 1;\n break;\n }\n }\n\n this._rotate();\n }\n\n /**\n * downscale first rotates, then collapses 2**`by`-to-1 buckets.\n * @param by\n */\n downscale(by: number) {\n this._rotate();\n\n const size = 1 + this.indexEnd - this.indexStart;\n const each = 1 << by;\n let inpos = 0;\n let outpos = 0;\n\n for (let pos = this.indexStart; pos <= this.indexEnd; ) {\n let mod = pos % each;\n if (mod < 0) {\n mod += each;\n }\n for (let i = mod; i < each && inpos < size; i++) {\n this._relocateBucket(outpos, inpos);\n inpos++;\n pos++;\n }\n outpos++;\n }\n\n this.indexStart >>= by;\n this.indexEnd >>= by;\n this.indexBase = this.indexStart;\n }\n\n /**\n * Clone returns a deep copy of Buckets\n * @returns {Buckets}\n */\n clone(): Buckets {\n return new Buckets(\n this.backing.clone(),\n this.indexBase,\n this.indexStart,\n this.indexEnd\n );\n }\n\n /**\n * _rotate shifts the backing array contents so that indexStart ==\n * indexBase to simplify the downscale logic.\n */\n private _rotate() {\n const bias = this.indexBase - this.indexStart;\n\n if (bias === 0) {\n return;\n } else if (bias > 0) {\n this.backing.reverse(0, this.backing.length);\n this.backing.reverse(0, bias);\n this.backing.reverse(bias, this.backing.length);\n } else {\n // negative bias, this can happen when diffing two histograms\n this.backing.reverse(0, this.backing.length);\n this.backing.reverse(0, this.backing.length + bias);\n }\n this.indexBase = this.indexStart;\n }\n\n /**\n * _relocateBucket adds the count in counts[src] to counts[dest] and\n * resets count[src] to zero.\n */\n private _relocateBucket(dest: number, src: number) {\n if (dest === src) {\n return;\n }\n this.incrementBucket(dest, this.backing.emptyBucket(src));\n }\n}\n\n/**\n * BucketsBacking holds the raw buckets and some utility methods to\n * manage them.\n */\nclass BucketsBacking {\n private _counts;\n\n constructor(counts = [0]) {\n this._counts = counts;\n }\n\n /**\n * length returns the physical size of the backing array, which\n * is >= buckets.length()\n */\n get length(): number {\n return this._counts.length;\n }\n\n /**\n * countAt returns the count in a specific bucket\n */\n countAt(pos: number): number {\n return this._counts[pos];\n }\n\n /**\n * growTo grows a backing array and copies old entries\n * into their correct new positions.\n */\n growTo(newSize: number, oldPositiveLimit: number, newPositiveLimit: number) {\n const tmp = new Array<number>(newSize).fill(0);\n tmp.splice(\n newPositiveLimit,\n this._counts.length - oldPositiveLimit,\n ...this._counts.slice(oldPositiveLimit)\n );\n tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit));\n this._counts = tmp;\n }\n\n /**\n * reverse the items in the backing array in the range [from, limit).\n */\n reverse(from: number, limit: number) {\n const num = Math.floor((from + limit) / 2) - from;\n for (let i = 0; i < num; i++) {\n const tmp = this._counts[from + i];\n this._counts[from + i] = this._counts[limit - i - 1];\n this._counts[limit - i - 1] = tmp;\n }\n }\n\n /**\n * emptyBucket empties the count from a bucket, for\n * moving into another.\n */\n emptyBucket(src: number): number {\n const tmp = this._counts[src];\n this._counts[src] = 0;\n return tmp;\n }\n\n /**\n * increments a bucket by `increment`\n */\n increment(bucketIndex: number, increment: number) {\n this._counts[bucketIndex] += increment;\n }\n\n /**\n * decrements a bucket by `decrement`\n */\n decrement(bucketIndex: number, decrement: number) {\n if (this._counts[bucketIndex] >= decrement) {\n this._counts[bucketIndex] -= decrement;\n } else {\n // this should not happen, but we're being defensive against\n // negative counts.\n this._counts[bucketIndex] = 0;\n }\n }\n\n /**\n * clone returns a deep copy of BucketsBacking\n */\n clone(): BucketsBacking {\n return new BucketsBacking([...this._counts]);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * The functions and constants in this file allow us to interact\n * with the internal representation of an IEEE 64-bit floating point\n * number. We need to work with all 64-bits, thus, care needs to be\n * taken when working with Javascript's bitwise operators (<<, >>, &,\n * |, etc) as they truncate operands to 32-bits. In order to work around\n * this we work with the 64-bits as two 32-bit halves and perform bitwise\n * operations on each half independently.\n */\n\n/**\n * EXPONENT_MASK is set to 1 for the hi 32-bits of an IEEE 754\n * floating point exponent: 0x7ff00000.\n */\nconst EXPONENT_MASK = 0x7ff00000;\n\n/**\n * SIGNIFICAND_MASK is the mask for the significand portion of the hi 32-bits\n * of an IEEE 754 double-precision floating-point value: 0xfffff\n */\nconst SIGNIFICAND_MASK = 0xfffff;\n\n/**\n * EXPONENT_BIAS is the exponent bias specified for encoding\n * the IEEE 754 double-precision floating point exponent: 1023\n */\nconst EXPONENT_BIAS = 1023;\n\n/**\n * MIN_NORMAL_EXPONENT is the minimum exponent of a normalized\n * floating point: -1022.\n */\nexport const MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1;\n\n/**\n * MAX_NORMAL_EXPONENT is the maximum exponent of a normalized\n * floating point: 1023.\n */\nexport const MAX_NORMAL_EXPONENT = EXPONENT_BIAS;\n\n/**\n * MIN_VALUE is the smallest normal number\n */\nexport const MIN_VALUE = Math.pow(2, -1022);\n\n// A single DataView, allocated once and reused. Sharing the buffer is safe\n// because every read below is synchronous.\nconst dv = new DataView(new ArrayBuffer(8));\n\n/**\n * floatBits writes value into the shared buffer and returns its two 32-bit\n * halves.\n * @param {number} value - the floating point number to read\n * @returns {{hi: number, lo: number}} the high and low 32-bit halves\n */\nfunction floatBits(value: number): { hi: number; lo: number } {\n dv.setFloat64(0, value);\n return { hi: dv.getUint32(0), lo: dv.getUint32(4) };\n}\n\n/**\n * getNormalBase2 extracts the normalized base-2 fractional exponent.\n * This returns k for the equation f x 2**k where f is\n * in the range [1, 2). Note that this function is not called for\n * subnormal numbers.\n * @param {number} value - the value to determine normalized base-2 fractional\n * exponent for\n * @returns {number} the normalized base-2 exponent\n */\nexport function getNormalBase2(value: number): number {\n const { hi } = floatBits(value);\n return ((hi & EXPONENT_MASK) >> 20) - EXPONENT_BIAS;\n}\n\n/**\n * isPowerOfTwo reports whether value is an exact power of two, e.g. its 52-bit\n * significand is all zeros. Only valid for positive, finite values.\n * @param {number} value - the floating point number to test\n * @returns {boolean} true if value is an exact power of two\n */\nexport function isPowerOfTwo(value: number): boolean {\n const { hi, lo } = floatBits(value);\n return (hi & SIGNIFICAND_MASK) === 0 && lo === 0;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Note: other languages provide this as a built in function. This is\n * a naive, but functionally correct implementation. This is used sparingly,\n * when creating a new mapping in a running application.\n *\n * ldexp returns frac × 2**exp. With the following special cases:\n * ldexp(±0, exp) = ±0\n * ldexp(±Inf, exp) = ±Inf\n * ldexp(NaN, exp) = NaN\n * @param frac\n * @param exp\n * @returns {number}\n */\nexport function ldexp(frac: number, exp: number): number {\n if (\n frac === 0 ||\n frac === Number.POSITIVE_INFINITY ||\n frac === Number.NEGATIVE_INFINITY ||\n Number.isNaN(frac)\n ) {\n return frac;\n }\n return frac * Math.pow(2, exp);\n}\n\n/**\n * Computes the next power of two that is greater than or equal to v.\n * This implementation more efficient than, but functionally equivalent\n * to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))).\n * @param v\n * @returns {number}\n */\nexport function nextGreaterSquare(v: number): number {\n // The following expression computes the least power-of-two\n // that is >= v. There are a number of tricky ways to\n // do this, see https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport class MappingError extends Error {}\n\n/**\n * The mapping interface is used by the exponential histogram to determine\n * where to bucket values. The interface is implemented by ExponentMapping,\n * used for scales [-10, 0] and LogarithmMapping, used for scales [1, 20].\n */\nexport interface Mapping {\n mapToIndex(value: number): number;\n lowerBoundary(index: number): number;\n get scale(): number;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as ieee754 from './ieee754';\nimport * as util from '../util';\nimport type { Mapping } from './types';\nimport { MappingError } from './types';\n\n/**\n * ExponentMapping implements exponential mapping functions for\n * scales <=0. For scales > 0 LogarithmMapping should be used.\n */\nexport class ExponentMapping implements Mapping {\n private readonly _shift: number;\n\n constructor(scale: number) {\n this._shift = -scale;\n }\n\n /**\n * Maps positive floating point values to indexes corresponding to scale\n * @param value\n * @returns {number} index for provided value at the current scale\n */\n mapToIndex(value: number): number {\n if (value < ieee754.MIN_VALUE) {\n return this._minNormalLowerBoundaryIndex();\n }\n\n const exp = ieee754.getNormalBase2(value);\n\n // An exact power of two sits on a bucket boundary; correct by -1 so it\n // falls into the lower bucket.\n const correction = ieee754.isPowerOfTwo(value) ? -1 : 0;\n\n return (exp + correction) >> this._shift;\n }\n\n /**\n * Returns the lower bucket boundary for the given index for scale\n *\n * @param index\n * @returns {number}\n */\n lowerBoundary(index: number): number {\n const minIndex = this._minNormalLowerBoundaryIndex();\n if (index < minIndex) {\n throw new MappingError(\n `underflow: ${index} is < minimum lower boundary: ${minIndex}`\n );\n }\n const maxIndex = this._maxNormalLowerBoundaryIndex();\n if (index > maxIndex) {\n throw new MappingError(\n `overflow: ${index} is > maximum lower boundary: ${maxIndex}`\n );\n }\n\n return util.ldexp(1, index << this._shift);\n }\n\n /**\n * The scale used by this mapping\n * @returns {number}\n */\n get scale(): number {\n if (this._shift === 0) {\n return 0;\n }\n return -this._shift;\n }\n\n private _minNormalLowerBoundaryIndex(): number {\n let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift;\n if (this._shift < 2) {\n index--;\n }\n\n return index;\n }\n\n private _maxNormalLowerBoundaryIndex(): number {\n return ieee754.MAX_NORMAL_EXPONENT >> this._shift;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as ieee754 from './ieee754';\nimport * as util from '../util';\nimport type { Mapping } from './types';\nimport { MappingError } from './types';\n\n/**\n * LogarithmMapping implements exponential mapping functions for scale > 0.\n * For scales <= 0 the exponent mapping should be used.\n */\nexport class LogarithmMapping implements Mapping {\n private readonly _scale: number;\n private readonly _scaleFactor: number;\n private readonly _inverseFactor: number;\n\n constructor(scale: number) {\n this._scale = scale;\n this._scaleFactor = util.ldexp(Math.LOG2E, scale);\n this._inverseFactor = util.ldexp(Math.LN2, -scale);\n }\n\n /**\n * Maps positive floating point values to indexes corresponding to scale\n * @param value\n * @returns {number} index for provided value at the current scale\n */\n mapToIndex(value: number): number {\n if (value <= ieee754.MIN_VALUE) {\n return this._minNormalLowerBoundaryIndex() - 1;\n }\n\n // exact power of two special case\n if (ieee754.isPowerOfTwo(value)) {\n const exp = ieee754.getNormalBase2(value);\n return (exp << this._scale) - 1;\n }\n\n // non-power of two cases. use Math.floor to round the scaled logarithm\n const index = Math.floor(Math.log(value) * this._scaleFactor);\n const maxIndex = this._maxNormalLowerBoundaryIndex();\n if (index >= maxIndex) {\n return maxIndex;\n }\n\n return index;\n }\n\n /**\n * Returns the lower bucket boundary for the given index for scale\n *\n * @param index\n * @returns {number}\n */\n lowerBoundary(index: number): number {\n const maxIndex = this._maxNormalLowerBoundaryIndex();\n if (index >= maxIndex) {\n if (index === maxIndex) {\n return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor);\n }\n throw new MappingError(\n `overflow: ${index} is > maximum lower boundary: ${maxIndex}`\n );\n }\n\n const minIndex = this._minNormalLowerBoundaryIndex();\n if (index <= minIndex) {\n if (index === minIndex) {\n return ieee754.MIN_VALUE;\n } else if (index === minIndex - 1) {\n return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2;\n }\n throw new MappingError(\n `overflow: ${index} is < minimum lower boundary: ${minIndex}`\n );\n }\n\n return Math.exp(index * this._inverseFactor);\n }\n\n /**\n * The scale used by this mapping\n * @returns {number}\n */\n get scale(): number {\n return this._scale;\n }\n\n private _minNormalLowerBoundaryIndex(): number {\n return ieee754.MIN_NORMAL_EXPONENT << this._scale;\n }\n\n private _maxNormalLowerBoundaryIndex(): number {\n return ((ieee754.MAX_NORMAL_EXPONENT + 1) << this._scale) - 1;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ExponentMapping } from './ExponentMapping';\nimport { LogarithmMapping } from './LogarithmMapping';\nimport type { Mapping } from './types';\nimport { MappingError } from './types';\n\nconst MIN_SCALE = -10;\nconst MAX_SCALE = 20;\nconst PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => {\n if (i > 10) {\n return new LogarithmMapping(i - 10);\n }\n return new ExponentMapping(i - 10);\n});\n\n/**\n * getMapping returns an appropriate mapping for the given scale. For scales -10\n * to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the\n * underlying type will be LogarithmMapping.\n * @param scale a number in the range [-10, 20]\n * @returns {Mapping}\n */\nexport function getMapping(scale: number): Mapping {\n if (scale > MAX_SCALE || scale < MIN_SCALE) {\n throw new MappingError(\n `expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`\n );\n }\n // mappings are offset by 10. scale -10 is at position 0 and scale 20 is at 30\n return PREBUILT_MAPPINGS[scale + 10];\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n LastValue,\n} from './types';\nimport { AggregatorKind } from './types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { millisToHrTime, hrTimeToMicroseconds } from '@opentelemetry/core';\nimport type { GaugeMetricData } from '../export/MetricData';\nimport { DataPointType } from '../export/MetricData';\nimport type { Maybe } from '../utils';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\nexport class LastValueAccumulation implements Accumulation {\n public startTime;\n private _current;\n public sampleTime;\n\n constructor(startTime: HrTime, current = 0, sampleTime: HrTime = [0, 0]) {\n this.startTime = startTime;\n this._current = current;\n this.sampleTime = sampleTime;\n }\n\n record(value: number): void {\n this._current = value;\n this.sampleTime = millisToHrTime(Date.now());\n }\n\n setStartTime(startTime: HrTime): void {\n this.startTime = startTime;\n }\n\n toPointValue(): LastValue {\n return this._current;\n }\n}\n\n/** Basic aggregator which calculates a LastValue from individual measurements. */\nexport class LastValueAggregator implements Aggregator<LastValueAccumulation> {\n public kind: AggregatorKind.LAST_VALUE = AggregatorKind.LAST_VALUE;\n\n createAccumulation(startTime: HrTime) {\n return new LastValueAccumulation(startTime);\n }\n\n /**\n * Returns the result of the merge of the given accumulations.\n *\n * Return the newly captured (delta) accumulation for LastValueAggregator.\n */\n merge(\n previous: LastValueAccumulation,\n delta: LastValueAccumulation\n ): LastValueAccumulation {\n // nanoseconds may lose precisions.\n const latestAccumulation =\n hrTimeToMicroseconds(delta.sampleTime) >=\n hrTimeToMicroseconds(previous.sampleTime)\n ? delta\n : previous;\n return new LastValueAccumulation(\n previous.startTime,\n latestAccumulation.toPointValue(),\n latestAccumulation.sampleTime\n );\n }\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n *\n * A delta aggregation is not meaningful to LastValueAggregator, just return\n * the newly captured (delta) accumulation for LastValueAggregator.\n */\n diff(\n previous: LastValueAccumulation,\n current: LastValueAccumulation\n ): LastValueAccumulation {\n // nanoseconds may lose precisions.\n const latestAccumulation =\n hrTimeToMicroseconds(current.sampleTime) >=\n hrTimeToMicroseconds(previous.sampleTime)\n ? current\n : previous;\n return new LastValueAccumulation(\n current.startTime,\n latestAccumulation.toPointValue(),\n latestAccumulation.sampleTime\n );\n }\n\n toMetricData(\n descriptor: InstrumentDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<LastValueAccumulation>[],\n endTime: HrTime\n ): Maybe<GaugeMetricData> {\n return {\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.GAUGE,\n dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {\n return {\n attributes,\n startTime: accumulation.startTime,\n endTime,\n value: accumulation.toPointValue(),\n };\n }),\n };\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Sum,\n Aggregator,\n Accumulation,\n AccumulationRecord,\n} from './types';\nimport { AggregatorKind } from './types';\nimport type { HrTime } from '@opentelemetry/api';\nimport type { SumMetricData } from '../export/MetricData';\nimport { DataPointType } from '../export/MetricData';\nimport type { Maybe } from '../utils';\nimport type { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\nexport class SumAccumulation implements Accumulation {\n public startTime;\n public monotonic;\n private _current;\n public reset;\n\n constructor(\n startTime: HrTime,\n monotonic: boolean,\n current = 0,\n reset = false\n ) {\n this.startTime = startTime;\n this.monotonic = monotonic;\n this._current = current;\n this.reset = reset;\n }\n\n record(value: number): void {\n if (this.monotonic && value < 0) {\n return;\n }\n this._current += value;\n }\n\n setStartTime(startTime: HrTime): void {\n this.startTime = startTime;\n }\n\n toPointValue(): Sum {\n return this._current;\n }\n}\n\n/** Basic aggregator which calculates a Sum from individual measurements. */\nexport class SumAggregator implements Aggregator<SumAccumulation> {\n public kind: AggregatorKind.SUM = AggregatorKind.SUM;\n public monotonic: boolean;\n\n constructor(monotonic: boolean) {\n this.monotonic = monotonic;\n }\n\n createAccumulation(startTime: HrTime) {\n return new SumAccumulation(startTime, this.monotonic);\n }\n\n /**\n * Returns the result of the merge of the given accumulations.\n */\n merge(previous: SumAccumulation, delta: SumAccumulation): SumAccumulation {\n const prevPv = previous.toPointValue();\n const deltaPv = delta.toPointValue();\n if (delta.reset) {\n return new SumAccumulation(\n delta.startTime,\n this.monotonic,\n deltaPv,\n delta.reset\n );\n }\n return new SumAccumulation(\n previous.startTime,\n this.monotonic,\n prevPv + deltaPv\n );\n }\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n */\n diff(previous: SumAccumulation, current: SumAccumulation): SumAccumulation {\n const prevPv = previous.toPointValue();\n const currPv = current.toPointValue();\n /**\n * If the SumAggregator is a monotonic one and the previous point value is\n * greater than the current one, a reset is deemed to be happened.\n * Return the current point value to prevent the value from been reset.\n */\n if (this.monotonic && prevPv > currPv) {\n return new SumAccumulation(\n current.startTime,\n this.monotonic,\n currPv,\n true\n );\n }\n return new SumAccumulation(\n current.startTime,\n this.monotonic,\n currPv - prevPv\n );\n }\n\n toMetricData(\n descriptor: InstrumentDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<SumAccumulation>[],\n endTime: HrTime\n ): Maybe<SumMetricData> {\n return {\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.SUM,\n dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => {\n return {\n attributes,\n startTime: accumulation.startTime,\n endTime,\n value: accumulation.toPointValue(),\n };\n }),\n isMonotonic: this.monotonic,\n };\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Aggregation } from './Aggregation';\nimport {\n DEFAULT_AGGREGATION,\n DROP_AGGREGATION,\n ExplicitBucketHistogramAggregation,\n ExponentialHistogramAggregation,\n HISTOGRAM_AGGREGATION,\n LAST_VALUE_AGGREGATION,\n SUM_AGGREGATION,\n} from './Aggregation';\n\nexport enum AggregationType {\n DEFAULT = 0,\n DROP = 1,\n SUM = 2,\n LAST_VALUE = 3,\n EXPLICIT_BUCKET_HISTOGRAM = 4,\n EXPONENTIAL_HISTOGRAM = 5,\n}\n\nexport type SumAggregationOption = {\n type: AggregationType.SUM;\n};\n\nexport type LastValueAggregationOption = {\n type: AggregationType.LAST_VALUE;\n};\n\nexport type DropAggregationOption = {\n type: AggregationType.DROP;\n};\n\nexport type DefaultAggregationOption = {\n type: AggregationType.DEFAULT;\n};\n\nexport type HistogramAggregationOption = {\n type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM;\n options?: {\n recordMinMax?: boolean;\n boundaries: number[];\n };\n};\n\nexport type ExponentialHistogramAggregationOption = {\n type: AggregationType.EXPONENTIAL_HISTOGRAM;\n options?: {\n recordMinMax?: boolean;\n maxSize?: number;\n };\n};\n\nexport type AggregationOption =\n | ExponentialHistogramAggregationOption\n | HistogramAggregationOption\n | SumAggregationOption\n | DropAggregationOption\n | DefaultAggregationOption\n | LastValueAggregationOption;\n\nexport function toAggregation(option: AggregationOption): Aggregation {\n switch (option.type) {\n case AggregationType.DEFAULT:\n return DEFAULT_AGGREGATION;\n case AggregationType.DROP:\n return DROP_AGGREGATION;\n case AggregationType.SUM:\n return SUM_AGGREGATION;\n case AggregationType.LAST_VALUE:\n return LAST_VALUE_AGGREGATION;\n case AggregationType.EXPONENTIAL_HISTOGRAM: {\n const expOption = option as ExponentialHistogramAggregationOption;\n return new ExponentialHistogramAggregation(\n expOption.options?.maxSize,\n expOption.options?.recordMinMax\n );\n }\n case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: {\n const expOption = option as HistogramAggregationOption;\n if (expOption.options == null) {\n return HISTOGRAM_AGGREGATION;\n } else {\n return new ExplicitBucketHistogramAggregation(\n expOption.options?.boundaries,\n expOption.options?.recordMinMax\n );\n }\n }\n default:\n throw new Error('Unsupported Aggregation');\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { AggregationTemporality } from './AggregationTemporality';\nimport type { InstrumentType } from './MetricData';\nimport type { AggregationOption } from '../view/AggregationOption';\nimport { AggregationType } from '../view/AggregationOption';\n\n/**\n * Aggregation selector based on metric instrument types.\n */\nexport type AggregationSelector = (\n instrumentType: InstrumentType\n) => AggregationOption;\n\n/**\n * Aggregation temporality selector based on metric instrument types.\n */\nexport type AggregationTemporalitySelector = (\n instrumentType: InstrumentType\n) => AggregationTemporality;\n\nexport const DEFAULT_AGGREGATION_SELECTOR: AggregationSelector =\n _instrumentType => {\n return {\n type: AggregationType.DEFAULT,\n };\n };\n\nexport const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR: AggregationTemporalitySelector =\n _instrumentType => AggregationTemporality.CUMULATIVE;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * A name uniquely identifying the instance of the OpenTelemetry component within its containing SDK instance.\n *\n * @example otlp_grpc_span_exporter/0\n * @example custom-name\n *\n * @note Implementations **SHOULD** ensure a low cardinality for this attribute, even across application or SDK restarts.\n * E.g. implementations **MUST NOT** use UUIDs as values for this attribute.\n *\n * Implementations **MAY** achieve these goals by following a `<otel.component.type>/<instance-counter>` pattern, e.g. `batching_span_processor/0`.\n * Hereby `otel.component.type` refers to the corresponding attribute value of the component.\n *\n * The value of `instance-counter` **MAY** be automatically assigned by the component and uniqueness within the enclosing SDK instance **MUST** be guaranteed.\n * For example, `<instance-counter>` **MAY** be implemented by using a monotonically increasing counter (starting with `0`), which is incremented every time an\n * instance of the given component type is started.\n *\n * With this implementation, for example the first Batching Span Processor would have `batching_span_processor/0`\n * as `otel.component.name`, the second one `batching_span_processor/1` and so on.\n * These values will therefore be reused in the case of an application restart.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_NAME = 'otel.component.name' as const;\n\n/**\n * A name identifying the type of the OpenTelemetry component.\n *\n * @example batching_span_processor\n * @example com.example.MySpanExporter\n *\n * @note If none of the standardized values apply, implementations **SHOULD** use the language-defined name of the type.\n * E.g. for Java the fully qualified classname **SHOULD** be used in this case.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_COMPONENT_TYPE = 'otel.component.type' as const;\n\n/**\n * Enum value \"periodic_metric_reader\" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}.\n *\n * The builtin SDK periodically exporting metric reader\n *\n * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER =\n 'periodic_metric_reader' as const;\n\n/**\n * The duration of the collect operation of the metric reader.\n *\n * @note For successful collections, `error.type` **MUST NOT** be set. For failed collections, `error.type` **SHOULD** contain the failure cause.\n * It can happen that metrics collection is successful for some MetricProducers, while others fail. In that case `error.type` **SHOULD** be set to any of the failure causes.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION =\n 'otel.sdk.metric_reader.collection.duration' as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, Histogram, Meter } from '@opentelemetry/api';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_OTEL_COMPONENT_NAME,\n ATTR_OTEL_COMPONENT_TYPE,\n METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION,\n} from '../semconv';\n\nconst componentCounter = new Map<string, number>();\n\n/**\n * Generates `otel.sdk.metric_reader.*` self-observability metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#metric-otelsdkmetric_readercollectionduration\n */\nexport class MetricReaderMetrics {\n private readonly collectionDuration: Histogram;\n private readonly standardAttrs: Attributes;\n\n constructor(componentType: string, meter: Meter) {\n const counter = componentCounter.get(componentType) ?? 0;\n componentCounter.set(componentType, counter + 1);\n\n this.standardAttrs = {\n [ATTR_OTEL_COMPONENT_TYPE]: componentType,\n [ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}`,\n };\n\n this.collectionDuration = meter.createHistogram(\n METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION,\n {\n unit: 's',\n description:\n 'The duration of the collect operation of the metric reader.',\n advice: {\n explicitBucketBoundaries: [],\n },\n }\n );\n }\n\n recordCollection(durationSecs: number, error: string | undefined) {\n const attrs = error\n ? { ...this.standardAttrs, [ATTR_ERROR_TYPE]: error }\n : this.standardAttrs;\n this.collectionDuration.record(durationSecs, attrs);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.12.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n} from '@opentelemetry/core';\nimport { MetricReader } from './MetricReader';\nimport type { PushMetricExporter } from './MetricExporter';\nimport { callWithTimeout, TimeoutError } from '../utils';\nimport { InstrumentType } from './MetricData';\nimport { splitMetricData } from './MetricDataSplitter';\nimport type { MetricProducer } from './MetricProducer';\nimport { OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER } from '../semconv';\n\nexport type PeriodicExportingMetricReaderOptions = {\n /**\n * The backing exporter for the metric reader.\n */\n exporter: PushMetricExporter;\n /**\n * An internal milliseconds for the metric reader to initiate metric\n * collection.\n */\n exportIntervalMillis?: number;\n /**\n * Milliseconds for the async observable callback to timeout.\n */\n exportTimeoutMillis?: number;\n /**\n * **Note, this option is experimental**. Additional MetricProducers to use as a source of\n * aggregated metric data in addition to the SDK's metric data. The resource returned by\n * these MetricProducers is ignored; the SDK's resource will be used instead.\n * @experimental\n */\n metricProducers?: MetricProducer[];\n /**\n * Cardinality limits for the metric reader, applied per instrument. If not configured, defaults to 2000 time series per instrument. These are wrapped in a cardinalitySelector function that returns limits based on the instrument type, so they can be configured differently per type if desired.\n *\n */\n cardinalityLimits?: {\n counter?: number;\n gauge?: number;\n histogram?: number;\n upDownCounter?: number;\n observableCounter?: number;\n observableGauge?: number;\n observableUpDownCounter?: number;\n default?: number;\n };\n /**\n * The maximum batch size for exports. If configured, the reader will split\n * batches larger than this size into smaller batches.\n * @experimental\n */\n maxExportBatchSize?: number;\n};\n\n/**\n * {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to\n * the configured {@link PushMetricExporter}\n */\nexport class PeriodicExportingMetricReader extends MetricReader {\n private _interval?: ReturnType<typeof setInterval>;\n private _exporter: PushMetricExporter;\n private readonly _exportInterval: number;\n private readonly _exportTimeout: number;\n private readonly _maxExportBatchSize?: number;\n private _ongoingExportPromise: Promise<void> | null = null;\n\n constructor(options: PeriodicExportingMetricReaderOptions) {\n const {\n exporter,\n exportIntervalMillis = 60000,\n metricProducers,\n cardinalityLimits,\n maxExportBatchSize,\n } = options;\n let { exportTimeoutMillis = 30000 } = options;\n\n super({\n aggregationSelector: exporter.selectAggregation?.bind(exporter),\n aggregationTemporalitySelector:\n exporter.selectAggregationTemporality?.bind(exporter),\n otelComponentType: OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER,\n metricProducers,\n cardinalitySelector: (instrumentType: InstrumentType) => {\n const limits = {\n default: 2000,\n ...cardinalityLimits,\n };\n\n switch (instrumentType) {\n case InstrumentType.COUNTER:\n return limits.counter ?? limits.default;\n case InstrumentType.GAUGE:\n return limits.gauge ?? limits.default;\n case InstrumentType.HISTOGRAM:\n return limits.histogram ?? limits.default;\n case InstrumentType.OBSERVABLE_COUNTER:\n return limits.observableCounter ?? limits.default;\n case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:\n return limits.observableUpDownCounter ?? limits.default;\n case InstrumentType.OBSERVABLE_GAUGE:\n return limits.observableGauge ?? limits.default;\n case InstrumentType.UP_DOWN_COUNTER:\n return limits.upDownCounter ?? limits.default;\n default:\n return limits.default;\n }\n },\n });\n\n if (exportIntervalMillis <= 0) {\n throw Error('exportIntervalMillis must be greater than 0');\n }\n\n if (exportTimeoutMillis <= 0) {\n throw Error('exportTimeoutMillis must be greater than 0');\n }\n\n if (\n maxExportBatchSize !== undefined &&\n (!Number.isInteger(maxExportBatchSize) || maxExportBatchSize <= 0)\n ) {\n throw Error('maxExportBatchSize must be a positive integer');\n }\n\n if (exportIntervalMillis < exportTimeoutMillis) {\n if (\n 'exportIntervalMillis' in options &&\n 'exportTimeoutMillis' in options\n ) {\n // An invalid combination of values was explicitly provided.\n throw Error(\n 'exportIntervalMillis must be greater than or equal to exportTimeoutMillis'\n );\n } else {\n // An invalid combination of value was implicitly provided.\n api.diag.info(\n `Timeout of ${exportTimeoutMillis} exceeds the interval of ${exportIntervalMillis}. Clamping timeout to interval duration.`\n );\n exportTimeoutMillis = exportIntervalMillis;\n }\n }\n\n this._exportInterval = exportIntervalMillis;\n this._exportTimeout = exportTimeoutMillis;\n this._exporter = exporter;\n this._maxExportBatchSize = maxExportBatchSize;\n }\n\n private async _runOnce(): Promise<void> {\n try {\n await this._doRun();\n } catch (err) {\n globalErrorHandler(err);\n }\n }\n\n private async _doRun(): Promise<void> {\n if (this._ongoingExportPromise) {\n api.diag.debug(\n 'PeriodicExportingMetricReader: export already in progress, skipping'\n );\n return;\n }\n\n const currentRun = async () => {\n const { resourceMetrics, errors } = await this.collect({\n timeoutMillis: this._exportTimeout,\n });\n\n if (errors.length > 0) {\n api.diag.error(\n 'PeriodicExportingMetricReader: metrics collection errors',\n ...errors\n );\n }\n\n if (resourceMetrics.resource.asyncAttributesPending) {\n try {\n await resourceMetrics.resource.waitForAsyncAttributes?.();\n } catch (e) {\n api.diag.debug(\n 'Error while resolving async portion of resource: ',\n e\n );\n globalErrorHandler(e);\n }\n }\n\n if (resourceMetrics.scopeMetrics.length === 0) {\n return;\n }\n\n const batches = this._maxExportBatchSize\n ? splitMetricData(resourceMetrics, this._maxExportBatchSize)\n : [resourceMetrics];\n\n let anyErr: Error | null = null;\n for (const batch of batches) {\n try {\n const result = await callWithTimeout(\n internal._export(this._exporter, batch),\n this._exportTimeout\n );\n if (result.code !== ExportResultCode.SUCCESS) {\n const err = new Error(\n `PeriodicExportingMetricReader: metrics export failed (error ${result.error})`\n );\n anyErr = err;\n }\n } catch (e) {\n if (e instanceof TimeoutError) {\n api.diag.error(\n `PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`\n );\n break;\n } else {\n api.diag.error(\n 'PeriodicExportingMetricReader: metrics export threw error',\n e\n );\n anyErr = e instanceof Error ? e : new Error(String(e));\n }\n }\n }\n if (anyErr) {\n throw anyErr;\n }\n };\n\n this._ongoingExportPromise = currentRun();\n try {\n await this._ongoingExportPromise;\n } finally {\n this._ongoingExportPromise = null;\n }\n }\n\n protected override onInitialized(): void {\n // start running the interval as soon as this reader is initialized and keep handle for shutdown.\n this._interval = setInterval(() => {\n // this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises.\n void this._runOnce();\n }, this._exportInterval);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._interval !== 'number') {\n this._interval.unref();\n }\n }\n\n protected async onForceFlush(): Promise<void> {\n // Wait for any in-progress export to finish first so that we never run\n // collect + export concurrently with it.\n await this._awaitOngoingExport();\n // forceFlush SHOULD collect and export the latest metrics. If a concurrent\n // caller already started a fresh export while we were waiting above, await\n // that one instead of starting yet another collect + export cycle;\n // otherwise run our own.\n if (this._ongoingExportPromise) {\n await this._awaitOngoingExport();\n } else {\n await this._runOnce();\n }\n await this._exporter.forceFlush();\n }\n\n /**\n * Helper function to wait for an ongoing export to complete.\n * Errors are swallowed and handled by the original _runOnce().\n */\n private async _awaitOngoingExport(): Promise<void> {\n if (this._ongoingExportPromise) {\n api.diag.debug(\n 'PeriodicExportingMetricReader: export already in progress, awaiting ongoing export'\n );\n try {\n await this._ongoingExportPromise;\n } catch {\n // Error is handled by the _runOnce() that initiated the export.\n }\n }\n }\n\n protected async onShutdown(): Promise<void> {\n if (this._interval) {\n clearInterval(this._interval);\n }\n await this.onForceFlush();\n await this._exporter.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPoint, ResourceMetrics, ScopeMetrics } from './MetricData';\n\n/**\n * Splits a ResourceMetrics object into smaller ResourceMetrics objects\n * such that no batch exceeds maxExportBatchSize data points.\n * @param resourceMetrics The metrics to split.\n * @param maxExportBatchSize The maximum number of data points per batch.\n * @internal\n */\nexport function splitMetricData(\n resourceMetrics: ResourceMetrics,\n maxExportBatchSize: number\n): ResourceMetrics[] {\n if (!Number.isInteger(maxExportBatchSize) || maxExportBatchSize <= 0) {\n throw new Error('maxExportBatchSize must be a positive integer');\n }\n const batches: ResourceMetrics[] = [];\n let currentBatchPoints = 0;\n let currentScopeMetrics: ScopeMetrics[] = [];\n\n function flush() {\n if (currentScopeMetrics.length > 0) {\n batches.push({\n resource: resourceMetrics.resource,\n scopeMetrics: currentScopeMetrics,\n });\n currentScopeMetrics = [];\n currentBatchPoints = 0;\n }\n }\n\n // Iterate through all scopes in the input metrics\n for (const scopeMetric of resourceMetrics.scopeMetrics) {\n let scopeMetricCopy: ScopeMetrics | null = null;\n // Iterate through all metrics within the current scope\n for (const metric of scopeMetric.metrics) {\n const dataPoints = metric.dataPoints;\n // If a metric has no data points, add it directly to the current batch\n if (dataPoints.length === 0) {\n if (!scopeMetricCopy) {\n scopeMetricCopy = { scope: scopeMetric.scope, metrics: [] };\n currentScopeMetrics.push(scopeMetricCopy);\n }\n scopeMetricCopy.metrics.push(metric);\n continue;\n }\n // Chunk the data points of the current metric across batches. We iterate\n // with an offset instead of repeatedly slicing the remaining tail, which\n // keeps the overall work linear in the number of data points.\n let offset = 0;\n while (offset < dataPoints.length) {\n const spaceLeft = maxExportBatchSize - currentBatchPoints;\n const take = Math.min(spaceLeft, dataPoints.length - offset);\n // Ensure we have a ScopeMetrics object in the current batch\n if (!scopeMetricCopy) {\n scopeMetricCopy = { scope: scopeMetric.scope, metrics: [] };\n currentScopeMetrics.push(scopeMetricCopy);\n }\n // A metric receives exactly one contiguous chunk per batch (after\n // appending, the batch is either full and flushed, or the metric is\n // exhausted), so we can slice the data points directly rather than\n // copying them incrementally.\n const metricCopy = {\n ...metric,\n dataPoints: dataPoints.slice(\n offset,\n offset + take\n ) as DataPoint<unknown>[],\n } as typeof metric;\n scopeMetricCopy.metrics.push(metricCopy);\n offset += take;\n currentBatchPoints += take;\n // If the current batch is full, flush it and start a new one\n if (currentBatchPoints === maxExportBatchSize) {\n flush();\n scopeMetricCopy = null; // Force recreation of scope copy in the next batch\n }\n }\n }\n }\n\n flush();\n return batches;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n MeterProvider as IMeterProvider,\n Meter as IMeter,\n MeterOptions,\n} from '@opentelemetry/api';\nimport { diag, createNoopMeter } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport { MetricReader, type IMetricReader } from './export/MetricReader';\nimport { MeterProviderSharedState } from './state/MeterProviderSharedState';\nimport { MetricCollector } from './state/MetricCollector';\nimport type { ForceFlushOptions, ShutdownOptions } from './types';\nimport type { ViewOptions } from './view/View';\nimport { View } from './view/View';\n\n/**\n * MeterProviderOptions provides an interface for configuring a MeterProvider.\n */\nexport interface MeterProviderOptions {\n /** Resource associated with metric telemetry */\n resource?: Resource;\n views?: ViewOptions[];\n readers?: IMetricReader[];\n\n /**\n * Whether to enable SDK metrics for this meter provider.\n * @experimental This option is experimental and is subject to breaking changes in minor releases.\n */\n sdkMetricsEnabled?: boolean;\n}\n\n/**\n * This class implements the {@link MeterProvider} interface.\n */\nexport class MeterProvider implements IMeterProvider {\n private _sharedState: MeterProviderSharedState;\n private _shutdown = false;\n\n constructor(options?: MeterProviderOptions) {\n this._sharedState = new MeterProviderSharedState(\n options?.resource ?? defaultResource()\n );\n if (options?.views != null && options.views.length > 0) {\n for (const viewOption of options.views) {\n this._sharedState.viewRegistry.addView(new View(viewOption));\n }\n }\n\n if (options?.readers != null && options.readers.length > 0) {\n for (const metricReader of options.readers) {\n const collector = new MetricCollector(this._sharedState, metricReader);\n metricReader.setMetricProducer(collector);\n this._sharedState.metricCollectors.push(collector);\n if (options.sdkMetricsEnabled && metricReader instanceof MetricReader) {\n metricReader._setSelfObsMeterProvider(this);\n }\n }\n }\n }\n\n /**\n * Get a meter with the configuration of the MeterProvider.\n */\n getMeter(name: string, version = '', options: MeterOptions = {}): IMeter {\n // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation\n if (this._shutdown) {\n diag.warn('A shutdown MeterProvider cannot provide a Meter');\n return createNoopMeter();\n }\n\n return this._sharedState.getMeterSharedState({\n name,\n version,\n schemaUrl: options.schemaUrl,\n }).meter;\n }\n\n /**\n * Shut down the MeterProvider and all registered\n * MetricReaders.\n *\n * Returns a promise which is resolved when all flushes are complete.\n */\n async shutdown(options?: ShutdownOptions): Promise<void> {\n if (this._shutdown) {\n diag.warn('shutdown may only be called once per MeterProvider');\n return;\n }\n\n this._shutdown = true;\n\n await Promise.all(\n this._sharedState.metricCollectors.map(collector => {\n return collector.shutdown(options);\n })\n );\n }\n\n /**\n * Notifies all registered MetricReaders to flush any buffered data.\n *\n * Returns a promise which is resolved when all flushes are complete.\n */\n async forceFlush(options?: ForceFlushOptions): Promise<void> {\n // do not flush after shutdown\n if (this._shutdown) {\n diag.warn('invalid attempt to force flush after MeterProvider shutdown');\n return;\n }\n\n await Promise.all(\n this._sharedState.metricCollectors.map(collector => {\n return collector.forceFlush(options);\n })\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport type { InstrumentSelector } from './InstrumentSelector';\nimport type { MeterSelector } from './MeterSelector';\nimport type { View } from './View';\n\nexport class ViewRegistry {\n private _registeredViews: View[] = [];\n\n addView(view: View) {\n this._registeredViews.push(view);\n }\n\n findViews(\n instrument: InstrumentDescriptor,\n meter: InstrumentationScope\n ): View[] {\n const views = this._registeredViews.filter(registeredView => {\n return (\n this._matchInstrument(registeredView.instrumentSelector, instrument) &&\n this._matchMeter(registeredView.meterSelector, meter)\n );\n });\n\n return views;\n }\n\n private _matchInstrument(\n selector: InstrumentSelector,\n instrument: InstrumentDescriptor\n ): boolean {\n return (\n (selector.getType() === undefined ||\n instrument.type === selector.getType()) &&\n selector.getNameFilter().match(instrument.name) &&\n selector.getUnitFilter().match(instrument.unit)\n );\n }\n\n private _matchMeter(\n selector: MeterSelector,\n meter: InstrumentationScope\n ): boolean {\n return (\n selector.getNameFilter().match(meter.name) &&\n (meter.version === undefined ||\n selector.getVersionFilter().match(meter.version)) &&\n (meter.schemaUrl === undefined ||\n selector.getSchemaUrlFilter().match(meter.schemaUrl))\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { MetricAdvice, MetricOptions } from '@opentelemetry/api';\nimport { ValueType, diag } from '@opentelemetry/api';\nimport type { View } from './view/View';\nimport { equalsCaseInsensitive } from './utils';\nimport type { InstrumentType, MetricDescriptor } from './export/MetricData';\n\n/**\n * An internal interface describing the instrument.\n *\n * This is intentionally distinguished from the public MetricDescriptor (a.k.a. InstrumentDescriptor)\n * which may not contains internal fields like metric advice.\n */\nexport interface InstrumentDescriptor extends MetricDescriptor {\n /**\n * For internal use; exporter should avoid depending on the type of the\n * instrument as their resulting aggregator can be re-mapped with views.\n */\n readonly type: InstrumentType;\n\n /**\n * See {@link MetricAdvice}\n *\n * @experimental\n */\n readonly advice: MetricAdvice;\n}\n\nexport function createInstrumentDescriptor(\n name: string,\n type: InstrumentType,\n options?: MetricOptions\n): InstrumentDescriptor {\n if (!isValidName(name)) {\n diag.warn(\n `Invalid metric name: \"${name}\". The metric name should be a ASCII string with a length no greater than 255 characters.`\n );\n }\n return {\n name,\n type,\n description: options?.description ?? '',\n unit: options?.unit ?? '',\n valueType: options?.valueType ?? ValueType.DOUBLE,\n advice: options?.advice ?? {},\n };\n}\n\nexport function createInstrumentDescriptorWithView(\n view: View,\n instrument: InstrumentDescriptor\n): InstrumentDescriptor {\n return {\n name: view.name ?? instrument.name,\n description: view.description ?? instrument.description,\n type: instrument.type,\n unit: instrument.unit,\n valueType: instrument.valueType,\n advice: instrument.advice,\n };\n}\n\nexport function isDescriptorCompatibleWith(\n descriptor: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n) {\n // Names are case-insensitive strings.\n return (\n equalsCaseInsensitive(descriptor.name, otherDescriptor.name) &&\n descriptor.unit === otherDescriptor.unit &&\n descriptor.type === otherDescriptor.type &&\n descriptor.valueType === otherDescriptor.valueType\n );\n}\n\n// ASCII string with a length no greater than 255 characters.\n// NB: the first character counted separately from the rest.\nconst NAME_REGEXP = /^[a-z][a-z0-9_.\\-/]{0,254}$/i;\nexport function isValidName(name: string): boolean {\n return NAME_REGEXP.test(name);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Attributes,\n UpDownCounter,\n Counter,\n Gauge,\n Histogram,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n} from '@opentelemetry/api';\nimport { diag, ValueType } from '@opentelemetry/api';\nimport type { InstrumentDescriptor } from './InstrumentDescriptor';\nimport type { ObservableRegistry } from './state/ObservableRegistry';\nimport type {\n AsyncWritableMetricStorage,\n WritableMetricStorage,\n} from './state/WritableMetricStorage';\n\nexport class SyncInstrument {\n private _writableMetricStorage: WritableMetricStorage;\n protected _descriptor: InstrumentDescriptor;\n\n constructor(\n writableMetricStorage: WritableMetricStorage,\n descriptor: InstrumentDescriptor\n ) {\n this._writableMetricStorage = writableMetricStorage;\n this._descriptor = descriptor;\n }\n\n protected _record(\n value: number,\n attributes: Attributes = {},\n context?: Context\n ) {\n if (typeof value !== 'number') {\n diag.warn(\n `non-number value provided to metric ${this._descriptor.name}: ${value}`\n );\n return;\n }\n if (\n this._descriptor.valueType === ValueType.INT &&\n !Number.isInteger(value)\n ) {\n diag.warn(\n `INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`\n );\n value = Math.trunc(value);\n // ignore non-finite values.\n if (!Number.isInteger(value)) {\n return;\n }\n }\n this._writableMetricStorage.record(value, attributes, context, Date.now());\n }\n}\n\n/**\n * The class implements {@link UpDownCounter} interface.\n */\nexport class UpDownCounterInstrument\n extends SyncInstrument\n implements UpDownCounter\n{\n /**\n * Increment value of counter by the input. Inputs may be negative.\n */\n add(value: number, attributes?: Attributes, ctx?: Context): void {\n this._record(value, attributes, ctx);\n }\n}\n\n/**\n * The class implements {@link Counter} interface.\n */\nexport class CounterInstrument extends SyncInstrument implements Counter {\n /**\n * Increment value of counter by the input. Inputs may not be negative.\n */\n add(value: number, attributes?: Attributes, ctx?: Context): void {\n if (value < 0) {\n diag.warn(\n `negative value provided to counter ${this._descriptor.name}: ${value}`\n );\n return;\n }\n\n this._record(value, attributes, ctx);\n }\n}\n\n/**\n * The class implements {@link Gauge} interface.\n */\nexport class GaugeInstrument extends SyncInstrument implements Gauge {\n /**\n * Records a measurement.\n */\n record(value: number, attributes?: Attributes, ctx?: Context): void {\n this._record(value, attributes, ctx);\n }\n}\n\n/**\n * The class implements {@link Histogram} interface.\n */\nexport class HistogramInstrument extends SyncInstrument implements Histogram {\n /**\n * Records a measurement. Value of the measurement must not be negative.\n */\n record(value: number, attributes?: Attributes, ctx?: Context): void {\n if (value < 0) {\n diag.warn(\n `negative value provided to histogram ${this._descriptor.name}: ${value}`\n );\n return;\n }\n this._record(value, attributes, ctx);\n }\n}\n\nexport class ObservableInstrument implements Observable {\n /** @internal */\n _metricStorages: AsyncWritableMetricStorage[];\n /** @internal */\n _descriptor: InstrumentDescriptor;\n private _observableRegistry: ObservableRegistry;\n\n constructor(\n descriptor: InstrumentDescriptor,\n metricStorages: AsyncWritableMetricStorage[],\n observableRegistry: ObservableRegistry\n ) {\n this._descriptor = descriptor;\n this._metricStorages = metricStorages;\n this._observableRegistry = observableRegistry;\n }\n\n /**\n * @see {Observable.addCallback}\n */\n addCallback(callback: ObservableCallback) {\n this._observableRegistry.addCallback(callback, this);\n }\n\n /**\n * @see {Observable.removeCallback}\n */\n removeCallback(callback: ObservableCallback) {\n this._observableRegistry.removeCallback(callback, this);\n }\n}\n\nexport class ObservableCounterInstrument\n extends ObservableInstrument\n implements ObservableCounter {}\nexport class ObservableGaugeInstrument\n extends ObservableInstrument\n implements ObservableGauge {}\nexport class ObservableUpDownCounterInstrument\n extends ObservableInstrument\n implements ObservableUpDownCounter {}\n\nexport function isObservableInstrument(\n it: unknown\n): it is ObservableInstrument {\n return it instanceof ObservableInstrument;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Meter as IMeter,\n MetricOptions,\n Gauge,\n Histogram,\n Counter,\n UpDownCounter,\n ObservableGauge,\n ObservableCounter,\n ObservableUpDownCounter,\n BatchObservableCallback,\n Observable,\n} from '@opentelemetry/api';\nimport { createInstrumentDescriptor } from './InstrumentDescriptor';\nimport {\n CounterInstrument,\n GaugeInstrument,\n HistogramInstrument,\n ObservableCounterInstrument,\n ObservableGaugeInstrument,\n ObservableUpDownCounterInstrument,\n UpDownCounterInstrument,\n} from './Instruments';\nimport type { MeterSharedState } from './state/MeterSharedState';\nimport { InstrumentType } from './export/MetricData';\n\n/**\n * This class implements the {@link IMeter} interface.\n */\nexport class Meter implements IMeter {\n private _meterSharedState: MeterSharedState;\n constructor(meterSharedState: MeterSharedState) {\n this._meterSharedState = meterSharedState;\n }\n\n /**\n * Create a {@link Gauge} instrument.\n */\n createGauge(name: string, options?: MetricOptions): Gauge {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.GAUGE,\n options\n );\n const storage = this._meterSharedState.registerMetricStorage(descriptor);\n return new GaugeInstrument(storage, descriptor);\n }\n\n /**\n * Create a {@link Histogram} instrument.\n */\n createHistogram(name: string, options?: MetricOptions): Histogram {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.HISTOGRAM,\n options\n );\n const storage = this._meterSharedState.registerMetricStorage(descriptor);\n return new HistogramInstrument(storage, descriptor);\n }\n\n /**\n * Create a {@link Counter} instrument.\n */\n createCounter(name: string, options?: MetricOptions): Counter {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.COUNTER,\n options\n );\n const storage = this._meterSharedState.registerMetricStorage(descriptor);\n return new CounterInstrument(storage, descriptor);\n }\n\n /**\n * Create a {@link UpDownCounter} instrument.\n */\n createUpDownCounter(name: string, options?: MetricOptions): UpDownCounter {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.UP_DOWN_COUNTER,\n options\n );\n const storage = this._meterSharedState.registerMetricStorage(descriptor);\n return new UpDownCounterInstrument(storage, descriptor);\n }\n\n /**\n * Create a {@link ObservableGauge} instrument.\n */\n createObservableGauge(\n name: string,\n options?: MetricOptions\n ): ObservableGauge {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.OBSERVABLE_GAUGE,\n options\n );\n const storages =\n this._meterSharedState.registerAsyncMetricStorage(descriptor);\n return new ObservableGaugeInstrument(\n descriptor,\n storages,\n this._meterSharedState.observableRegistry\n );\n }\n\n /**\n * Create a {@link ObservableCounter} instrument.\n */\n createObservableCounter(\n name: string,\n options?: MetricOptions\n ): ObservableCounter {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.OBSERVABLE_COUNTER,\n options\n );\n const storages =\n this._meterSharedState.registerAsyncMetricStorage(descriptor);\n return new ObservableCounterInstrument(\n descriptor,\n storages,\n this._meterSharedState.observableRegistry\n );\n }\n\n /**\n * Create a {@link ObservableUpDownCounter} instrument.\n */\n createObservableUpDownCounter(\n name: string,\n options?: MetricOptions\n ): ObservableUpDownCounter {\n const descriptor = createInstrumentDescriptor(\n name,\n InstrumentType.OBSERVABLE_UP_DOWN_COUNTER,\n options\n );\n const storages =\n this._meterSharedState.registerAsyncMetricStorage(descriptor);\n return new ObservableUpDownCounterInstrument(\n descriptor,\n storages,\n this._meterSharedState.observableRegistry\n );\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n callback: BatchObservableCallback,\n observables: Observable[]\n ) {\n this._meterSharedState.observableRegistry.addBatchCallback(\n callback,\n observables\n );\n }\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(\n callback: BatchObservableCallback,\n observables: Observable[]\n ) {\n this._meterSharedState.observableRegistry.removeBatchCallback(\n callback,\n observables\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type { MetricData } from '../export/MetricData';\nimport type { Maybe } from '../utils';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { createInstrumentDescriptor } from '../InstrumentDescriptor';\n\n/**\n * Internal interface.\n *\n * Represents a storage from which we can collect metrics.\n */\nexport abstract class MetricStorage {\n protected _instrumentDescriptor: InstrumentDescriptor;\n constructor(instrumentDescriptor: InstrumentDescriptor) {\n this._instrumentDescriptor = instrumentDescriptor;\n }\n\n /**\n * Collects the metrics from this storage.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n abstract collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData>;\n\n getInstrumentDescriptor(): Readonly<InstrumentDescriptor> {\n return this._instrumentDescriptor;\n }\n\n updateDescription(description: string): void {\n this._instrumentDescriptor = createInstrumentDescriptor(\n this._instrumentDescriptor.name,\n this._instrumentDescriptor.type,\n {\n description: description,\n valueType: this._instrumentDescriptor.valueType,\n unit: this._instrumentDescriptor.unit,\n advice: this._instrumentDescriptor.advice,\n }\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, Attributes } from '@opentelemetry/api';\nimport { millisToHrTime } from '@opentelemetry/core';\nimport type { Maybe } from '../utils';\nimport { hashAttributes } from '../utils';\nimport type { Accumulation, Aggregator } from '../aggregator/types';\nimport { AttributeHashMap } from './HashMap';\n\n/**\n * Internal interface.\n *\n * Allows synchronous collection of metrics. This processor should allow\n * allocation of new aggregation cells for metrics and convert cumulative\n * recording to delta data points.\n */\nexport class DeltaMetricProcessor<T extends Maybe<Accumulation>> {\n private _activeCollectionStorage = new AttributeHashMap<T>();\n // TODO: find a reasonable mean to clean the memo;\n // https://github.com/open-telemetry/opentelemetry-specification/pull/2208\n private _cumulativeMemoStorage = new AttributeHashMap<T>();\n private _cardinalityLimit: number;\n private _overflowAttributes = { 'otel.metric.overflow': true };\n private _overflowHashCode: string;\n private _aggregator: Aggregator<T>;\n\n constructor(aggregator: Aggregator<T>, aggregationCardinalityLimit?: number) {\n this._aggregator = aggregator;\n this._cardinalityLimit = (aggregationCardinalityLimit ?? 2000) - 1;\n this._overflowHashCode = hashAttributes(this._overflowAttributes);\n }\n\n record(value: number, attributes: Attributes, collectionTime: number) {\n let accumulation = this._activeCollectionStorage.get(attributes);\n\n if (!accumulation) {\n const hrTime = millisToHrTime(collectionTime);\n if (this._activeCollectionStorage.size >= this._cardinalityLimit) {\n const overflowAccumulation = this._activeCollectionStorage.getOrDefault(\n this._overflowAttributes,\n () => this._aggregator.createAccumulation(hrTime)\n );\n overflowAccumulation?.record(value);\n return;\n }\n\n accumulation = this._aggregator.createAccumulation(hrTime);\n this._activeCollectionStorage.set(attributes, accumulation);\n }\n\n accumulation?.record(value);\n }\n\n batchCumulate(\n measurements: AttributeHashMap<number>,\n collectionTime: HrTime\n ) {\n for (const [\n originalAttributes,\n value,\n originalHashCode,\n ] of measurements.entries()) {\n let attributes = originalAttributes;\n let hashCode = originalHashCode;\n const accumulation = this._aggregator.createAccumulation(collectionTime);\n accumulation?.record(value);\n let delta = accumulation;\n // Diff with recorded cumulative memo.\n if (this._cumulativeMemoStorage.has(attributes, hashCode)) {\n // has() returned true, previous is present.\n const previous = this._cumulativeMemoStorage.get(attributes, hashCode)!;\n delta = this._aggregator.diff(previous, accumulation);\n } else {\n // If the cardinality limit is reached, we need to change the attributes\n if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) {\n attributes = this._overflowAttributes;\n hashCode = this._overflowHashCode;\n if (this._cumulativeMemoStorage.has(attributes, hashCode)) {\n // has() returned true, previous is present.\n const previous = this._cumulativeMemoStorage.get(\n attributes,\n hashCode\n )!;\n delta = this._aggregator.diff(previous, accumulation);\n }\n }\n }\n // Merge with uncollected active delta.\n if (this._activeCollectionStorage.has(attributes, hashCode)) {\n // has() returned true, active is present.\n const active = this._activeCollectionStorage.get(attributes, hashCode)!;\n delta = this._aggregator.merge(active, delta);\n }\n\n // Save the current record and the delta record.\n this._cumulativeMemoStorage.set(attributes, accumulation, hashCode);\n this._activeCollectionStorage.set(attributes, delta, hashCode);\n }\n }\n\n /**\n * Returns a collection of delta metrics. Start time is the when first\n * time event collected.\n */\n collect() {\n const unreportedDelta = this._activeCollectionStorage;\n this._activeCollectionStorage = new AttributeHashMap();\n\n return unreportedDelta;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes } from '@opentelemetry/api';\nimport { hashAttributes } from '../utils';\n\nexport interface Hash<ValueType, HashCodeType> {\n (value: ValueType): HashCodeType;\n}\n\nexport class HashMap<KeyType, ValueType, HashCodeType> {\n private _valueMap = new Map<HashCodeType, ValueType>();\n private _keyMap = new Map<HashCodeType, KeyType>();\n private _hash;\n\n constructor(hash: Hash<KeyType, HashCodeType>) {\n this._hash = hash;\n }\n\n get(key: KeyType, hashCode?: HashCodeType) {\n hashCode ??= this._hash(key);\n return this._valueMap.get(hashCode);\n }\n\n getOrDefault(key: KeyType, defaultFactory: () => ValueType) {\n const hash = this._hash(key);\n if (this._valueMap.has(hash)) {\n return this._valueMap.get(hash);\n }\n const val = defaultFactory();\n if (!this._keyMap.has(hash)) {\n this._keyMap.set(hash, key);\n }\n this._valueMap.set(hash, val);\n return val;\n }\n\n set(key: KeyType, value: ValueType, hashCode?: HashCodeType) {\n hashCode ??= this._hash(key);\n if (!this._keyMap.has(hashCode)) {\n this._keyMap.set(hashCode, key);\n }\n this._valueMap.set(hashCode, value);\n }\n\n has(key: KeyType, hashCode?: HashCodeType) {\n hashCode ??= this._hash(key);\n return this._valueMap.has(hashCode);\n }\n\n *keys(): IterableIterator<[KeyType, HashCodeType]> {\n const keyIterator = this._keyMap.entries();\n let next = keyIterator.next();\n while (next.done !== true) {\n yield [next.value[1], next.value[0]];\n next = keyIterator.next();\n }\n }\n\n *entries(): IterableIterator<[KeyType, ValueType, HashCodeType]> {\n const valueIterator = this._valueMap.entries();\n let next = valueIterator.next();\n while (next.done !== true) {\n // next.value[0] here can not be undefined\n yield [this._keyMap.get(next.value[0])!, next.value[1], next.value[0]];\n next = valueIterator.next();\n }\n }\n\n get size() {\n return this._valueMap.size;\n }\n}\n\nexport class AttributeHashMap<ValueType> extends HashMap<\n Attributes,\n ValueType,\n string\n> {\n constructor() {\n super(hashAttributes);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n} from '../aggregator/types';\nimport type { MetricData } from '../export/MetricData';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport type { Maybe } from '../utils';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport { AttributeHashMap } from './HashMap';\n\n/**\n * Remembers what was presented to a specific exporter.\n */\ninterface LastReportedHistory<T extends Maybe<Accumulation>> {\n /**\n * The last accumulation of metric data.\n */\n accumulations: AttributeHashMap<T>;\n /**\n * The timestamp the data was reported.\n */\n collectionTime: HrTime;\n /**\n * The AggregationTemporality used to aggregate reports.\n */\n aggregationTemporality: AggregationTemporality;\n}\n\n/**\n * Internal interface.\n *\n * Provides unique reporting for each collector. Allows synchronous collection\n * of metrics and reports given temporality values.\n */\nexport class TemporalMetricProcessor<T extends Maybe<Accumulation>> {\n private _aggregator: Aggregator<T>;\n private _unreportedAccumulations = new Map<\n MetricCollectorHandle,\n AttributeHashMap<T>[]\n >();\n private _reportHistory = new Map<\n MetricCollectorHandle,\n LastReportedHistory<T>\n >();\n\n constructor(\n aggregator: Aggregator<T>,\n collectorHandles: MetricCollectorHandle[]\n ) {\n this._aggregator = aggregator;\n collectorHandles.forEach(handle => {\n this._unreportedAccumulations.set(handle, []);\n });\n }\n\n /**\n * Builds the {@link MetricData} streams to report against a specific MetricCollector.\n * @param collector The information of the MetricCollector.\n * @param collectors The registered collectors.\n * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with.\n * @param currentAccumulations The current accumulation of metric data from instruments.\n * @param collectionTime The current collection timestamp.\n * @returns The {@link MetricData} points or `null`.\n */\n buildMetrics(\n collector: MetricCollectorHandle,\n instrumentDescriptor: InstrumentDescriptor,\n currentAccumulations: AttributeHashMap<T>,\n collectionTime: HrTime\n ): Maybe<MetricData> {\n this._stashAccumulations(currentAccumulations);\n const unreportedAccumulations =\n this._getMergedUnreportedAccumulations(collector);\n\n let result = unreportedAccumulations;\n let aggregationTemporality: AggregationTemporality;\n // Check our last report time.\n if (this._reportHistory.has(collector)) {\n const last = this._reportHistory.get(collector)!;\n const lastCollectionTime = last.collectionTime;\n aggregationTemporality = last.aggregationTemporality;\n\n // Use aggregation temporality + instrument to determine if we do a merge or a diff of\n // previous. We have the following four scenarios:\n // 1. Cumulative Aggregation (temporality) + Delta recording (sync instrument).\n // Here we merge with our last record to get a cumulative aggregation.\n // 2. Cumulative Aggregation + Cumulative recording (async instrument).\n // Cumulative records are converted to delta recording with DeltaMetricProcessor.\n // Here we merge with our last record to get a cumulative aggregation.\n // 3. Delta Aggregation + Delta recording\n // Calibrate the startTime of metric streams to be the reader's lastCollectionTime.\n // 4. Delta Aggregation + Cumulative recording.\n // Cumulative records are converted to delta recording with DeltaMetricProcessor.\n // Calibrate the startTime of metric streams to be the reader's lastCollectionTime.\n if (aggregationTemporality === AggregationTemporality.CUMULATIVE) {\n // We need to make sure the current delta recording gets merged into the previous cumulative\n // for the next cumulative recording.\n result = TemporalMetricProcessor.merge(\n last.accumulations,\n unreportedAccumulations,\n this._aggregator\n );\n } else {\n result = TemporalMetricProcessor.calibrateStartTime(\n last.accumulations,\n unreportedAccumulations,\n lastCollectionTime\n );\n }\n } else {\n // Call into user code to select aggregation temporality for the instrument.\n aggregationTemporality = collector.selectAggregationTemporality(\n instrumentDescriptor.type\n );\n }\n\n // Update last reported (cumulative) accumulation.\n this._reportHistory.set(collector, {\n accumulations: result,\n collectionTime,\n aggregationTemporality,\n });\n\n const accumulationRecords = AttributesMapToAccumulationRecords(result);\n\n // do not convert to metric data if there is nothing to convert.\n if (accumulationRecords.length === 0) {\n return undefined;\n }\n\n return this._aggregator.toMetricData(\n instrumentDescriptor,\n aggregationTemporality,\n accumulationRecords,\n /* endTime */ collectionTime\n );\n }\n\n private _stashAccumulations(currentAccumulation: AttributeHashMap<T>) {\n const registeredCollectors = this._unreportedAccumulations.keys();\n for (const collector of registeredCollectors) {\n let stash = this._unreportedAccumulations.get(collector);\n if (stash === undefined) {\n stash = [];\n this._unreportedAccumulations.set(collector, stash);\n }\n stash.push(currentAccumulation);\n }\n }\n\n private _getMergedUnreportedAccumulations(collector: MetricCollectorHandle) {\n let result = new AttributeHashMap<T>();\n const unreportedList = this._unreportedAccumulations.get(collector);\n this._unreportedAccumulations.set(collector, []);\n if (unreportedList === undefined) {\n return result;\n }\n for (const it of unreportedList) {\n result = TemporalMetricProcessor.merge(result, it, this._aggregator);\n }\n return result;\n }\n\n static merge<T extends Maybe<Accumulation>>(\n last: AttributeHashMap<T>,\n current: AttributeHashMap<T>,\n aggregator: Aggregator<T>\n ) {\n const result = last;\n const iterator = current.entries();\n let next = iterator.next();\n while (next.done !== true) {\n const [key, record, hash] = next.value;\n if (last.has(key, hash)) {\n const lastAccumulation = last.get(key, hash);\n // last.has() returned true, lastAccumulation is present.\n const accumulation = aggregator.merge(lastAccumulation!, record);\n result.set(key, accumulation, hash);\n } else {\n result.set(key, record, hash);\n }\n\n next = iterator.next();\n }\n return result;\n }\n\n /**\n * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves\n * the new stream to be the initial observation time unchanged.\n */\n static calibrateStartTime<T extends Maybe<Accumulation>>(\n last: AttributeHashMap<T>,\n current: AttributeHashMap<T>,\n lastCollectionTime: HrTime\n ) {\n for (const [key, hash] of last.keys()) {\n const currentAccumulation = current.get(key, hash);\n currentAccumulation?.setStartTime(lastCollectionTime);\n }\n return current;\n }\n}\n\n// TypeScript complains about converting 3 elements tuple to AccumulationRecord<T>.\nfunction AttributesMapToAccumulationRecords<T>(\n map: AttributeHashMap<T>\n): AccumulationRecord<T>[] {\n return Array.from(map.entries()) as unknown as AccumulationRecord<T>[];\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type { Accumulation, Aggregator } from '../aggregator/types';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { MetricStorage } from './MetricStorage';\nimport type { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport type { Maybe } from '../utils';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport { AttributeHashMap } from './HashMap';\nimport type { AsyncWritableMetricStorage } from './WritableMetricStorage';\nimport type { IAttributesProcessor } from '../view/AttributesProcessor';\n\n/**\n * Internal interface.\n *\n * Stores and aggregates {@link MetricData} for asynchronous instruments.\n */\nexport class AsyncMetricStorage<T extends Maybe<Accumulation>>\n extends MetricStorage\n implements AsyncWritableMetricStorage\n{\n private _aggregationCardinalityLimit?: number;\n private _deltaMetricStorage: DeltaMetricProcessor<T>;\n private _temporalMetricStorage: TemporalMetricProcessor<T>;\n private _attributesProcessor?: IAttributesProcessor;\n\n constructor(\n _instrumentDescriptor: InstrumentDescriptor,\n aggregator: Aggregator<T>,\n attributesProcessor: IAttributesProcessor | undefined,\n collectorHandles: MetricCollectorHandle[],\n aggregationCardinalityLimit?: number\n ) {\n super(_instrumentDescriptor);\n this._aggregationCardinalityLimit = aggregationCardinalityLimit;\n this._deltaMetricStorage = new DeltaMetricProcessor(\n aggregator,\n this._aggregationCardinalityLimit\n );\n this._temporalMetricStorage = new TemporalMetricProcessor(\n aggregator,\n collectorHandles\n );\n this._attributesProcessor = attributesProcessor;\n }\n\n record(measurements: AttributeHashMap<number>, observationTime: HrTime) {\n if (this._attributesProcessor === undefined) {\n this._deltaMetricStorage.batchCumulate(measurements, observationTime);\n return;\n }\n const processed = new AttributeHashMap<number>();\n for (const [attributes, value] of measurements.entries()) {\n processed.set(this._attributesProcessor.process(attributes), value);\n }\n this._deltaMetricStorage.batchCumulate(processed, observationTime);\n }\n\n /**\n * Collects the metrics from this storage. The ObservableCallback is invoked\n * during the collection.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData> {\n const accumulations = this._deltaMetricStorage.collect();\n\n return this._temporalMetricStorage.buildMetrics(\n collector,\n this._instrumentDescriptor,\n accumulations,\n collectionTime\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { MetricStorage } from './MetricStorage';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { isDescriptorCompatibleWith } from '../InstrumentDescriptor';\nimport * as api from '@opentelemetry/api';\nimport {\n getConflictResolutionRecipe,\n getIncompatibilityDetails,\n} from '../view/RegistrationConflicts';\nimport type { MetricCollectorHandle } from './MetricCollector';\n\ntype StorageMap = Map<string, MetricStorage[]>;\n\n/**\n * Internal class for storing {@link MetricStorage}\n */\nexport class MetricStorageRegistry {\n private readonly _sharedRegistry: StorageMap = new Map();\n private readonly _perCollectorRegistry = new Map<\n MetricCollectorHandle,\n StorageMap\n >();\n\n static create() {\n return new MetricStorageRegistry();\n }\n\n getStorages(collector: MetricCollectorHandle): MetricStorage[] {\n let storages: MetricStorage[] = [];\n for (const metricStorages of this._sharedRegistry.values()) {\n storages = storages.concat(metricStorages);\n }\n\n const perCollectorStorages = this._perCollectorRegistry.get(collector);\n if (perCollectorStorages != null) {\n for (const metricStorages of perCollectorStorages.values()) {\n storages = storages.concat(metricStorages);\n }\n }\n\n return storages;\n }\n\n register(storage: MetricStorage) {\n this._registerStorage(storage, this._sharedRegistry);\n }\n\n registerForCollector(\n collector: MetricCollectorHandle,\n storage: MetricStorage\n ) {\n let storageMap = this._perCollectorRegistry.get(collector);\n if (storageMap == null) {\n storageMap = new Map();\n this._perCollectorRegistry.set(collector, storageMap);\n }\n this._registerStorage(storage, storageMap);\n }\n\n findOrUpdateCompatibleStorage<T extends MetricStorage>(\n expectedDescriptor: InstrumentDescriptor\n ): T | null {\n const storages = this._sharedRegistry.get(expectedDescriptor.name);\n if (storages === undefined) {\n return null;\n }\n\n // If the descriptor is compatible, the type of their metric storage\n // (either SyncMetricStorage or AsyncMetricStorage) must be compatible.\n return this._findOrUpdateCompatibleStorage<T>(expectedDescriptor, storages);\n }\n\n findOrUpdateCompatibleCollectorStorage<T extends MetricStorage>(\n collector: MetricCollectorHandle,\n expectedDescriptor: InstrumentDescriptor\n ): T | null {\n const storageMap = this._perCollectorRegistry.get(collector);\n if (storageMap === undefined) {\n return null;\n }\n\n const storages = storageMap.get(expectedDescriptor.name);\n if (storages === undefined) {\n return null;\n }\n\n // If the descriptor is compatible, the type of their metric storage\n // (either SyncMetricStorage or AsyncMetricStorage) must be compatible.\n return this._findOrUpdateCompatibleStorage<T>(expectedDescriptor, storages);\n }\n\n private _registerStorage(storage: MetricStorage, storageMap: StorageMap) {\n const descriptor = storage.getInstrumentDescriptor();\n const storages = storageMap.get(descriptor.name);\n\n if (storages === undefined) {\n storageMap.set(descriptor.name, [storage]);\n return;\n }\n\n storages.push(storage);\n }\n\n private _findOrUpdateCompatibleStorage<T extends MetricStorage>(\n expectedDescriptor: InstrumentDescriptor,\n existingStorages: MetricStorage[]\n ): T | null {\n let compatibleStorage = null;\n\n for (const existingStorage of existingStorages) {\n const existingDescriptor = existingStorage.getInstrumentDescriptor();\n\n if (isDescriptorCompatibleWith(existingDescriptor, expectedDescriptor)) {\n // Use the longer description if it does not match.\n if (existingDescriptor.description !== expectedDescriptor.description) {\n if (\n expectedDescriptor.description.length >\n existingDescriptor.description.length\n ) {\n existingStorage.updateDescription(expectedDescriptor.description);\n }\n\n api.diag.warn(\n 'A view or instrument with the name ',\n expectedDescriptor.name,\n ' has already been registered, but has a different description and is incompatible with another registered view.\\n',\n 'Details:\\n',\n getIncompatibilityDetails(existingDescriptor, expectedDescriptor),\n 'The longer description will be used.\\nTo resolve the conflict:',\n getConflictResolutionRecipe(existingDescriptor, expectedDescriptor)\n );\n }\n // Storage is fully compatible. There will never be more than one pre-existing fully compatible storage.\n compatibleStorage = existingStorage as T;\n } else {\n // The implementation SHOULD warn about duplicate instrument registration\n // conflicts after applying View configuration.\n api.diag.warn(\n 'A view or instrument with the name ',\n expectedDescriptor.name,\n ' has already been registered and is incompatible with another registered view.\\n',\n 'Details:\\n',\n getIncompatibilityDetails(existingDescriptor, expectedDescriptor),\n 'To resolve the conflict:\\n',\n getConflictResolutionRecipe(existingDescriptor, expectedDescriptor)\n );\n }\n }\n\n return compatibleStorage;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentSelectorCriteria } from './InstrumentSelector';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\n\nexport function getIncompatibilityDetails(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n) {\n let incompatibility = '';\n if (existing.unit !== otherDescriptor.unit) {\n incompatibility += `\\t- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'\\n`;\n }\n if (existing.type !== otherDescriptor.type) {\n incompatibility += `\\t- Type '${existing.type}' does not match '${otherDescriptor.type}'\\n`;\n }\n if (existing.valueType !== otherDescriptor.valueType) {\n incompatibility += `\\t- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'\\n`;\n }\n if (existing.description !== otherDescriptor.description) {\n incompatibility += `\\t- Description '${existing.description}' does not match '${otherDescriptor.description}'\\n`;\n }\n\n return incompatibility;\n}\n\nexport function getValueTypeConflictResolutionRecipe(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n) {\n return `\\t- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;\n}\n\nexport function getUnitConflictResolutionRecipe(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n) {\n return `\\t- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;\n}\n\nexport function getTypeConflictResolutionRecipe(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n) {\n const selector: InstrumentSelectorCriteria = {\n name: otherDescriptor.name,\n type: otherDescriptor.type,\n unit: otherDescriptor.unit,\n };\n\n const selectorString = JSON.stringify(selector);\n\n return `\\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`;\n}\n\nexport function getDescriptionResolutionRecipe(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n): string {\n const selector: InstrumentSelectorCriteria = {\n name: otherDescriptor.name,\n type: otherDescriptor.type,\n unit: otherDescriptor.unit,\n };\n\n const selectorString = JSON.stringify(selector);\n\n return `\\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'\n \\t- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString}\n \\t- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`;\n}\n\nexport function getConflictResolutionRecipe(\n existing: InstrumentDescriptor,\n otherDescriptor: InstrumentDescriptor\n): string {\n // Conflicts that cannot be solved via views.\n if (existing.valueType !== otherDescriptor.valueType) {\n return getValueTypeConflictResolutionRecipe(existing, otherDescriptor);\n }\n\n if (existing.unit !== otherDescriptor.unit) {\n return getUnitConflictResolutionRecipe(existing, otherDescriptor);\n }\n\n // Conflicts that can be solved via views.\n if (existing.type !== otherDescriptor.type) {\n // this will automatically solve possible description conflicts.\n return getTypeConflictResolutionRecipe(existing, otherDescriptor);\n }\n\n if (existing.description !== otherDescriptor.description) {\n return getDescriptionResolutionRecipe(existing, otherDescriptor);\n }\n\n return '';\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Attributes } from '@opentelemetry/api';\nimport { context as contextApi } from '@opentelemetry/api';\nimport type { WritableMetricStorage } from './WritableMetricStorage';\n\n/**\n * Internal interface.\n */\nexport class MultiMetricStorage implements WritableMetricStorage {\n private readonly _backingStorages: WritableMetricStorage[];\n readonly hasAttributeProcessor: boolean;\n\n constructor(backingStorages: WritableMetricStorage[]) {\n this._backingStorages = backingStorages;\n this.hasAttributeProcessor = backingStorages.some(\n s => s.hasAttributeProcessor\n );\n }\n\n record(\n value: number,\n attributes: Attributes,\n context: Context | undefined,\n recordTime: number\n ) {\n if (this.hasAttributeProcessor && context === undefined) {\n context = contextApi.active();\n }\n const storages = this._backingStorages;\n for (let i = 0; i < storages.length; i++) {\n storages[i].record(value, attributes, context, recordTime);\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n HrTime,\n BatchObservableCallback,\n Observable,\n ObservableCallback,\n} from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ObservableInstrument } from '../Instruments';\nimport { isObservableInstrument } from '../Instruments';\nimport {\n BatchObservableResultImpl,\n ObservableResultImpl,\n} from '../ObservableResult';\nimport { callWithTimeout, setEquals } from '../utils';\n\n/**\n * Records for single instrument observable callback.\n */\ninterface ObservableCallbackRecord {\n callback: ObservableCallback;\n instrument: ObservableInstrument;\n}\n\n/**\n * Records for multiple instruments observable callback.\n */\ninterface BatchObservableCallbackRecord {\n callback: BatchObservableCallback;\n instruments: Set<ObservableInstrument>;\n}\n\n/**\n * An internal interface for managing ObservableCallbacks.\n *\n * Every registered callback associated with a set of instruments are be evaluated\n * exactly once during collection prior to reading data for that instrument.\n */\nexport class ObservableRegistry {\n private _callbacks: ObservableCallbackRecord[] = [];\n private _batchCallbacks: BatchObservableCallbackRecord[] = [];\n\n addCallback(callback: ObservableCallback, instrument: ObservableInstrument) {\n const idx = this._findCallback(callback, instrument);\n if (idx >= 0) {\n return;\n }\n this._callbacks.push({ callback, instrument });\n }\n\n removeCallback(\n callback: ObservableCallback,\n instrument: ObservableInstrument\n ) {\n const idx = this._findCallback(callback, instrument);\n if (idx < 0) {\n return;\n }\n this._callbacks.splice(idx, 1);\n }\n\n addBatchCallback(\n callback: BatchObservableCallback,\n instruments: Observable[]\n ) {\n // Create a set of unique instruments.\n const observableInstruments = new Set(\n instruments.filter(isObservableInstrument)\n );\n if (observableInstruments.size === 0) {\n diag.error(\n 'BatchObservableCallback is not associated with valid instruments',\n instruments\n );\n return;\n }\n const idx = this._findBatchCallback(callback, observableInstruments);\n if (idx >= 0) {\n return;\n }\n this._batchCallbacks.push({ callback, instruments: observableInstruments });\n }\n\n removeBatchCallback(\n callback: BatchObservableCallback,\n instruments: Observable[]\n ) {\n // Create a set of unique instruments.\n const observableInstruments = new Set(\n instruments.filter(isObservableInstrument)\n );\n const idx = this._findBatchCallback(callback, observableInstruments);\n if (idx < 0) {\n return;\n }\n this._batchCallbacks.splice(idx, 1);\n }\n\n /**\n * @returns a promise of rejected reasons for invoking callbacks.\n */\n async observe(\n collectionTime: HrTime,\n timeoutMillis?: number\n ): Promise<unknown[]> {\n const callbackFutures = this._observeCallbacks(\n collectionTime,\n timeoutMillis\n );\n const batchCallbackFutures = this._observeBatchCallbacks(\n collectionTime,\n timeoutMillis\n );\n\n const results = await Promise.allSettled([\n ...callbackFutures,\n ...batchCallbackFutures,\n ]);\n\n const rejections = results\n .filter(result => result.status === 'rejected')\n .map(result => (result as PromiseRejectedResult).reason);\n return rejections;\n }\n\n private _observeCallbacks(observationTime: HrTime, timeoutMillis?: number) {\n return this._callbacks.map(async ({ callback, instrument }) => {\n const observableResult = new ObservableResultImpl(\n instrument._descriptor.name,\n instrument._descriptor.valueType\n );\n let callPromise: Promise<void> = Promise.resolve(\n callback(observableResult)\n );\n if (timeoutMillis != null) {\n callPromise = callWithTimeout(callPromise, timeoutMillis);\n }\n await callPromise;\n instrument._metricStorages.forEach(metricStorage => {\n metricStorage.record(observableResult._buffer, observationTime);\n });\n });\n }\n\n private _observeBatchCallbacks(\n observationTime: HrTime,\n timeoutMillis?: number\n ) {\n return this._batchCallbacks.map(async ({ callback, instruments }) => {\n const observableResult = new BatchObservableResultImpl();\n let callPromise: Promise<void> = Promise.resolve(\n callback(observableResult)\n );\n if (timeoutMillis != null) {\n callPromise = callWithTimeout(callPromise, timeoutMillis);\n }\n await callPromise;\n instruments.forEach(instrument => {\n const buffer = observableResult._buffer.get(instrument);\n if (buffer == null) {\n return;\n }\n instrument._metricStorages.forEach(metricStorage => {\n metricStorage.record(buffer, observationTime);\n });\n });\n });\n }\n\n private _findCallback(\n callback: ObservableCallback,\n instrument: ObservableInstrument\n ) {\n return this._callbacks.findIndex(record => {\n return record.callback === callback && record.instrument === instrument;\n });\n }\n\n private _findBatchCallback(\n callback: BatchObservableCallback,\n instruments: Set<ObservableInstrument>\n ) {\n return this._batchCallbacks.findIndex(record => {\n return (\n record.callback === callback &&\n setEquals(record.instruments, instruments)\n );\n });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n ObservableResult,\n Attributes,\n BatchObservableResult,\n Observable,\n} from '@opentelemetry/api';\nimport { diag, ValueType } from '@opentelemetry/api';\nimport { AttributeHashMap } from './state/HashMap';\nimport type { ObservableInstrument } from './Instruments';\nimport { isObservableInstrument } from './Instruments';\n\n/**\n * The class implements {@link ObservableResult} interface.\n */\nexport class ObservableResultImpl implements ObservableResult {\n /**\n * @internal\n */\n _buffer = new AttributeHashMap<number>();\n private _instrumentName: string;\n private _valueType: ValueType;\n\n constructor(instrumentName: string, valueType: ValueType) {\n this._instrumentName = instrumentName;\n this._valueType = valueType;\n }\n\n /**\n * Observe a measurement of the value associated with the given attributes.\n */\n observe(value: number, attributes: Attributes = {}): void {\n if (typeof value !== 'number') {\n diag.warn(\n `non-number value provided to metric ${this._instrumentName}: ${value}`\n );\n return;\n }\n if (this._valueType === ValueType.INT && !Number.isInteger(value)) {\n diag.warn(\n `INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`\n );\n value = Math.trunc(value);\n // ignore non-finite values.\n if (!Number.isInteger(value)) {\n return;\n }\n }\n this._buffer.set(attributes, value);\n }\n}\n\n/**\n * The class implements {@link BatchObservableCallback} interface.\n */\nexport class BatchObservableResultImpl implements BatchObservableResult {\n /**\n * @internal\n */\n _buffer: Map<ObservableInstrument, AttributeHashMap<number>> = new Map();\n\n /**\n * Observe a measurement of the value associated with the given attributes.\n */\n observe(\n metric: Observable,\n value: number,\n attributes: Attributes = {}\n ): void {\n if (!isObservableInstrument(metric)) {\n return;\n }\n let map = this._buffer.get(metric);\n if (map == null) {\n map = new AttributeHashMap();\n this._buffer.set(metric, map);\n }\n if (typeof value !== 'number') {\n diag.warn(\n `non-number value provided to metric ${metric._descriptor.name}: ${value}`\n );\n return;\n }\n if (\n metric._descriptor.valueType === ValueType.INT &&\n !Number.isInteger(value)\n ) {\n diag.warn(\n `INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`\n );\n value = Math.trunc(value);\n // ignore non-finite values.\n if (!Number.isInteger(value)) {\n return;\n }\n }\n map.set(attributes, value);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { context as contextApi } from '@opentelemetry/api';\nimport type { WritableMetricStorage } from './WritableMetricStorage';\nimport type { Accumulation, Aggregator } from '../aggregator/types';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport type { IAttributesProcessor } from '../view/AttributesProcessor';\nimport { MetricStorage } from './MetricStorage';\nimport type { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport type { Maybe } from '../utils';\nimport type { MetricCollectorHandle } from './MetricCollector';\n\n/**\n * Internal interface.\n *\n * Stores and aggregates {@link MetricData} for synchronous instruments.\n */\nexport class SyncMetricStorage<T extends Maybe<Accumulation>>\n extends MetricStorage\n implements WritableMetricStorage\n{\n private _aggregationCardinalityLimit?: number;\n private _deltaMetricStorage: DeltaMetricProcessor<T>;\n private _temporalMetricStorage: TemporalMetricProcessor<T>;\n private _attributesProcessor?: IAttributesProcessor;\n\n constructor(\n instrumentDescriptor: InstrumentDescriptor,\n aggregator: Aggregator<T>,\n attributesProcessor: IAttributesProcessor | undefined,\n collectorHandles: MetricCollectorHandle[],\n aggregationCardinalityLimit?: number\n ) {\n super(instrumentDescriptor);\n this._aggregationCardinalityLimit = aggregationCardinalityLimit;\n this._deltaMetricStorage = new DeltaMetricProcessor(\n aggregator,\n this._aggregationCardinalityLimit\n );\n this._temporalMetricStorage = new TemporalMetricProcessor(\n aggregator,\n collectorHandles\n );\n this._attributesProcessor = attributesProcessor;\n this.hasAttributeProcessor = attributesProcessor !== undefined;\n }\n\n readonly hasAttributeProcessor: boolean;\n\n record(\n value: number,\n attributes: Attributes,\n context: Context | undefined,\n recordTime: number\n ) {\n if (this._attributesProcessor !== undefined) {\n attributes = this._attributesProcessor.process(\n attributes,\n context ?? contextApi.active()\n );\n }\n this._deltaMetricStorage.record(value, attributes, recordTime);\n }\n\n /**\n * Collects the metrics from this storage.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData> {\n const accumulations = this._deltaMetricStorage.collect();\n\n return this._temporalMetricStorage.buildMetrics(\n collector,\n this._instrumentDescriptor,\n accumulations,\n collectionTime\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { MetricCollectOptions } from '../export/MetricProducer';\nimport type { MetricData, ScopeMetrics } from '../export/MetricData';\nimport type { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { createInstrumentDescriptorWithView } from '../InstrumentDescriptor';\nimport { Meter } from '../Meter';\nimport type { Maybe } from '../utils';\nimport { AsyncMetricStorage } from './AsyncMetricStorage';\nimport type { MeterProviderSharedState } from './MeterProviderSharedState';\nimport type { MetricCollectorHandle } from './MetricCollector';\nimport { MetricStorageRegistry } from './MetricStorageRegistry';\nimport { MultiMetricStorage } from './MultiWritableMetricStorage';\nimport { ObservableRegistry } from './ObservableRegistry';\nimport { SyncMetricStorage } from './SyncMetricStorage';\nimport type { Accumulation, Aggregator } from '../aggregator/types';\nimport type { IAttributesProcessor } from '../view/AttributesProcessor';\nimport type { MetricStorage } from './MetricStorage';\n\n/**\n * An internal record for shared meter provider states.\n */\nexport class MeterSharedState {\n metricStorageRegistry = new MetricStorageRegistry();\n observableRegistry = new ObservableRegistry();\n meter: Meter;\n private _meterProviderSharedState: MeterProviderSharedState;\n private _instrumentationScope: InstrumentationScope;\n\n constructor(\n meterProviderSharedState: MeterProviderSharedState,\n instrumentationScope: InstrumentationScope\n ) {\n this.meter = new Meter(this);\n this._meterProviderSharedState = meterProviderSharedState;\n this._instrumentationScope = instrumentationScope;\n }\n\n registerMetricStorage(descriptor: InstrumentDescriptor) {\n const storages = this._registerMetricStorage(descriptor, SyncMetricStorage);\n\n if (storages.length === 1) {\n return storages[0];\n }\n return new MultiMetricStorage(storages);\n }\n\n registerAsyncMetricStorage(descriptor: InstrumentDescriptor) {\n const storages = this._registerMetricStorage(\n descriptor,\n AsyncMetricStorage\n );\n\n return storages;\n }\n\n /**\n * @param collector opaque handle of {@link MetricCollector} which initiated the collection.\n * @param collectionTime the HrTime at which the collection was initiated.\n * @param options options for collection.\n * @returns the list of metric data collected.\n */\n async collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime,\n options?: MetricCollectOptions\n ): Promise<ScopeMetricsResult | null> {\n /**\n * 1. Call all observable callbacks first.\n * 2. Collect metric result for the collector.\n */\n const errors = await this.observableRegistry.observe(\n collectionTime,\n options?.timeoutMillis\n );\n const storages = this.metricStorageRegistry.getStorages(collector);\n\n // prevent more allocations if there are no storages.\n if (storages.length === 0) {\n return null;\n }\n\n const metricDataList: MetricData[] = [];\n storages.forEach(metricStorage => {\n const metricData = metricStorage.collect(collector, collectionTime);\n\n if (metricData != null) {\n metricDataList.push(metricData);\n }\n });\n\n // skip this scope if no data was collected (storage created, but no data observed)\n if (metricDataList.length === 0) {\n return { errors };\n }\n\n return {\n scopeMetrics: {\n scope: this._instrumentationScope,\n metrics: metricDataList,\n },\n errors,\n };\n }\n\n private _registerMetricStorage<\n MetricStorageType extends MetricStorageConstructor,\n R extends InstanceType<MetricStorageType>,\n >(\n descriptor: InstrumentDescriptor,\n MetricStorageType: MetricStorageType\n ): R[] {\n const views = this._meterProviderSharedState.viewRegistry.findViews(\n descriptor,\n this._instrumentationScope\n );\n let storages = views.map(view => {\n const viewDescriptor = createInstrumentDescriptorWithView(\n view,\n descriptor\n );\n const compatibleStorage =\n this.metricStorageRegistry.findOrUpdateCompatibleStorage<R>(\n viewDescriptor\n );\n if (compatibleStorage != null) {\n return compatibleStorage;\n }\n const aggregator = view.aggregation.createAggregator(viewDescriptor);\n const viewStorage = new MetricStorageType(\n viewDescriptor,\n aggregator,\n view.attributesProcessor,\n this._meterProviderSharedState.metricCollectors,\n view.aggregationCardinalityLimit\n ) as R;\n this.metricStorageRegistry.register(viewStorage);\n return viewStorage;\n });\n\n // Fallback to the per-collector aggregations if no view is configured for the instrument.\n if (storages.length === 0) {\n const perCollectorAggregations =\n this._meterProviderSharedState.selectAggregations(descriptor.type);\n const collectorStorages = perCollectorAggregations.map(\n ([collector, aggregation]) => {\n const compatibleStorage =\n this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage<R>(\n collector,\n descriptor\n );\n if (compatibleStorage != null) {\n return compatibleStorage;\n }\n\n const aggregator = aggregation.createAggregator(descriptor);\n const cardinalityLimit = collector.selectCardinalityLimit(\n descriptor.type\n );\n const storage = new MetricStorageType(\n descriptor,\n aggregator,\n undefined,\n [collector],\n cardinalityLimit\n ) as R;\n this.metricStorageRegistry.registerForCollector(collector, storage);\n return storage;\n }\n );\n storages = storages.concat(collectorStorages);\n }\n\n return storages;\n }\n}\n\ninterface ScopeMetricsResult {\n scopeMetrics?: ScopeMetrics;\n errors: unknown[];\n}\n\ninterface MetricStorageConstructor {\n new (\n instrumentDescriptor: InstrumentDescriptor,\n aggregator: Aggregator<Maybe<Accumulation>>,\n attributesProcessor: IAttributesProcessor | undefined,\n collectors: MetricCollectorHandle[],\n aggregationCardinalityLimit?: number\n ): MetricStorage;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { instrumentationScopeId } from '../utils';\nimport { ViewRegistry } from '../view/ViewRegistry';\nimport { MeterSharedState } from './MeterSharedState';\nimport type { MetricCollector, MetricCollectorHandle } from './MetricCollector';\nimport { toAggregation } from '../view/AggregationOption';\nimport type { Aggregation } from '../view/Aggregation';\nimport type { InstrumentType } from '../export/MetricData';\n\n/**\n * An internal record for shared meter provider states.\n */\nexport class MeterProviderSharedState {\n viewRegistry = new ViewRegistry();\n\n metricCollectors: MetricCollector[] = [];\n\n meterSharedStates: Map<string, MeterSharedState> = new Map();\n public resource: Resource;\n\n constructor(resource: Resource) {\n this.resource = resource;\n }\n\n getMeterSharedState(instrumentationScope: InstrumentationScope) {\n const id = instrumentationScopeId(instrumentationScope);\n let meterSharedState = this.meterSharedStates.get(id);\n if (meterSharedState == null) {\n meterSharedState = new MeterSharedState(this, instrumentationScope);\n this.meterSharedStates.set(id, meterSharedState);\n }\n return meterSharedState;\n }\n\n selectAggregations(instrumentType: InstrumentType) {\n const result: [MetricCollectorHandle, Aggregation][] = [];\n for (const collector of this.metricCollectors) {\n result.push([\n collector,\n toAggregation(collector.selectAggregation(instrumentType)),\n ]);\n }\n return result;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { millisToHrTime } from '@opentelemetry/core';\nimport type { AggregationTemporalitySelector } from '../export/AggregationSelector';\nimport type {\n CollectionResult,\n InstrumentType,\n ScopeMetrics,\n} from '../export/MetricData';\nimport type {\n MetricCollectOptions,\n MetricProducer,\n} from '../export/MetricProducer';\nimport type { IMetricReader } from '../export/MetricReader';\nimport type { ForceFlushOptions, ShutdownOptions } from '../types';\nimport type { MeterProviderSharedState } from './MeterProviderSharedState';\n\n/**\n * An internal opaque interface that the MetricReader receives as\n * MetricProducer. It acts as the storage key to the internal metric stream\n * state for each MetricReader.\n */\nexport class MetricCollector implements MetricProducer {\n private _sharedState: MeterProviderSharedState;\n private _metricReader: IMetricReader;\n\n constructor(\n sharedState: MeterProviderSharedState,\n metricReader: IMetricReader\n ) {\n this._sharedState = sharedState;\n this._metricReader = metricReader;\n }\n\n async collect(options?: MetricCollectOptions): Promise<CollectionResult> {\n const collectionTime = millisToHrTime(Date.now());\n const scopeMetrics: ScopeMetrics[] = [];\n const errors: unknown[] = [];\n\n const meterCollectionPromises = Array.from(\n this._sharedState.meterSharedStates.values()\n ).map(async meterSharedState => {\n const current = await meterSharedState.collect(\n this,\n collectionTime,\n options\n );\n\n // only add scope metrics if available\n if (current?.scopeMetrics != null) {\n scopeMetrics.push(current.scopeMetrics);\n }\n\n // only add errors if available\n if (current?.errors != null) {\n errors.push(...current.errors);\n }\n });\n await Promise.all(meterCollectionPromises);\n\n return {\n resourceMetrics: {\n resource: this._sharedState.resource,\n scopeMetrics: scopeMetrics,\n },\n errors: errors,\n };\n }\n\n /**\n * Delegates for MetricReader.forceFlush.\n */\n async forceFlush(options?: ForceFlushOptions): Promise<void> {\n await this._metricReader.forceFlush(options);\n }\n\n /**\n * Delegates for MetricReader.shutdown.\n */\n async shutdown(options?: ShutdownOptions): Promise<void> {\n await this._metricReader.shutdown(options);\n }\n\n selectAggregationTemporality(instrumentType: InstrumentType) {\n return this._metricReader.selectAggregationTemporality(instrumentType);\n }\n\n selectAggregation(instrumentType: InstrumentType) {\n return this._metricReader.selectAggregation(instrumentType);\n }\n\n /**\n * Select the cardinality limit for the given {@link InstrumentType} for this\n * collector.\n */\n selectCardinalityLimit(instrumentType: InstrumentType): number {\n return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2000;\n }\n}\n\n/**\n * An internal interface for MetricCollector. Exposes the necessary\n * information for metric collection.\n */\nexport interface MetricCollectorHandle {\n selectAggregationTemporality: AggregationTemporalitySelector;\n selectCardinalityLimit(instrumentType: InstrumentType): number;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// https://tc39.es/proposal-regex-escaping\n// escape ^ $ \\ . + ? ( ) [ ] { } |\n// do not need to escape * as we interpret it as wildcard\nconst ESCAPE = /[\\^$\\\\.+?()[\\]{}|]/g;\n\nexport interface Predicate {\n match(str: string): boolean;\n}\n\n/**\n * Wildcard pattern predicate, supports patterns like `*`, `foo*`, `*bar`.\n */\nexport class PatternPredicate implements Predicate {\n private _matchAll: boolean;\n private _regexp: RegExp;\n\n constructor(pattern: string) {\n if (pattern === '*') {\n this._matchAll = true;\n this._regexp = /.*/;\n } else {\n this._matchAll = false;\n this._regexp = new RegExp(PatternPredicate.escapePattern(pattern));\n }\n }\n\n match(str: string): boolean {\n if (this._matchAll) {\n return true;\n }\n\n return this._regexp.test(str);\n }\n\n static escapePattern(pattern: string): string {\n return `^${pattern.replace(ESCAPE, '\\\\$&').replace('*', '.*')}$`;\n }\n\n static hasWildcard(pattern: string): boolean {\n return pattern.includes('*');\n }\n}\n\nexport class ExactPredicate implements Predicate {\n private _matchAll: boolean;\n private _pattern?: string;\n\n constructor(pattern?: string) {\n this._matchAll = pattern === undefined;\n this._pattern = pattern;\n }\n\n match(str: string): boolean {\n if (this._matchAll) {\n return true;\n }\n if (str === this._pattern) {\n return true;\n }\n return false;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Attributes } from '@opentelemetry/api';\n\n/**\n * The {@link AttributesProcessor} is responsible for customizing which\n * attribute(s) are to be reported as metrics dimension(s) and adding\n * additional dimension(s) from the {@link Context}.\n */\nexport interface IAttributesProcessor {\n /**\n * Process the metric instrument attributes.\n *\n * @param incoming The metric instrument attributes.\n * @param context The active context when the instrument is synchronous.\n * `undefined` otherwise.\n */\n process: (incoming: Attributes, context?: Context) => Attributes;\n}\n\nclass NoopAttributesProcessor implements IAttributesProcessor {\n process(incoming: Attributes, _context?: Context) {\n return incoming;\n }\n}\n\nclass MultiAttributesProcessor implements IAttributesProcessor {\n private readonly _processors: IAttributesProcessor[];\n constructor(processors: IAttributesProcessor[]) {\n this._processors = processors;\n }\n process(incoming: Attributes, context?: Context): Attributes {\n let filteredAttributes = incoming;\n for (const processor of this._processors) {\n filteredAttributes = processor.process(filteredAttributes, context);\n }\n return filteredAttributes;\n }\n}\n\nclass AllowListProcessor implements IAttributesProcessor {\n private readonly _allowedAttributeNames: Set<string>;\n constructor(allowedAttributeNames: string[]) {\n this._allowedAttributeNames = new Set(allowedAttributeNames);\n }\n\n process(incoming: Attributes, _context?: Context): Attributes {\n const filteredAttributes: Attributes = {};\n for (const attributeName in incoming) {\n if (\n Object.prototype.hasOwnProperty.call(incoming, attributeName) &&\n this._allowedAttributeNames.has(attributeName)\n ) {\n filteredAttributes[attributeName] = incoming[attributeName];\n }\n }\n return filteredAttributes;\n }\n}\n\nclass DenyListProcessor implements IAttributesProcessor {\n private readonly _deniedAttributeNames: Set<string>;\n constructor(deniedAttributeNames: string[]) {\n this._deniedAttributeNames = new Set(deniedAttributeNames);\n }\n\n process(incoming: Attributes, _context?: Context): Attributes {\n const filteredAttributes: Attributes = {};\n for (const attributeName in incoming) {\n if (\n Object.prototype.hasOwnProperty.call(incoming, attributeName) &&\n !this._deniedAttributeNames.has(attributeName)\n ) {\n filteredAttributes[attributeName] = incoming[attributeName];\n }\n }\n return filteredAttributes;\n }\n}\n\n/**\n * @internal\n *\n * Create an {@link IAttributesProcessor} that acts as a simple pass-through for attributes.\n */\nexport function createNoopAttributesProcessor(): IAttributesProcessor {\n return NOOP;\n}\n\n/**\n * @internal\n *\n * Create an {@link IAttributesProcessor} that applies all processors from the provided list in order.\n *\n * @param processors Processors to apply in order.\n */\nexport function createMultiAttributesProcessor(\n processors: IAttributesProcessor[]\n): IAttributesProcessor {\n return new MultiAttributesProcessor(processors);\n}\n\n/**\n * Create an {@link IAttributesProcessor} that filters by allowed attribute names and drops any names that are not in the\n * allow list.\n */\nexport function createAllowListAttributesProcessor(\n attributeAllowList: string[]\n): IAttributesProcessor {\n return new AllowListProcessor(attributeAllowList);\n}\n\n/**\n * Create an {@link IAttributesProcessor} that drops attributes based on the names provided in the deny list\n */\nexport function createDenyListAttributesProcessor(\n attributeDenyList: string[]\n): IAttributesProcessor {\n return new DenyListProcessor(attributeDenyList);\n}\n\nconst NOOP = new NoopAttributesProcessor();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Predicate } from './Predicate';\nimport { ExactPredicate, PatternPredicate } from './Predicate';\nimport type { InstrumentType } from '../export/MetricData';\n\nexport interface InstrumentSelectorCriteria {\n name?: string;\n type?: InstrumentType;\n unit?: string;\n}\n\nexport class InstrumentSelector {\n private _nameFilter: Predicate;\n private _type?: InstrumentType;\n private _unitFilter: Predicate;\n\n constructor(criteria?: InstrumentSelectorCriteria) {\n this._nameFilter = new PatternPredicate(criteria?.name ?? '*');\n this._type = criteria?.type;\n this._unitFilter = new ExactPredicate(criteria?.unit);\n }\n\n getType() {\n return this._type;\n }\n\n getNameFilter() {\n return this._nameFilter;\n }\n\n getUnitFilter() {\n return this._unitFilter;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Predicate } from './Predicate';\nimport { ExactPredicate } from './Predicate';\n\nexport interface MeterSelectorCriteria {\n name?: string;\n version?: string;\n schemaUrl?: string;\n}\n\nexport class MeterSelector {\n private _nameFilter: Predicate;\n private _versionFilter: Predicate;\n private _schemaUrlFilter: Predicate;\n\n constructor(criteria?: MeterSelectorCriteria) {\n this._nameFilter = new ExactPredicate(criteria?.name);\n this._versionFilter = new ExactPredicate(criteria?.version);\n this._schemaUrlFilter = new ExactPredicate(criteria?.schemaUrl);\n }\n\n getNameFilter() {\n return this._nameFilter;\n }\n\n /**\n * TODO: semver filter? no spec yet.\n */\n getVersionFilter() {\n return this._versionFilter;\n }\n\n getSchemaUrlFilter() {\n return this._schemaUrlFilter;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { PatternPredicate } from './Predicate';\nimport type { IAttributesProcessor } from './AttributesProcessor';\nimport {\n createMultiAttributesProcessor,\n createNoopAttributesProcessor,\n} from './AttributesProcessor';\nimport { InstrumentSelector } from './InstrumentSelector';\nimport { MeterSelector } from './MeterSelector';\nimport type { Aggregation } from './Aggregation';\nimport type { AggregationOption } from './AggregationOption';\nimport { AggregationType, toAggregation } from './AggregationOption';\nimport type { InstrumentType } from '../export/MetricData';\n\nexport type ViewOptions = {\n /**\n * Alters the metric stream:\n * This will be used as the name of the metrics stream.\n * If not provided, the original Instrument name will be used.\n */\n name?: string;\n /**\n * Alters the metric stream:\n * This will be used as the description of the metrics stream.\n * If not provided, the original Instrument description will be used by default.\n *\n * @example <caption>changes the description of all selected instruments to 'sample description'</caption>\n * description: 'sample description'\n */\n description?: string;\n /**\n * Alters the metric stream:\n * If provided, the attributes will be modified as defined by the processors in the list. Processors are applied\n * in the order they're provided.\n * If not provided, all attribute keys will be used by default.\n *\n * @example <caption>drops all attributes with top-level keys except for 'myAttr' and 'myOtherAttr'</caption>\n * attributesProcessors: [createAllowListProcessor(['myAttr', 'myOtherAttr'])]\n * @example <caption>drops all attributes</caption>\n * attributesProcessors: [createAllowListProcessor([])]\n * @example <caption>allows all attributes except for 'myAttr'</caption>\n * attributesProcessors: [createDenyListProcessor(['myAttr']]\n */\n attributesProcessors?: IAttributesProcessor[];\n /**\n * Alters the metric stream:\n * Alters the Aggregation of the metric stream.\n *\n * @example <caption>changes the aggregation of the selected instrument(s) to ExplicitBucketHistogramAggregation</caption>\n * aggregation: { type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM, options: { boundaries: [1, 10, 100] } }\n * @example <caption>changes the aggregation of the selected instrument(s) to LastValueAggregation</caption>\n * aggregation: { type: AggregationType.LAST_VALUE, options: { boundaries: [1, 10, 100] } }\n */\n aggregation?: AggregationOption;\n /**\n * Alters the metric stream:\n * Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated.\n * If not provided, the default limit will be used.\n *\n * @example <caption>sets the cardinality limit to 1000</caption>\n * aggregationCardinalityLimit: 1000\n */\n aggregationCardinalityLimit?: number;\n /**\n * Instrument selection criteria:\n * The original type of the Instrument(s).\n *\n * @example <caption>selects all counters</caption>\n * instrumentType: InstrumentType.COUNTER\n * @example <caption>selects all histograms</caption>\n * instrumentType: InstrumentType.HISTOGRAM\n */\n instrumentType?: InstrumentType;\n /**\n * Instrument selection criteria:\n * Original name of the Instrument(s) with wildcard support.\n *\n * @example <caption>select all instruments</caption>\n * instrumentName: '*'\n * @example <caption>select all instruments starting with 'my.instruments.'</caption>\n * instrumentName: 'my.instruments.*'\n * @example <caption>select all instruments named 'my.instrument.requests' exactly</caption>\n * instrumentName: 'my.instruments.requests'\n */\n instrumentName?: string;\n /**\n * Instrument selection criteria:\n * The unit of the Instrument(s).\n *\n * @example <caption>select all instruments with unit 'ms'</caption>\n * instrumentUnit: 'ms'\n */\n instrumentUnit?: string;\n /**\n * Instrument selection criteria:\n * The name of the Meter. No wildcard support, name must match the meter exactly.\n *\n * @example <caption>select all meters named 'example.component.app' exactly</caption>\n * meterName: 'example.component.app'\n */\n meterName?: string;\n /**\n * Instrument selection criteria:\n * The version of the Meter. No wildcard support, version must match exactly.\n *\n * @example\n * meterVersion: '1.0.1'\n */\n meterVersion?: string;\n /**\n * Instrument selection criteria:\n * The schema URL of the Meter. No wildcard support, schema URL must match exactly.\n *\n * @example <caption>Select all meters with schema URL 'https://example.com/schema' exactly.</caption>\n * meterSchemaUrl: 'https://example.com/schema'\n */\n meterSchemaUrl?: string;\n};\n\nfunction isSelectorNotProvided(options: ViewOptions): boolean {\n return (\n options.instrumentName == null &&\n options.instrumentType == null &&\n options.instrumentUnit == null &&\n options.meterName == null &&\n options.meterVersion == null &&\n options.meterSchemaUrl == null\n );\n}\n\nfunction validateViewOptions(viewOptions: ViewOptions) {\n // If no criteria is provided, the SDK SHOULD treat it as an error.\n // It is recommended that the SDK implementations fail fast.\n if (isSelectorNotProvided(viewOptions)) {\n throw new Error('Cannot create view with no selector arguments supplied');\n }\n\n // the SDK SHOULD NOT allow Views with a specified name to be declared with instrument selectors that\n // may select more than one instrument (e.g. wild card instrument name) in the same Meter.\n if (\n viewOptions.name != null &&\n (viewOptions?.instrumentName == null ||\n PatternPredicate.hasWildcard(viewOptions.instrumentName))\n ) {\n throw new Error(\n 'Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.'\n );\n }\n}\n\n/**\n * Can be passed to a {@link MeterProvider} to select instruments and alter their metric stream.\n */\nexport class View {\n readonly name?: string;\n readonly description?: string;\n readonly aggregation: Aggregation;\n readonly attributesProcessor: IAttributesProcessor;\n readonly instrumentSelector: InstrumentSelector;\n readonly meterSelector: MeterSelector;\n readonly aggregationCardinalityLimit?: number;\n\n /**\n * Create a new {@link View} instance.\n *\n * Parameters can be categorized as two types:\n * Instrument selection criteria: Used to describe the instrument(s) this view will be applied to.\n * Will be treated as additive (the Instrument has to meet all the provided criteria to be selected).\n *\n * Metric stream altering: Alter the metric stream of instruments selected by instrument selection criteria.\n *\n * @param viewOptions {@link ViewOptions} for altering the metric stream and instrument selection.\n * @param viewOptions.name\n * Alters the metric stream:\n * This will be used as the name of the metrics stream.\n * If not provided, the original Instrument name will be used.\n * @param viewOptions.description\n * Alters the metric stream:\n * This will be used as the description of the metrics stream.\n * If not provided, the original Instrument description will be used by default.\n * @param viewOptions.attributesProcessors\n * Alters the metric stream:\n * If provided, the attributes will be modified as defined by the added processors.\n * If not provided, all attribute keys will be used by default.\n * @param viewOptions.aggregationCardinalityLimit\n * Alters the metric stream:\n * Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated.\n * If not provided, the default limit of 2000 will be used.\n * @param viewOptions.aggregation\n * Alters the metric stream:\n * Alters the {@link Aggregation} of the metric stream.\n * @param viewOptions.instrumentName\n * Instrument selection criteria:\n * Original name of the Instrument(s) with wildcard support.\n * @param viewOptions.instrumentType\n * Instrument selection criteria:\n * The original type of the Instrument(s).\n * @param viewOptions.instrumentUnit\n * Instrument selection criteria:\n * The unit of the Instrument(s).\n * @param viewOptions.meterName\n * Instrument selection criteria:\n * The name of the Meter. No wildcard support, name must match the meter exactly.\n * @param viewOptions.meterVersion\n * Instrument selection criteria:\n * The version of the Meter. No wildcard support, version must match exactly.\n * @param viewOptions.meterSchemaUrl\n * Instrument selection criteria:\n * The schema URL of the Meter. No wildcard support, schema URL must match exactly.\n *\n * @example\n * // Create a view that changes the Instrument 'my.instrument' to use to an\n * // ExplicitBucketHistogramAggregation with the boundaries [20, 30, 40]\n * new View({\n * aggregation: new ExplicitBucketHistogramAggregation([20, 30, 40]),\n * instrumentName: 'my.instrument'\n * })\n */\n constructor(viewOptions: ViewOptions) {\n validateViewOptions(viewOptions);\n\n // Create multi-processor if attributesProcessors are defined.\n if (viewOptions.attributesProcessors != null) {\n this.attributesProcessor = createMultiAttributesProcessor(\n viewOptions.attributesProcessors\n );\n } else {\n this.attributesProcessor = createNoopAttributesProcessor();\n }\n\n this.name = viewOptions.name;\n this.description = viewOptions.description;\n this.aggregation = toAggregation(\n viewOptions.aggregation ?? { type: AggregationType.DEFAULT }\n );\n this.instrumentSelector = new InstrumentSelector({\n name: viewOptions.instrumentName,\n type: viewOptions.instrumentType,\n unit: viewOptions.instrumentUnit,\n });\n this.meterSelector = new MeterSelector({\n name: viewOptions.meterName,\n version: viewOptions.meterVersion,\n schemaUrl: viewOptions.meterSchemaUrl,\n });\n this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit;\n }\n}\n", "/**\n * The telemetry JSONL files: their record shapes, the one appender that stamps the\n * writing account, and the SDK exporters that feed it. The detached shipper\n * (span-shipper.ts) reads these files and forwards them.\n */\n\n// Before constants.js: TELEMETRY_DIR is fixed when constants loads, and .envrc may set it.\nimport '../core/load-envrc.js';\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';\nimport type { PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';\nimport type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-node';\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';\nimport { TELEMETRY_DIR } from '../core/constants.js';\nimport { ensureDirExists } from '../core/file-utils.js';\nimport { telemetryFileName, writeStderr } from '../core/format-utils.js';\nimport { resolveKeySecretName } from '../core/identity-key-resolver.js';\nimport type { OtlpSignal } from './otlp-signal.js';\n\n/** A signal prefix must stay an `OtlpSignal`: shipper-cursor.ts finds these files by `OTLP_SIGNALS`, so a drift is a silently unshipped signal. */\nexport function telemetryFilePath(prefix: OtlpSignal, date: Date = new Date()): string {\n ensureDirExists(TELEMETRY_DIR);\n return path.join(TELEMETRY_DIR, telemetryFileName(prefix, date));\n}\n\n/** Absent on pre-TKR6 records; the shipper then uses the signed-in account's key. */\nexport type IdentityKeyRef = string | null;\n\nlet cachedIdentityKeyRef: IdentityKeyRef | undefined;\n\n/**\n * The writing account as its Doppler secret name (never the email; it never leaves the\n * machine). The shipper keys each record by this, not by whoever is signed in when it\n * ships \u2014 the latter sent the tail of every session across an account switch to the\n * wrong org (TKR6). Exported for `appendEvaluation`, which bypasses these exporters.\n */\nexport function writerIdentityKeyRef(): IdentityKeyRef {\n cachedIdentityKeyRef ??= resolveKeySecretName() ?? null;\n return cachedIdentityKeyRef;\n}\n\n/** Drop the cached stamp. Tests only. */\nexport function resetWriterIdentityKeyRef(): void {\n cachedIdentityKeyRef = undefined;\n}\n\n/**\n * The one appender for every telemetry record, so the account stamp (TKR6) cannot be\n * forgotten by a writer that bypasses the SDK exporters. Throws on a write failure: the\n * exporters turn that into an ExportResult, appendEvaluation into a metric.\n */\nexport function appendTelemetryRecords(prefix: OtlpSignal, records: readonly object[], date: Date = new Date()): void {\n const identityKeyRef = writerIdentityKeyRef();\n fs.appendFileSync(\n telemetryFilePath(prefix, date),\n records.map((record) => `${JSON.stringify({ ...record, identityKeyRef })}\\n`).join(''),\n );\n}\n\n/** `buildRecords` runs inside the try so a serialization failure fails the export rather than throwing into the SDK. */\nfunction appendJsonl(\n prefix: OtlpSignal,\n signal: string,\n buildRecords: () => object[],\n resultCallback: (result: ExportResult) => void\n): void {\n try {\n appendTelemetryRecords(prefix, buildRecords());\n resultCallback({ code: ExportResultCode.SUCCESS });\n } catch (error) {\n writeStderr(`Failed to export ${signal} to file:`, error);\n resultCallback({ code: ExportResultCode.FAILED, error: error as Error });\n }\n}\n\n/** Spans built outside the SDK, stamped with the writing account like every exported record. */\nexport function appendSpanRecords(records: ExportedSpan[]): void {\n appendJsonl('traces', 'spans', () => records, () => {});\n}\n\n/**\n * One SDK exporter per signal. `Batch` is whatever that signal's `export` receives: an array of\n * spans or log records, but a single ResourceMetrics. Nothing is ever buffered, so shutdown and\n * flush have no work.\n */\nclass FileExporter<Batch> {\n constructor(\n private readonly prefix: OtlpSignal,\n private readonly signal: string,\n private readonly toRecords: (batch: Batch) => object[],\n ) {\n // Best-effort eager mkdir; first export re-runs this inside appendJsonl's try/catch and reports non-fatally.\n try { ensureDirExists(TELEMETRY_DIR); } catch { /* intentionally swallowed */ }\n }\n\n export(batch: Batch, resultCallback: (result: ExportResult) => void): void {\n appendJsonl(this.prefix, this.signal, () => this.toRecords(batch), resultCallback);\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/** The traces-*.jsonl record shape; consumers should type against it. `dropped*Count` omitted: always 0. */\nexport interface ExportedSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n kind: number;\n startTime: [number, number];\n endTime: [number, number];\n duration: [number, number];\n status: { code: number; message?: string };\n attributes: Record<string, unknown>;\n events: unknown[];\n links: unknown[];\n resource: {\n serviceName: string | undefined;\n serviceVersion: string | undefined;\n };\n instrumentationScope?: {\n name: string;\n version?: string;\n };\n identityKeyRef?: IdentityKeyRef;\n}\n\nfunction serializeSpan(span: ReadableSpan): ExportedSpan {\n const { traceId, spanId } = span.spanContext();\n return {\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n kind: span.kind,\n startTime: span.startTime,\n endTime: span.endTime,\n duration: span.duration,\n status: span.status,\n attributes: span.attributes,\n events: span.events,\n links: span.links,\n resource: {\n serviceName: span.resource.attributes[ATTR_SERVICE_NAME] as string | undefined,\n serviceVersion: span.resource.attributes[ATTR_SERVICE_VERSION] as string | undefined,\n },\n instrumentationScope: {\n name: span.instrumentationScope.name,\n version: span.instrumentationScope.version,\n },\n };\n}\n\nexport class FileSpanExporter extends FileExporter<ReadableSpan[]> implements SpanExporter {\n constructor() {\n super('traces', 'spans', (spans) => spans.map(serializeSpan));\n }\n}\n\n/** The logs-*.jsonl record shape; the shipper reconstructs ReadableLogRecords from it. */\nexport interface ExportedLog {\n timestamp: [number, number];\n observedTimestamp?: [number, number];\n severityNumber?: number;\n severityText?: string;\n body?: unknown;\n eventName?: string;\n attributes?: Record<string, unknown>;\n traceId?: string;\n spanId?: string;\n resource?: {\n serviceName?: unknown;\n serviceVersion?: unknown;\n };\n instrumentationScope?: {\n name: string;\n version?: string;\n };\n identityKeyRef?: IdentityKeyRef;\n}\n\nexport const LOGS_FILE_PREFIX = 'logs' satisfies OtlpSignal;\n\nfunction serializeLog(log: ReadableLogRecord): ExportedLog {\n return {\n timestamp: log.hrTime,\n observedTimestamp: log.hrTimeObserved,\n severityNumber: log.severityNumber,\n severityText: log.severityText,\n body: log.body,\n eventName: log.eventName ?? undefined,\n attributes: log.attributes,\n traceId: log.spanContext?.traceId,\n spanId: log.spanContext?.spanId,\n resource: {\n serviceName: log.resource.attributes[ATTR_SERVICE_NAME],\n serviceVersion: log.resource.attributes[ATTR_SERVICE_VERSION],\n },\n instrumentationScope: {\n name: log.instrumentationScope.name,\n version: log.instrumentationScope.version,\n },\n };\n}\n\n/** Every severity is written; the log file is the record of what a hook said, not only of what went wrong. */\nexport class FileLogExporter extends FileExporter<ReadableLogRecord[]> implements LogRecordExporter {\n constructor() {\n super(LOGS_FILE_PREFIX, 'logs', (logs) => logs.map(serializeLog));\n }\n}\n\n/** One ResourceMetrics collection per metrics-*.jsonl line; the shipper duck-types it back for OTLP. */\nexport interface ExportedResourceMetrics {\n resource: { attributes: Record<string, unknown> };\n scopeMetrics: unknown[];\n identityKeyRef?: IdentityKeyRef;\n}\n\n/** `advice` is on the runtime descriptor though the SDK's type omits it. */\ntype MetricDescriptor = ResourceMetrics['scopeMetrics'][number]['metrics'][number]['descriptor'] & { advice?: object };\n\n/** Drops the empty `description` and `advice` the SDK puts on every descriptor; the OTLP serializer reads neither when absent. */\nfunction compactDescriptor({ description, advice, ...rest }: MetricDescriptor): Partial<MetricDescriptor> {\n return {\n ...rest,\n ...(description ? { description } : {}),\n ...(advice && Object.keys(advice).length > 0 ? { advice } : {}),\n };\n}\n\nfunction serializeMetrics(metrics: ResourceMetrics): ExportedResourceMetrics {\n return {\n resource: { attributes: metrics.resource.attributes },\n scopeMetrics: metrics.scopeMetrics.map((scopeMetric) => ({\n ...scopeMetric,\n metrics: scopeMetric.metrics.map((metric) => ({ ...metric, descriptor: compactDescriptor(metric.descriptor) })),\n })),\n };\n}\n\n/** The SDK ships no metrics file exporter of its own. */\nexport class FileMetricExporter extends FileExporter<ResourceMetrics> implements PushMetricExporter {\n constructor() {\n super('metrics', 'metrics', (metrics) => [serializeMetrics(metrics)]);\n }\n}\n", "/**\n * `hostDetector` with `host.id` remembered across processes (HSF25): on darwin it\n * execs `ioreg` and holds the resource `asyncAttributesPending`, costing every hook\n * process a median 17-28 ms. A record is trusted only while `os.arch()` matches and\n * it is younger than `HOST_RECORD_TTL_MS`; otherwise `hostDetector` runs and rewrites it.\n */\n\nimport { arch, hostname } from 'node:os';\nimport { join } from 'node:path';\nimport { hostDetector, type DetectedResource, type ResourceDetector } from '@opentelemetry/resources';\nimport { loadJson, writeJsonAtomic } from '../core/file-utils.js';\nimport { TIME_MS } from '../core/units.js';\nimport { hostStateDir } from '../session/session-state.js';\n\n/** The registered `host.*` keys `hostDetector` fills (semconv, Development). */\nconst HOST_ATTRS = {\n NAME: 'host.name',\n ARCH: 'host.arch',\n ID: 'host.id',\n} as const;\n\nconst HOST_RECORD_FILE = 'host-resource.json';\n\n/** How long a recorded id is trusted before `hostDetector` is asked again. */\nexport const HOST_RECORD_TTL_MS = TIME_MS.WEEK;\n\nexport interface HostRecord {\n /** `host.id` as `hostDetector` resolved it. */\n id: string;\n /** `host.arch` as `hostDetector` normalized it (`x64` -> `amd64`). */\n arch: string;\n /** `os.arch()` when recorded; a different runtime arch invalidates the record. */\n nodeArch: string;\n recordedAtMs: number;\n}\n\n/** The record, or undefined when there is none worth trusting now. */\nfunction readHostRecord(recordPath: string): HostRecord | undefined {\n const record = loadJson<Partial<HostRecord>>(recordPath);\n if (\n typeof record?.id !== 'string' || !record.id ||\n typeof record.arch !== 'string' ||\n record.nodeArch !== arch() ||\n typeof record.recordedAtMs !== 'number' ||\n Date.now() - record.recordedAtMs >= HOST_RECORD_TTL_MS\n ) {\n return undefined;\n }\n return record as HostRecord;\n}\n\n/** A host detector that reads and writes its record at `recordPath`. */\nexport function createHostResourceDetector(\n recordPath: string = join(hostStateDir(), HOST_RECORD_FILE),\n): ResourceDetector {\n return {\n detect(config): DetectedResource {\n const record = readHostRecord(recordPath);\n if (record) {\n return {\n attributes: {\n [HOST_ATTRS.NAME]: hostname(),\n [HOST_ATTRS.ARCH]: record.arch,\n [HOST_ATTRS.ID]: record.id,\n },\n };\n }\n\n const detected = hostDetector.detect(config);\n const attributes = { ...detected.attributes };\n const hostArch = attributes[HOST_ATTRS.ARCH];\n attributes[HOST_ATTRS.ID] = Promise.resolve(attributes[HOST_ATTRS.ID]).then((id) => {\n if (typeof id === 'string' && id && typeof hostArch === 'string') {\n writeJsonAtomic<HostRecord>(\n recordPath,\n { id, arch: hostArch, nodeArch: arch(), recordedAtMs: Date.now() },\n { silent: true },\n );\n }\n return id;\n });\n return { ...detected, attributes };\n },\n };\n}\n\nexport const hostResourceDetector = createHostResourceDetector();\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYM,SAAU,gBAAgBA,UAAgB;AAC9C,SAAOA,SAAQ,SAAS,sBAAsB,IAAI;AACpD;AAEM,SAAU,kBAAkBA,UAAgB;AAChD,SAAOA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MAAM,SAAS;AAAA,IACjB,CAAC;AAAA,EACH;AACF;AAGO,SAAS,cACd,MACA,OACA,aAA6B,CAAC,GAC9B,SACM;AACN,aAAW,MAAM,OAAO,EAAE,IAAI,OAAO,UAAU;AACjD;AAEO,SAAS,aACd,MACA,OACA,aAA6B,CAAC,GAC9B,SACM;AACN,eAAa,MAAM,OAAO,EAAE,OAAO,OAAO,UAAU;AACtD;AAKO,SAAS,IACd,OACA,SACA,aAA6B,CAAC,GACxB;AAEN,EAAQ,KAAK,UAAU,cAAc,eAAe,EAAE,KAAK;AAAA,IACzD,gBAAgB,eAAe,KAAK;AAAA,IACpC,cAAc;AAAA,IACd,MAAM;AAAA,IACN;AAAA,EACF,CAAC;AACH;",
|
|
6
|
-
"names": ["context", "context", "init_esm", "ExportResultCode", "context", "VERSION", "context", "context", "RPCType", "esm_exports", "init_esm", "init_utils", "init_esm", "init_utils", "init_semconv", "process", "init_utils", "init_semconv", "init_utils", "init_node", "init_platform", "init_node", "init_platform", "init_esm", "context", "context", "context", "inspect", "init_esm", "inspect", "SamplingDecision", "ATTR_OTEL_COMPONENT_NAME", "ATTR_OTEL_COMPONENT_TYPE", "init_semconv", "SamplingDecision", "init_semconv", "VERSION", "init_version", "init_esm", "init_version", "VERSION", "context", "inspect", "init_esm", "context", "SamplingDecision", "SamplingDecision", "init_esm", "context", "componentCounter", "init_esm", "init_semconv", "ATTR_OTEL_COMPONENT_TYPE", "ATTR_OTEL_COMPONENT_NAME", "init_esm", "init_semconv", "init_node", "init_platform", "init_node", "init_esm", "init_platform", "ForceFlushState", "inspect", "init_esm", "init_esm", "init_esm", "init_semconv", "context", "SamplingDecision", "init_esm", "init_platform", "init_esm", "TracesSamplerValues", "init_esm", "init_esm", "BatchSpanProcessor", "init_esm", "SimpleSpanProcessor", "init_esm", "BatchSpanProcessor", "SamplingDecision", "SimpleSpanProcessor", "init_esm", "NodeTracerProvider", "path", "init_esm", "SUPPRESS_TRACING_KEY", "suppressTracing", "context", "loggingErrorHandler", "stringifyException", "flattenException", "delegateHandler", "loggingErrorHandler", "globalErrorHandler", "delegateHandler", "VERSION", "init_esm", "ATTR_PROCESS_RUNTIME_NAME", "SDK_INFO", "ATTR_PROCESS_RUNTIME_NAME", "VERSION", "otperformance", "NANOSECOND_DIGITS", "NANOSECOND_DIGITS_IN_MILLIS", "MILLISECONDS_TO_NANOSECONDS", "SECOND_TO_NANOSECONDS", "millisToHrTime", "hrTime", "millisToHrTime", "otperformance", "addHrTimes", "timeInputToHrTime", "isTimeInputHrTime", "isTimeInputHrTime", "addHrTimes", "SECOND_TO_NANOSECONDS", "ExportResultCode", "TimeoutError", "callWithTimeout", "Deferred", "BindOnceFuture", "Deferred", "_export", "suppressTracing", "internal", "_export", "init_esm", "serviceName", "defaultServiceName", "isPromiseLike", "ResourceImpl", "guardedRawAttributes", "isPromiseLike", "validateSchemaUrl", "mergeSchemaUrl", "resourceFromAttributes", "defaultResource", "resourceFromAttributes", "defaultServiceName", "SDK_INFO", "guardedRawAttributes", "isPromiseLike", "validateSchemaUrl", "mergeSchemaUrl", "init_esm", "AddAttributeDecision", "hrTime", "context", "timeInputToHrTime", "callWithTimeout", "context", "ATTR_ERROR_TYPE", "VERSION", "meterProvider", "VERSION", "defaultResource", "BindOnceFuture", "ATTR_ERROR_TYPE", "BindOnceFuture", "internal", "ExportResultCode", "globalErrorHandler", "AggregationTemporality", "InstrumentType", "DataPointType", "TimeoutError", "callWithTimeout", "AggregatorKind", "MAX_SCALE", "init_esm", "AggregationType", "ATTR_OTEL_COMPONENT_NAME", "ATTR_OTEL_COMPONENT_TYPE", "ATTR_ERROR_TYPE", "componentCounter", "ATTR_OTEL_COMPONENT_TYPE", "ATTR_OTEL_COMPONENT_NAME", "ATTR_ERROR_TYPE", "VERSION", "init_esm", "meterProvider", "VERSION", "callWithTimeout", "init_esm", "callWithTimeout", "TimeoutError", "init_esm", "context", "init_esm", "hrTime", "context", "callWithTimeout", "context", "init_esm", "context", "init_esm", "init_esm", "fs", "path", "log", "logs", "metrics", "init_esm", "arch", "hostname", "join", "arch", "join", "hostname"]
|
|
7
|
-
}
|