@elastic/opentelemetry-browser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/LICENSE +202 -0
- package/NOTICE.md +5765 -0
- package/README.md +22 -0
- package/build/elastic-otel-browser.js +11593 -0
- package/build/elastic-otel-browser.js.map +7 -0
- package/build/elastic-otel-browser.min.js +14 -0
- package/build/elastic-otel-browser.min.js.map +7 -0
- package/lib/bundle.js +8 -0
- package/lib/context.js +347 -0
- package/lib/detector.js +226 -0
- package/lib/index.js +6 -0
- package/lib/logging.js +67 -0
- package/lib/sdk.js +232 -0
- package/lib/semconv.js +68 -0
- package/lib/version.js +6 -0
- package/package.json +81 -0
- package/types/bundle.d.ts +1 -0
- package/types/context.d.ts +2 -0
- package/types/detector.d.ts +47 -0
- package/types/index.d.ts +1 -0
- package/types/logging.d.ts +9 -0
- package/types/sdk.d.ts +32 -0
- package/types/semconv.d.ts +58 -0
- package/types/version.d.ts +1 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../node_modules/@opentelemetry/api/src/platform/browser/globalThis.ts", "../node_modules/@opentelemetry/api/src/version.ts", "../node_modules/@opentelemetry/api/src/internal/semver.ts", "../node_modules/@opentelemetry/api/src/internal/global-utils.ts", "../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts", "../node_modules/@opentelemetry/api/src/diag/types.ts", "../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts", "../node_modules/@opentelemetry/api/src/api/diag.ts", "../node_modules/@opentelemetry/api/src/baggage/internal/baggage-impl.ts", "../node_modules/@opentelemetry/api/src/baggage/internal/symbol.ts", "../node_modules/@opentelemetry/api/src/baggage/utils.ts", "../node_modules/@opentelemetry/api/src/context/context.ts", "../node_modules/@opentelemetry/api/src/metrics/NoopMeter.ts", "../node_modules/@opentelemetry/api/src/metrics/Metric.ts", "../node_modules/@opentelemetry/api/src/propagation/TextMapPropagator.ts", "../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts", "../node_modules/@opentelemetry/api/src/api/context.ts", "../node_modules/@opentelemetry/api/src/trace/trace_flags.ts", "../node_modules/@opentelemetry/api/src/trace/invalid-span-constants.ts", "../node_modules/@opentelemetry/api/src/trace/NonRecordingSpan.ts", "../node_modules/@opentelemetry/api/src/trace/context-utils.ts", "../node_modules/@opentelemetry/api/src/trace/spancontext-utils.ts", "../node_modules/@opentelemetry/api/src/trace/NoopTracer.ts", "../node_modules/@opentelemetry/api/src/trace/ProxyTracer.ts", "../node_modules/@opentelemetry/api/src/trace/NoopTracerProvider.ts", "../node_modules/@opentelemetry/api/src/trace/ProxyTracerProvider.ts", "../node_modules/@opentelemetry/api/src/trace/SamplingResult.ts", "../node_modules/@opentelemetry/api/src/trace/span_kind.ts", "../node_modules/@opentelemetry/api/src/trace/status.ts", "../node_modules/@opentelemetry/api/src/context-api.ts", "../node_modules/@opentelemetry/api/src/diag-api.ts", "../node_modules/@opentelemetry/api/src/metrics/NoopMeterProvider.ts", "../node_modules/@opentelemetry/api/src/api/metrics.ts", "../node_modules/@opentelemetry/api/src/metrics-api.ts", "../node_modules/@opentelemetry/api/src/propagation/NoopTextMapPropagator.ts", "../node_modules/@opentelemetry/api/src/baggage/context-helpers.ts", "../node_modules/@opentelemetry/api/src/api/propagation.ts", "../node_modules/@opentelemetry/api/src/propagation-api.ts", "../node_modules/@opentelemetry/api/src/api/trace.ts", "../node_modules/@opentelemetry/api/src/trace-api.ts", "../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts", "../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts", "../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts", "../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts", "../node_modules/@opentelemetry/api-logs/src/ProxyLogger.ts", "../node_modules/@opentelemetry/api-logs/src/ProxyLoggerProvider.ts", "../node_modules/@opentelemetry/api-logs/src/api/logs.ts", "../node_modules/@opentelemetry/api-logs/src/index.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts", "../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/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/version.ts", "../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts", "../node_modules/@opentelemetry/core/src/semconv.ts", "../node_modules/@opentelemetry/core/src/platform/browser/sdk-info.ts", "../node_modules/@opentelemetry/core/src/platform/browser/index.ts", "../node_modules/@opentelemetry/core/src/common/time.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/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/internal/exporter.ts", "../node_modules/@opentelemetry/core/src/index.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-network-export-delegate.ts", "../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts", "../node_modules/@opentelemetry/otlp-transformer/src/logs/internal.ts", "../node_modules/@opentelemetry/otlp-transformer/src/common/utils.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/utils.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/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/ExponentialHistogram.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/Aggregation.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/export/MetricReader.ts", "../node_modules/@opentelemetry/sdk-metrics/src/export/PeriodicExportingMetricReader.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/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/HashMap.ts", "../node_modules/@opentelemetry/sdk-metrics/src/state/DeltaMetricProcessor.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/view/RegistrationConflicts.ts", "../node_modules/@opentelemetry/sdk-metrics/src/state/MetricStorageRegistry.ts", "../node_modules/@opentelemetry/sdk-metrics/src/state/MultiWritableMetricStorage.ts", "../node_modules/@opentelemetry/sdk-metrics/src/ObservableResult.ts", "../node_modules/@opentelemetry/sdk-metrics/src/state/ObservableRegistry.ts", "../node_modules/@opentelemetry/sdk-metrics/src/state/SyncMetricStorage.ts", "../node_modules/@opentelemetry/sdk-metrics/src/view/AttributesProcessor.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/InstrumentSelector.ts", "../node_modules/@opentelemetry/sdk-metrics/src/view/MeterSelector.ts", "../node_modules/@opentelemetry/sdk-metrics/src/view/View.ts", "../node_modules/@opentelemetry/sdk-metrics/src/MeterProvider.ts", "../node_modules/@opentelemetry/otlp-transformer/src/metrics/internal-types.ts", "../node_modules/@opentelemetry/otlp-transformer/src/metrics/internal.ts", "../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts", "../node_modules/@opentelemetry/otlp-transformer/src/logs/json/logs.ts", "../node_modules/@opentelemetry/otlp-transformer/src/metrics/json/metrics.ts", "../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/transport/fetch-transport.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-browser-http-export-delegate.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-browser-http-options.ts", "../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/create-legacy-browser-delegate.ts", "../node_modules/@opentelemetry/exporter-logs-otlp-http/src/platform/browser/OTLPLogExporter.ts", "../node_modules/@opentelemetry/exporter-metrics-otlp-http/src/OTLPMetricExporterOptions.ts", "../node_modules/@opentelemetry/exporter-metrics-otlp-http/src/OTLPMetricExporterBase.ts", "../node_modules/@opentelemetry/exporter-metrics-otlp-http/src/platform/browser/OTLPMetricExporter.ts", "../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/browser/OTLPTraceExporter.ts", "../node_modules/@opentelemetry/sdk-logs/src/utils/validation.ts", "../node_modules/@opentelemetry/sdk-logs/src/LogRecordImpl.ts", "../node_modules/@opentelemetry/sdk-logs/src/Logger.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/internal/LoggerProviderSharedState.ts", "../node_modules/@opentelemetry/sdk-logs/src/LoggerProvider.ts", "../node_modules/@opentelemetry/sdk-logs/src/export/BatchLogRecordProcessorBase.ts", "../node_modules/@opentelemetry/sdk-logs/src/platform/browser/export/BatchLogRecordProcessor.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.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/export/BatchSpanProcessorBase.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/platform/browser/export/BatchSpanProcessor.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/platform/browser/RandomIdGenerator.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/version.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts", "../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts", "../node_modules/@opentelemetry/sdk-trace-web/src/StackContextManager.ts", "../node_modules/@opentelemetry/sdk-trace-web/src/WebTracerProvider.ts", "../node_modules/@opentelemetry/sdk-trace-web/src/enums/PerformanceTimingNames.ts", "../node_modules/@opentelemetry/sdk-trace-web/src/semconv.ts", "../node_modules/@opentelemetry/sdk-trace-web/src/utils.ts", "../node_modules/@opentelemetry/instrumentation/src/autoLoaderUtils.ts", "../node_modules/@opentelemetry/instrumentation/src/autoLoader.ts", "../node_modules/@opentelemetry/instrumentation/src/shimmer.ts", "../node_modules/@opentelemetry/instrumentation/src/instrumentation.ts", "../node_modules/@opentelemetry/instrumentation/src/platform/browser/instrumentation.ts", "../node_modules/@opentelemetry/instrumentation/src/utils.ts", "../node_modules/@opentelemetry/instrumentation/src/semconvStability.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/enums/AttributeNames.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/version.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/semconv.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/enums/EventNames.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/utils.ts", "../node_modules/@opentelemetry/instrumentation-document-load/src/instrumentation.ts", "../node_modules/@opentelemetry/instrumentation-fetch/src/enums/AttributeNames.ts", "../node_modules/@opentelemetry/instrumentation-fetch/src/semconv.ts", "../node_modules/@opentelemetry/instrumentation-fetch/src/utils.ts", "../node_modules/@opentelemetry/instrumentation-fetch/src/version.ts", "../node_modules/@opentelemetry/instrumentation-fetch/src/fetch.ts", "../node_modules/@opentelemetry/instrumentation-long-task/src/version.ts", "../node_modules/@opentelemetry/instrumentation-long-task/src/instrumentation.ts", "../node_modules/@opentelemetry/instrumentation-user-interaction/src/enums/AttributeNames.ts", "../node_modules/@opentelemetry/instrumentation-user-interaction/src/version.ts", "../node_modules/@opentelemetry/instrumentation-user-interaction/src/instrumentation.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/semconv.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/enums/EventNames.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/utils.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/version.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/enums/AttributeNames.ts", "../node_modules/@opentelemetry/instrumentation-xml-http-request/src/xhr.ts", "../node_modules/@opentelemetry/instrumentation-web-exception/src/version.ts", "../node_modules/@opentelemetry/instrumentation-web-exception/src/instrumentation.ts", "../node_modules/@opentelemetry/browser-instrumentation/src/web-vitals/semconv.ts", "../node_modules/web-vitals/dist/web-vitals.attribution.js", "../node_modules/@opentelemetry/browser-instrumentation/src/web-vitals/instrumentation.ts", "../lib/logging.js", "../lib/context.js", "../lib/semconv.js", "../lib/version.js", "../lib/detector.js", "../lib/sdk.js", "../lib/bundle.js"],
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/core too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - <object> (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Baggage, BaggageEntry } from '../types';\n\nexport class BaggageImpl implements Baggage {\n private _entries: Map<string, BaggageEntry>;\n\n constructor(entries?: Map<string, BaggageEntry>) {\n this._entries = entries ? new Map(entries) : new Map();\n }\n\n getEntry(key: string): BaggageEntry | undefined {\n const entry = this._entries.get(key);\n if (!entry) {\n return undefined;\n }\n\n return Object.assign({}, entry);\n }\n\n getAllEntries(): [string, BaggageEntry][] {\n return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);\n }\n\n setEntry(key: string, entry: BaggageEntry): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.set(key, entry);\n return newBaggage;\n }\n\n removeEntry(key: string): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n newBaggage._entries.delete(key);\n return newBaggage;\n }\n\n removeEntries(...keys: string[]): BaggageImpl {\n const newBaggage = new BaggageImpl(this._entries);\n for (const key of keys) {\n newBaggage._entries.delete(key);\n }\n return newBaggage;\n }\n\n clear(): BaggageImpl {\n return new BaggageImpl();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Symbol used to make BaggageEntryMetadata an opaque type\n */\nexport const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagAPI } from '../api/diag';\nimport { BaggageImpl } from './internal/baggage-impl';\nimport { baggageEntryMetadataSymbol } from './internal/symbol';\nimport { Baggage, BaggageEntry, BaggageEntryMetadata } from './types';\n\nconst diag = DiagAPI.instance();\n\n/**\n * Create a new Baggage with optional entries\n *\n * @param entries An array of baggage entries the new baggage should contain\n */\nexport function createBaggage(\n entries: Record<string, BaggageEntry> = {}\n): Baggage {\n return new BaggageImpl(new Map(Object.entries(entries)));\n}\n\n/**\n * Create a serializable BaggageEntryMetadata object from a string.\n *\n * @param str string metadata. Format is currently not defined by the spec and has no special meaning.\n *\n */\nexport function baggageEntryMetadataFromString(\n str: string\n): BaggageEntryMetadata {\n if (typeof str !== 'string') {\n diag.error(\n `Cannot create baggage metadata from unknown type: ${typeof str}`\n );\n str = '';\n }\n\n return {\n __TYPE__: baggageEntryMetadataSymbol,\n toString() {\n return str;\n },\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map<symbol, unknown>;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map<symbol, unknown>) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter } from './Meter';\nimport {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n constructor() {}\n\n /**\n * @see {@link Meter.createGauge}\n */\n createGauge(_name: string, _options?: MetricOptions): Gauge {\n return NOOP_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createHistogram}\n */\n createHistogram(_name: string, _options?: MetricOptions): Histogram {\n return NOOP_HISTOGRAM_METRIC;\n }\n\n /**\n * @see {@link Meter.createCounter}\n */\n createCounter(_name: string, _options?: MetricOptions): Counter {\n return NOOP_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableGauge}\n */\n createObservableGauge(\n _name: string,\n _options?: MetricOptions\n ): ObservableGauge {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableCounter}\n */\n createObservableCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableCounter {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n createObservableUpDownCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableUpDownCounter {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n _callback: BatchObservableCallback,\n _observables: Observable[]\n ): void {}\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n extends NoopMetric\n implements UpDownCounter\n{\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n addCallback(_callback: ObservableCallback) {}\n\n removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n extends NoopObservableMetric\n implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n extends NoopObservableMetric\n implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n extends NoopObservableMetric\n implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter(): Meter {\n return NOOP_METER;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes, AttributeValue } from '../common/Attributes';\nimport { Context } from '../context/types';\nimport { BatchObservableResult, ObservableResult } from './ObservableResult';\n\n/**\n * Advisory options influencing aggregation configuration parameters.\n * @experimental\n */\nexport interface MetricAdvice {\n /**\n * Hint the explicit bucket boundaries for SDK if the metric is been\n * aggregated with a HistogramAggregator.\n */\n explicitBucketBoundaries?: number[];\n}\n\n/**\n * Options needed for metric creation\n */\nexport interface MetricOptions {\n /**\n * The description of the Metric.\n * @default ''\n */\n description?: string;\n\n /**\n * The unit of the Metric values.\n * @default ''\n */\n unit?: string;\n\n /**\n * Indicates the type of the recorded value.\n * @default {@link ValueType.DOUBLE}\n */\n valueType?: ValueType;\n\n /**\n * The advice influencing aggregation configuration parameters.\n * @experimental\n */\n advice?: MetricAdvice;\n}\n\n/** The Type of value. It describes how the data is reported. */\nexport enum ValueType {\n INT,\n DOUBLE,\n}\n\n/**\n * Counter is the most common synchronous instrument. This instrument supports\n * an `Add(increment)` function for reporting a sum, and is restricted to\n * non-negative increments. The default aggregation is Sum, as for any additive\n * instrument.\n *\n * Example uses for Counter:\n * <ol>\n * <li> count the number of bytes received. </li>\n * <li> count the number of requests completed. </li>\n * <li> count the number of accounts created. </li>\n * <li> count the number of checkpoints run. </li>\n * <li> count the number of 5xx errors. </li>\n * <ol>\n */\nexport interface Counter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs must not be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface UpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Increment value of counter by the input. Inputs may be negative.\n */\n add(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Gauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\nexport interface Histogram<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Records a measurement. Value of the measurement must not be negative.\n */\n record(value: number, attributes?: AttributesTypes, context?: Context): void;\n}\n\n/**\n * @deprecated please use {@link Attributes}\n */\nexport type MetricAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n */\nexport type MetricAttributeValue = AttributeValue;\n\n/**\n * The observable callback for Observable instruments.\n */\nexport type ObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: ObservableResult<AttributesTypes>\n) => void | Promise<void>;\n\n/**\n * The observable callback for a batch of Observable instruments.\n */\nexport type BatchObservableCallback<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = (\n observableResult: BatchObservableResult<AttributesTypes>\n) => void | Promise<void>;\n\nexport interface Observable<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> {\n /**\n * Sets up a function that will be called whenever a metric collection is initiated.\n *\n * If the function is already in the list of callbacks for this Observable, the function is not added a second time.\n */\n addCallback(callback: ObservableCallback<AttributesTypes>): void;\n\n /**\n * Removes a callback previously registered with {@link Observable.addCallback}.\n */\n removeCallback(callback: ObservableCallback<AttributesTypes>): void;\n}\n\nexport type ObservableCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\nexport type ObservableUpDownCounter<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\nexport type ObservableGauge<\n AttributesTypes extends MetricAttributes = MetricAttributes,\n> = Observable<AttributesTypes>;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\n\n/**\n * Injects `Context` into and extracts it from carriers that travel\n * in-band across process boundaries. Encoding is expected to conform to the\n * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request\n * headers.\n *\n * The carrier of propagated data on both the client (injector) and server\n * (extractor) side is usually an object such as http headers. Propagation is\n * usually implemented via library-specific request interceptors, where the\n * client-side injects values and the server-side extracts them.\n */\nexport interface TextMapPropagator<Carrier = any> {\n /**\n * Injects values from a given `Context` into a carrier.\n *\n * OpenTelemetry defines a common set of format values (TextMapPropagator),\n * and each has an expected `carrier` type.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param setter an optional {@link TextMapSetter}. If undefined, values will be\n * set by direct object assignment.\n */\n inject(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter<Carrier>\n ): void;\n\n /**\n * Given a `Context` and a carrier, extract context values from a\n * carrier and return a new context, created from the old context, with the\n * extracted values.\n *\n * @param context the Context from which to extract values to transmit over\n * the wire.\n * @param carrier the carrier of propagation fields, such as http request\n * headers.\n * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all\n * own properties, and keys will be accessed by direct object access.\n */\n extract(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter<Carrier>\n ): Context;\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n fields(): string[];\n}\n\n/**\n * A setter is specified by the caller to define a specific method\n * to set key/value pairs on the carrier within a propagator.\n */\nexport interface TextMapSetter<Carrier = any> {\n /**\n * Callback used to set a key/value pair on an object.\n *\n * Should be called by the propagator each time a key/value pair\n * should be set, and should set that key/value pair on the propagator.\n *\n * @param carrier object or class which carries key/value pairs\n * @param key string key to modify\n * @param value value to be set to the key on the carrier\n */\n set(carrier: Carrier, key: string, value: string): void;\n}\n\n/**\n * A getter is specified by the caller to define a specific method\n * to get the value of a key from a carrier.\n */\nexport interface TextMapGetter<Carrier = any> {\n /**\n * Get a list of all keys available on the carrier.\n *\n * @param carrier\n */\n keys(carrier: Carrier): string[];\n\n /**\n * Get the value of a specific key from the carrier.\n *\n * @param carrier\n * @param key\n */\n get(carrier: Carrier, key: string): undefined | string | string[];\n}\n\nexport const defaultTextMapGetter: TextMapGetter = {\n get(carrier, key) {\n if (carrier == null) {\n return undefined;\n }\n return carrier[key];\n },\n\n keys(carrier) {\n if (carrier == null) {\n return [];\n }\n return Object.keys(carrier);\n },\n};\n\nexport const defaultTextMapSetter: TextMapSetter = {\n set(carrier, key, value) {\n if (carrier == null) {\n return;\n }\n\n carrier[key] = value;\n },\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return fn.call(thisArg, ...args);\n }\n\n bind<T>(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public 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 return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind<T>(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum TraceFlags {\n /** Represents no flag set. */\n NONE = 0x0,\n /** Bit to represent whether trace is sampled in trace flags. */\n SAMPLED = 0x1 << 0,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\nexport const INVALID_SPANID = '0000000000000000';\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '../common/Exception';\nimport { TimeInput } from '../common/Time';\nimport { SpanAttributes } from './attributes';\nimport { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { SpanStatus } from './status';\nimport { Link } from './link';\n\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nexport class NonRecordingSpan implements Span {\n constructor(\n private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT\n ) {}\n\n // Returns a SpanContext.\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n // By default does nothing\n setAttribute(_key: string, _value: unknown): this {\n return this;\n }\n\n // By default does nothing\n setAttributes(_attributes: SpanAttributes): this {\n return this;\n }\n\n // By default does nothing\n addEvent(_name: string, _attributes?: SpanAttributes): this {\n return this;\n }\n\n addLink(_link: Link): this {\n return this;\n }\n\n addLinks(_links: Link[]): this {\n return this;\n }\n\n // By default does nothing\n setStatus(_status: SpanStatus): this {\n return this;\n }\n\n // By default does nothing\n updateName(_name: string): this {\n return this;\n }\n\n // By default does nothing\n end(_endTime?: TimeInput): void {}\n\n // isRecording always returns false for NonRecordingSpan.\n isRecording(): boolean {\n return false;\n }\n\n // By default does nothing\n recordException(_exception: Exception, _time?: TimeInput): void {}\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n\n/**\n * span key\n */\nconst SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context: Context): Span | undefined {\n return (context.getValue(SPAN_KEY) as Span) || undefined;\n}\n\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan(): Span | undefined {\n return getSpan(ContextAPI.getInstance().active());\n}\n\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context: Context, span: Span): Context {\n return context.setValue(SPAN_KEY, span);\n}\n\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context: Context): Context {\n return context.deleteValue(SPAN_KEY);\n}\n\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(\n context: Context,\n spanContext: SpanContext\n): Context {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context: Context): SpanContext | undefined {\n return getSpan(context)?.spanContext();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { SpanContext } from './span_context';\n\nconst VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nconst VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\n\nexport function isValidTraceId(traceId: string): boolean {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\n\nexport function isValidSpanId(spanId: string): boolean {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext: SpanContext): boolean {\n return (\n isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)\n );\n}\n\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext: SpanContext): Span {\n return new NonRecordingSpan(spanContext);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { Context } from '../context/types';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { Span } from './span';\nimport { isSpanContextValid } from './spancontext-utils';\nimport { SpanOptions } from './SpanOptions';\nimport { SpanContext } from './span_context';\nimport { Tracer } from './tracer';\n\nconst contextApi = ContextAPI.getInstance();\n\n/**\n * No-op implementations of {@link Tracer}.\n */\nexport class NoopTracer implements Tracer {\n // startSpan starts a noop span.\n startSpan(\n name: string,\n options?: SpanOptions,\n context = contextApi.active()\n ): Span {\n const root = Boolean(options?.root);\n if (root) {\n return new NonRecordingSpan();\n }\n\n const parentFromContext = context && getSpanContext(context);\n\n if (\n isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)\n ) {\n return new NonRecordingSpan(parentFromContext);\n } else {\n return new NonRecordingSpan();\n }\n }\n\n startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n name: string,\n opts: SpanOptions | undefined,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n name: string,\n opts: SpanOptions | undefined,\n ctx: Context | undefined,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: Span) => ReturnType<F>>(\n name: string,\n arg2?: F | SpanOptions,\n arg3?: F | Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: SpanOptions | undefined;\n let ctx: 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 SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as SpanOptions | undefined;\n ctx = arg3 as Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? contextApi.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = setSpan(parentContext, span);\n\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n }\n}\n\nfunction isSpanContext(spanContext: any): spanContext is SpanContext {\n return (\n typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number'\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { NoopTracer } from './NoopTracer';\nimport { Span } from './span';\nimport { SpanOptions } from './SpanOptions';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER = new NoopTracer();\n\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nexport class ProxyTracer implements Tracer {\n // When a real implementation is provided, this will be it\n private _delegate?: Tracer;\n\n constructor(\n private _provider: TracerDelegator,\n public readonly name: string,\n public readonly version?: string,\n public readonly options?: TracerOptions\n ) {}\n\n startSpan(name: string, options?: SpanOptions, context?: Context): Span {\n return this._getTracer().startSpan(name, options, context);\n }\n\n startActiveSpan<F extends (span: Span) => unknown>(\n _name: string,\n _options: F | SpanOptions,\n _context?: F | Context,\n _fn?: F\n ): ReturnType<F> {\n const tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n }\n\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n private _getTracer() {\n if (this._delegate) {\n return this._delegate;\n }\n\n const tracer = this._provider.getDelegateTracer(\n this.name,\n this.version,\n this.options\n );\n\n if (!tracer) {\n return NOOP_TRACER;\n }\n\n this._delegate = tracer;\n return this._delegate;\n }\n}\n\nexport interface TracerDelegator {\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopTracer } from './NoopTracer';\nimport { Tracer } from './tracer';\nimport { TracerOptions } from './tracer_options';\nimport { TracerProvider } from './tracer_provider';\n\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nexport class NoopTracerProvider implements TracerProvider {\n getTracer(\n _name?: string,\n _version?: string,\n _options?: TracerOptions\n ): Tracer {\n return new NoopTracer();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Tracer } from './tracer';\nimport { TracerProvider } from './tracer_provider';\nimport { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nimport { TracerOptions } from './tracer_options';\n\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nexport class ProxyTracerProvider implements TracerProvider {\n private _delegate?: TracerProvider;\n\n /**\n * Get a {@link ProxyTracer}\n */\n getTracer(name: string, version?: string, options?: TracerOptions): Tracer {\n return (\n this.getDelegateTracer(name, version, options) ??\n new ProxyTracer(this, name, version, options)\n );\n }\n\n getDelegate(): TracerProvider {\n return this._delegate ?? NOOP_TRACER_PROVIDER;\n }\n\n /**\n * Set the delegate tracer provider\n */\n setDelegate(delegate: TracerProvider) {\n this._delegate = delegate;\n }\n\n getDelegateTracer(\n name: string,\n version?: string,\n options?: TracerOptions\n ): Tracer | undefined {\n return this._delegate?.getTracer(name, version, options);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from './attributes';\nimport { TraceState } from './trace_state';\n\n/**\n * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\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 * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\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<SpanAttributes>;\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 * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport enum SpanKind {\n /** Default value. Indicates that the span is used internally. */\n INTERNAL = 0,\n\n /**\n * Indicates that the span covers server-side handling of an RPC or other\n * remote request.\n */\n SERVER = 1,\n\n /**\n * Indicates that the span covers the client-side wrapper around an RPC or\n * other remote request.\n */\n CLIENT = 2,\n\n /**\n * Indicates that the span describes producer sending a message to a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n PRODUCER = 3,\n\n /**\n * Indicates that the span describes consumer receiving a message from a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n CONSUMER = 4,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport const diag = DiagAPI.instance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from './Meter';\nimport { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n return NOOP_METER;\n }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Meter, MeterOptions } from '../metrics/Meter';\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n private static _instance?: MetricsAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Metrics API */\n public static getInstance(): MetricsAPI {\n if (!this._instance) {\n this._instance = new MetricsAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global meter provider.\n * Returns true if the meter provider was successfully registered, else false.\n */\n public setGlobalMeterProvider(provider: MeterProvider): boolean {\n return registerGlobal(API_NAME, provider, DiagAPI.instance());\n }\n\n /**\n * Returns the global meter provider.\n */\n public getMeterProvider(): MeterProvider {\n return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n }\n\n /**\n * Returns a meter from the global meter provider.\n */\n public getMeter(\n name: string,\n version?: string,\n options?: MeterOptions\n ): Meter {\n return this.getMeterProvider().getMeter(name, version, options);\n }\n\n /** Remove the global meter provider */\n public disable(): void {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/** Entrypoint for metrics API */\nexport const metrics = MetricsAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport { TextMapPropagator } from './TextMapPropagator';\n\n/**\n * No-op implementations of {@link TextMapPropagator}.\n */\nexport class NoopTextMapPropagator implements TextMapPropagator {\n /** Noop inject function does nothing */\n inject(_context: Context, _carrier: unknown): void {}\n /** Noop extract function does nothing and returns the input context */\n extract(context: Context, _carrier: unknown): Context {\n return context;\n }\n fields(): string[] {\n return [];\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextAPI } from '../api/context';\nimport { createContextKey } from '../context/context';\nimport { Context } from '../context/types';\nimport { Baggage } from './types';\n\n/**\n * Baggage key\n */\nconst BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key');\n\n/**\n * Retrieve the current baggage from the given context\n *\n * @param {Context} Context that manage all context values\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getBaggage(context: Context): Baggage | undefined {\n return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined;\n}\n\n/**\n * Retrieve the current baggage from the active/current context\n *\n * @returns {Baggage} Extracted baggage from the context\n */\nexport function getActiveBaggage(): Baggage | undefined {\n return getBaggage(ContextAPI.getInstance().active());\n}\n\n/**\n * Store a baggage in the given context\n *\n * @param {Context} Context that manage all context values\n * @param {Baggage} baggage that will be set in the actual context\n */\nexport function setBaggage(context: Context, baggage: Baggage): Context {\n return context.setValue(BAGGAGE_KEY, baggage);\n}\n\n/**\n * Delete the baggage stored in the given context\n *\n * @param {Context} Context that manage all context values\n */\nexport function deleteBaggage(context: Context): Context {\n return context.deleteValue(BAGGAGE_KEY);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { NoopTextMapPropagator } from '../propagation/NoopTextMapPropagator';\nimport {\n defaultTextMapGetter,\n defaultTextMapSetter,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '../propagation/TextMapPropagator';\nimport {\n getBaggage,\n getActiveBaggage,\n setBaggage,\n deleteBaggage,\n} from '../baggage/context-helpers';\nimport { createBaggage } from '../baggage/utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'propagation';\nconst NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Propagation API\n */\nexport class PropagationAPI {\n private static _instance?: PropagationAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Propagator API */\n public static getInstance(): PropagationAPI {\n if (!this._instance) {\n this._instance = new PropagationAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current propagator.\n *\n * @returns true if the propagator was successfully registered, else false\n */\n public setGlobalPropagator(propagator: TextMapPropagator): boolean {\n return registerGlobal(API_NAME, propagator, DiagAPI.instance());\n }\n\n /**\n * Inject context into a carrier to be propagated inter-process\n *\n * @param context Context carrying tracing data to inject\n * @param carrier carrier to inject context into\n * @param setter Function used to set values on the carrier\n */\n public inject<Carrier>(\n context: Context,\n carrier: Carrier,\n setter: TextMapSetter<Carrier> = defaultTextMapSetter\n ): void {\n return this._getGlobalPropagator().inject(context, carrier, setter);\n }\n\n /**\n * Extract context from a carrier\n *\n * @param context Context which the newly created context will inherit from\n * @param carrier Carrier to extract context from\n * @param getter Function used to extract keys from a carrier\n */\n public extract<Carrier>(\n context: Context,\n carrier: Carrier,\n getter: TextMapGetter<Carrier> = defaultTextMapGetter\n ): Context {\n return this._getGlobalPropagator().extract(context, carrier, getter);\n }\n\n /**\n * Return a list of all fields which may be used by the propagator.\n */\n public fields(): string[] {\n return this._getGlobalPropagator().fields();\n }\n\n /** Remove the global propagator */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n\n public createBaggage = createBaggage;\n\n public getBaggage = getBaggage;\n\n public getActiveBaggage = getActiveBaggage;\n\n public setBaggage = setBaggage;\n\n public deleteBaggage = deleteBaggage;\n\n private _getGlobalPropagator(): TextMapPropagator {\n return getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport const propagation = PropagationAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport {\n isSpanContextValid,\n wrapSpanContext,\n} from '../trace/spancontext-utils';\nimport { Tracer } from '../trace/tracer';\nimport { TracerProvider } from '../trace/tracer_provider';\nimport {\n deleteSpan,\n getActiveSpan,\n getSpan,\n getSpanContext,\n setSpan,\n setSpanContext,\n} from '../trace/context-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'trace';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nexport class TraceAPI {\n private static _instance?: TraceAPI;\n\n private _proxyTracerProvider = new ProxyTracerProvider();\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Trace API */\n public static getInstance(): TraceAPI {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n public setGlobalTracerProvider(provider: TracerProvider): boolean {\n const success = registerGlobal(\n API_NAME,\n this._proxyTracerProvider,\n DiagAPI.instance()\n );\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n }\n\n /**\n * Returns the global tracer provider.\n */\n public getTracerProvider(): TracerProvider {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n }\n\n /**\n * Returns a tracer from the global tracer provider.\n */\n public getTracer(name: string, version?: string): Tracer {\n return this.getTracerProvider().getTracer(name, version);\n }\n\n /** Remove the global tracer provider */\n public disable() {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n }\n\n public wrapSpanContext = wrapSpanContext;\n\n public isSpanContextValid = isSpanContextValid;\n\n public deleteSpan = deleteSpan;\n\n public getSpan = getSpan;\n\n public getActiveSpan = getActiveSpan;\n\n public getSpanContext = getSpanContext;\n\n public setSpan = setSpan;\n\n public setSpanContext = setSpanContext;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport const trace = TraceAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Context, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The unique identifier for the log record.\n */\n eventName?: string;\n\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * An exception (or error) associated with the log record.\n *\n * @experimental\n */\n exception?: unknown;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { LoggerProvider } from '../types/LoggerProvider';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 1;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { NOOP_LOGGER } from './NoopLogger';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { LogRecord } from './types/LogRecord';\n\nexport class ProxyLogger implements Logger {\n // When a real implementation is provided, this will be it\n private _delegate?: Logger;\n private _provider: LoggerDelegator;\n public readonly name: string;\n public readonly version?: string | undefined;\n public readonly options?: LoggerOptions | undefined;\n\n constructor(\n provider: LoggerDelegator,\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ) {\n this._provider = provider;\n this.name = name;\n this.version = version;\n this.options = options;\n }\n\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void {\n this._getLogger().emit(logRecord);\n }\n\n /**\n * Try to get a logger from the proxy logger provider.\n * If the proxy logger provider has no delegate, return a noop logger.\n */\n private _getLogger() {\n if (this._delegate) {\n return this._delegate;\n }\n const logger = this._provider._getDelegateLogger(\n this.name,\n this.version,\n this.options\n );\n if (!logger) {\n return NOOP_LOGGER;\n }\n this._delegate = logger;\n return this._delegate;\n }\n}\n\nexport interface LoggerDelegator {\n _getDelegateLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger | undefined;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NOOP_LOGGER_PROVIDER } from './NoopLoggerProvider';\nimport { ProxyLogger } from './ProxyLogger';\n\nexport class ProxyLoggerProvider implements LoggerProvider {\n private _delegate?: LoggerProvider;\n\n getLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger {\n return (\n this._getDelegateLogger(name, version, options) ??\n new ProxyLogger(this, name, version, options)\n );\n }\n\n /**\n * Get the delegate logger provider.\n * Used by tests only.\n * @internal\n */\n _getDelegate(): LoggerProvider {\n return this._delegate ?? NOOP_LOGGER_PROVIDER;\n }\n\n /**\n * Set the delegate logger provider\n * @internal\n */\n _setDelegate(delegate: LoggerProvider) {\n this._delegate = delegate;\n }\n\n /**\n * @internal\n */\n _getDelegateLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger | undefined {\n return this._delegate?.getLogger(name, version, options);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\nimport { ProxyLoggerProvider } from '../ProxyLoggerProvider';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private _proxyLoggerProvider = new ProxyLoggerProvider();\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n this._proxyLoggerProvider._setDelegate(provider);\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n this._proxyLoggerProvider\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\n this._proxyLoggerProvider = new ProxyLoggerProvider();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type { Logger } from './types/Logger';\nexport type { LoggerProvider } from './types/LoggerProvider';\nexport { SeverityNumber } from './types/LogRecord';\nexport type { LogAttributes, LogBody, LogRecord } from './types/LogRecord';\nexport type { LoggerOptions } from './types/LoggerOptions';\nexport type { AnyValue, AnyValueMap } from './types/AnyValue';\nexport { NOOP_LOGGER, NoopLogger } from './NoopLogger';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ExportResult } from '@opentelemetry/core';\nimport { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n private _delegate: IOtlpExportDelegate<Internal>;\n constructor(delegate: IOtlpExportDelegate<Internal>) {\n this._delegate = delegate;\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._delegate.export(items, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n timeoutMillis: number;\n concurrencyLimit: number;\n compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n return timeoutMillis;\n }\n throw new Error(\n `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n );\n}\n\nexport function wrapStaticHeadersInFunction(\n headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n if (headers == null) {\n return undefined;\n }\n\n return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n return {\n timeoutMillis: validateTimeoutMillis(\n userProvidedConfiguration.timeoutMillis ??\n fallbackConfiguration.timeoutMillis ??\n defaultConfiguration.timeoutMillis\n ),\n concurrencyLimit:\n userProvidedConfiguration.concurrencyLimit ??\n fallbackConfiguration.concurrencyLimit ??\n defaultConfiguration.concurrencyLimit,\n compression:\n userProvidedConfiguration.compression ??\n fallbackConfiguration.compression ??\n defaultConfiguration.compression,\n };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n return {\n timeoutMillis: 10000,\n concurrencyLimit: 30,\n compression: 'none',\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n pushPromise(promise: Promise<void>): void;\n hasReachedLimit(): boolean;\n awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n private readonly _concurrencyLimit: number;\n private _sendingPromises: Promise<unknown>[] = [];\n\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit: number) {\n this._concurrencyLimit = concurrencyLimit;\n }\n\n public pushPromise(promise: Promise<void>): void {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n public hasReachedLimit(): boolean {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n\n public async awaitAll(): Promise<void> {\n await Promise.all(this._sendingPromises);\n }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n concurrencyLimit: number;\n}): IExportPromiseHandler {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Context, 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 {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\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 * 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 {\n BaggageEntry,\n Context,\n propagation,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport { getKeyPairs, parsePairKeyValue, serializeKeyPairs } 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 const baggageString = Array.isArray(headerValue)\n ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString) return context;\n const baggage: Record<string, BaggageEntry> = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n if (keyPair) {\n const baggageEntry: BaggageEntry = { value: keyPair.value };\n if (keyPair.metadata) {\n baggageEntry.metadata = keyPair.metadata;\n }\n baggage[keyPair.key] = baggageEntry;\n }\n });\n if (Object.entries(baggage).length === 0) {\n return context;\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\nimport { diag, AttributeValue, Attributes } 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 { diag, Exception } from '@opentelemetry/api';\nimport { 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 { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { 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 *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/database/database-spans.md#generating-a-summary-of-the-query)\n * section.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/database/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" 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 gRPC 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/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods\n * (this list **MUST** be a full override of the default known method, it is not a list of known methods in addition to the defaults).\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * The version string of the service API or implementation. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\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\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,\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]: 'browser',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,\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 = performance;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * 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 // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\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 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 microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\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\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} 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 this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\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 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 * as api 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 api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} 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\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 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 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 */\n\nimport { context } from '@opentelemetry/api';\nimport { 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 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 */\nimport { diag } from '@opentelemetry/api';\nimport { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n response: unknown\n): response is { partialSuccess: never } {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n T,\n>(): IOtlpResponseHandler<T> {\n return {\n handleResponse(response: T) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (\n response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0\n ) {\n return;\n }\n diag.warn(\n 'Received Partial Success response:',\n JSON.stringify(response.partialSuccess)\n );\n },\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { IExporterTransport } from './exporter-transport';\nimport { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport { diag, DiagLogger } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n implements IOtlpExportDelegate<Internal>\n{\n private _diagLogger: DiagLogger;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<Internal, Response>;\n private _responseHandler: IOtlpResponseHandler<Response>;\n private _promiseQueue: IExportPromiseHandler;\n private _timeout: number;\n\n constructor(\n transport: IExporterTransport,\n serializer: ISerializer<Internal, Response>,\n responseHandler: IOtlpResponseHandler<Response>,\n promiseQueue: IExportPromiseHandler,\n timeout: number\n ) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n const serializedRequest = this._serializer.serializeRequest(\n internalRepresentation\n );\n\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n\n this._promiseQueue.pushPromise(\n this._transport.send(serializedRequest, this._timeout).then(\n response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(\n this._serializer.deserializeResponse(response.data)\n );\n } catch (e) {\n this._diagLogger.warn(\n 'Export succeeded but could not deserialize response - is the response specification compliant?',\n e,\n response.data\n );\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n } else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n } else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error:\n response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n } else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n },\n reason =>\n resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })\n )\n );\n }\n\n forceFlush(): Promise<void> {\n return this._promiseQueue.awaitAll();\n }\n\n async shutdown(): Promise<void> {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n components: {\n transport: IExporterTransport;\n serializer: ISerializer<Internal, Response>;\n promiseHandler: IExportPromiseHandler;\n },\n settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n return new OTLPExportDelegate(\n components.transport,\n components.serializer,\n createLoggingPartialSuccessResponseHandler(),\n components.promiseHandler,\n settings.timeout\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { OtlpSharedConfiguration } from './configuration/shared-configuration';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { IExporterTransport } from './exporter-transport';\nimport {\n createOtlpExportDelegate,\n IOtlpExportDelegate,\n} from './otlp-export-delegate';\n\nexport function createOtlpNetworkExportDelegate<Internal, Response>(\n options: OtlpSharedConfiguration,\n serializer: ISerializer<Internal, Response>,\n transport: IExporterTransport\n): IOtlpExportDelegate<Internal> {\n return createOtlpExportDelegate(\n {\n transport: transport,\n serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n },\n { timeout: options.timeoutMillis }\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport { Attributes } from '@opentelemetry/api';\nimport { InstrumentationScope } from '@opentelemetry/core';\nimport { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\n\nexport function createResource(\n resource: ISdkResource,\n encoder: Encoder\n): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n return result;\n}\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(\n attributes: Attributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n\nexport function toKeyValue(\n key: string,\n value: unknown,\n encoder: Encoder\n): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values: IAnyValue[] = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values: IKeyValue[] = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n\n return {};\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableLogRecord } from '@opentelemetry/sdk-logs';\nimport {\n ESeverityNumber,\n IExportLogsServiceRequest,\n ILogRecord,\n IResourceLogs,\n} from './internal-types';\nimport { Resource } from '@opentelemetry/resources';\nimport { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAnyValue,\n toKeyValue,\n} from '../common/internal';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { IKeyValue } from '../common/internal-types';\nimport { LogAttributes } from '@opentelemetry/api-logs';\n\nexport function createExportLogsServiceRequest(\n logRecords: ReadableLogRecord[],\n encoder: Encoder\n): IExportLogsServiceRequest {\n return {\n resourceLogs: logRecordsToResourceLogs(logRecords, encoder),\n };\n}\n\nfunction createResourceMap(\n logRecords: ReadableLogRecord[]\n): Map<Resource, Map<string, ReadableLogRecord[]>> {\n const resourceMap: Map<\n Resource,\n Map<string, ReadableLogRecord[]>\n > = new Map();\n\n for (const record of logRecords) {\n const {\n resource,\n instrumentationScope: { name, version = '', schemaUrl = '' },\n } = record;\n\n let ismMap = resourceMap.get(resource);\n if (!ismMap) {\n ismMap = new Map();\n resourceMap.set(resource, ismMap);\n }\n\n const ismKey = `${name}@${version}:${schemaUrl}`;\n let records = ismMap.get(ismKey);\n if (!records) {\n records = [];\n ismMap.set(ismKey, records);\n }\n records.push(record);\n }\n return resourceMap;\n}\n\nfunction logRecordsToResourceLogs(\n logRecords: ReadableLogRecord[],\n encoder: Encoder\n): IResourceLogs[] {\n const resourceMap = createResourceMap(logRecords);\n return Array.from(resourceMap, ([resource, ismMap]) => {\n const processedResource = createResource(resource, encoder);\n return {\n resource: processedResource,\n scopeLogs: Array.from(ismMap, ([, scopeLogs]) => {\n return {\n scope: createInstrumentationScope(scopeLogs[0].instrumentationScope),\n logRecords: scopeLogs.map(log => toLogRecord(log, encoder)),\n schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl,\n };\n }),\n schemaUrl: processedResource.schemaUrl,\n };\n });\n}\n\nfunction toLogRecord(log: ReadableLogRecord, encoder: Encoder): ILogRecord {\n return {\n timeUnixNano: encoder.encodeHrTime(log.hrTime),\n observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved),\n severityNumber: toSeverityNumber(log.severityNumber),\n severityText: log.severityText,\n body: toAnyValue(log.body, encoder),\n eventName: log.eventName,\n attributes: toLogAttributes(log.attributes, encoder),\n droppedAttributesCount: log.droppedAttributesCount,\n flags: log.spanContext?.traceFlags,\n traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId),\n spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId),\n };\n}\n\nfunction toSeverityNumber(\n severityNumber: SeverityNumber | undefined\n): ESeverityNumber | undefined {\n return severityNumber as number | undefined as ESeverityNumber | undefined;\n}\n\nexport function toLogAttributes(\n attributes: LogAttributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return (\n BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes: Uint8Array): string => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\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 { HrTime, Attributes, ValueType } from '@opentelemetry/api';\nimport { InstrumentationScope } from '@opentelemetry/core';\nimport { Resource } from '@opentelemetry/resources';\nimport { AggregationTemporality } from './AggregationTemporality';\nimport { 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 { Attributes } from '@opentelemetry/api';\nimport { 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 { HrTime, Attributes } from '@opentelemetry/api';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { MetricData } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { 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 { HrTime } from '@opentelemetry/api';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { MetricData, MetricDescriptor } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { AggregatorKind, Aggregator, AccumulationRecord } 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 {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n AggregatorKind,\n} from './types';\nimport {\n DataPointType,\n HistogramMetricData,\n InstrumentType,\n} from '../export/MetricData';\nimport { HrTime } from '@opentelemetry/api';\nimport { binarySearchUB, Maybe } from '../utils';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { 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 */\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, perform bitwise\n * operations on them independently, and combine the results (if needed).\n */\n\nexport const SIGNIFICAND_WIDTH = 52;\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/**\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 dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value);\n // access the raw 64-bit float as 32-bit uints\n const hiBits = dv.getUint32(0);\n const expBits = (hiBits & EXPONENT_MASK) >> 20;\n return expBits - EXPONENT_BIAS;\n}\n\n/**\n * GetSignificand returns the 52 bit (unsigned) significand as a signed value.\n * @param {number} value - the floating point number to extract the significand from\n * @returns {number} The 52-bit significand\n */\nexport function getSignificand(value: number): number {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value);\n // access the raw 64-bit float as two 32-bit uints\n const hiBits = dv.getUint32(0);\n const loBits = dv.getUint32(4);\n // extract the significand bits from the hi bits and left shift 32 places note:\n // we can't use the native << operator as it will truncate the result to 32-bits\n const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32);\n // combine the hi and lo bits and return\n return significandHiBits + loBits;\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 { Mapping, 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 // In case the value is an exact power of two, compute a\n // correction of -1. Note, we are using a custom _rightShift\n // to accommodate a 52-bit argument, which the native bitwise\n // operators do not support\n const correction = this._rightShift(\n ieee754.getSignificand(value) - 1,\n ieee754.SIGNIFICAND_WIDTH\n );\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 private _rightShift(value: number, shift: number): number {\n return Math.floor(value * Math.pow(2, -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 { Mapping, 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.getSignificand(value) === 0) {\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 { MappingError, Mapping } 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 {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n AggregatorKind,\n ExponentialHistogram,\n} from './types';\nimport {\n DataPointType,\n ExponentialHistogramMetricData,\n InstrumentType,\n} from '../export/MetricData';\nimport { diag, HrTime } from '@opentelemetry/api';\nimport { Maybe } from '../utils';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { Buckets } from './exponential-histogram/Buckets';\nimport { getMapping } from './exponential-histogram/mapping/getMapping';\nimport { 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 // 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 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 */\n\nimport {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n AggregatorKind,\n LastValue,\n} from './types';\nimport { HrTime } from '@opentelemetry/api';\nimport { millisToHrTime, hrTimeToMicroseconds } from '@opentelemetry/core';\nimport { DataPointType, GaugeMetricData } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { 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 {\n Sum,\n AggregatorKind,\n Aggregator,\n Accumulation,\n AccumulationRecord,\n} from './types';\nimport { HrTime } from '@opentelemetry/api';\nimport { DataPointType, SumMetricData } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { 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 */\n\nimport * as api from '@opentelemetry/api';\nimport {\n Aggregator,\n SumAggregator,\n DropAggregator,\n LastValueAggregator,\n HistogramAggregator,\n ExponentialHistogramAggregator,\n} from '../aggregator';\nimport { Accumulation } from '../aggregator/types';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { 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 */\nimport {\n Aggregation,\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 { InstrumentType } from './MetricData';\nimport { AggregationOption, 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\nimport * as api from '@opentelemetry/api';\nimport { AggregationTemporality } from './AggregationTemporality';\nimport { MetricProducer } from './MetricProducer';\nimport { CollectionResult, InstrumentType } from './MetricData';\nimport { callWithTimeout } from '../utils';\nimport {\n CollectionOptions,\n ForceFlushOptions,\n ShutdownOptions,\n} from '../types';\nimport {\n AggregationSelector,\n AggregationTemporalitySelector,\n DEFAULT_AGGREGATION_SELECTOR,\n DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,\n} from './AggregationSelector';\nimport { AggregationOption } from '../view/AggregationOption';\nimport { CardinalitySelector } from './CardinalitySelector';\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\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 private readonly _aggregationTemporalitySelector: AggregationTemporalitySelector;\n private readonly _aggregationSelector: AggregationSelector;\n private readonly _cardinalitySelector?: CardinalitySelector;\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 }\n\n setMetricProducer(metricProducer: MetricProducer) {\n if (this._sdkMetricProducer) {\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 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 [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\n // Merge the results, keeping the SDK's Resource\n const errors = sdkCollectionResults.errors.concat(\n additionalCollectionResults.flatMap(result => result.errors)\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 * as api from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n} from '@opentelemetry/core';\nimport { MetricReader } from './MetricReader';\nimport { PushMetricExporter } from './MetricExporter';\nimport { callWithTimeout, TimeoutError } from '../utils';\nimport { MetricProducer } from './MetricProducer';\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\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\n constructor(options: PeriodicExportingMetricReaderOptions) {\n const { exporter, exportIntervalMillis = 60000, metricProducers } = options;\n let { exportTimeoutMillis = 30000 } = options;\n\n super({\n aggregationSelector: exporter.selectAggregation?.bind(exporter),\n aggregationTemporalitySelector:\n exporter.selectAggregationTemporality?.bind(exporter),\n metricProducers,\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 (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 }\n\n private async _runOnce(): Promise<void> {\n try {\n await callWithTimeout(this._doRun(), this._exportTimeout);\n } catch (err) {\n if (err instanceof TimeoutError) {\n api.diag.error(\n 'Export took longer than %s milliseconds and timed out.',\n this._exportTimeout\n );\n return;\n }\n\n globalErrorHandler(err);\n }\n }\n\n private async _doRun(): Promise<void> {\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('Error while resolving async portion of resource: ', e);\n globalErrorHandler(e);\n }\n }\n\n if (resourceMetrics.scopeMetrics.length === 0) {\n return;\n }\n\n const result = await internal._export(this._exporter, resourceMetrics);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw new Error(\n `PeriodicExportingMetricReader: metrics export failed (error ${result.error})`\n );\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 await this._runOnce();\n await this._exporter.forceFlush();\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\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 { Attributes, AttributeValue, 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 { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport {\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 { InstrumentationScope } from '@opentelemetry/core';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { InstrumentSelector } from './InstrumentSelector';\nimport { MeterSelector } from './MeterSelector';\nimport { 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 {\n MetricAdvice,\n MetricOptions,\n ValueType,\n diag,\n} from '@opentelemetry/api';\nimport { View } from './view/View';\nimport { equalsCaseInsensitive } from './utils';\nimport { 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 {\n context as contextApi,\n diag,\n Context,\n Attributes,\n ValueType,\n UpDownCounter,\n Counter,\n Gauge,\n Histogram,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n} from '@opentelemetry/api';\nimport { millisToHrTime } from '@opentelemetry/core';\nimport { InstrumentDescriptor } from './InstrumentDescriptor';\nimport { ObservableRegistry } from './state/ObservableRegistry';\nimport {\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 = contextApi.active()\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(\n value,\n attributes,\n context,\n millisToHrTime(Date.now())\n );\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 {\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 { 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 { HrTime } from '@opentelemetry/api';\nimport { MetricData } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { MetricCollectorHandle } from './MetricCollector';\nimport {\n createInstrumentDescriptor,\n InstrumentDescriptor,\n} 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 { 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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { Maybe, hashAttributes } from '../utils';\nimport { 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(\n value: number,\n attributes: Attributes,\n _context: Context,\n collectionTime: HrTime\n ) {\n let accumulation = this._activeCollectionStorage.get(attributes);\n\n if (!accumulation) {\n if (this._activeCollectionStorage.size >= this._cardinalityLimit) {\n const overflowAccumulation = this._activeCollectionStorage.getOrDefault(\n this._overflowAttributes,\n () => this._aggregator.createAccumulation(collectionTime)\n );\n overflowAccumulation?.record(value);\n return;\n }\n\n accumulation = this._aggregator.createAccumulation(collectionTime);\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 Array.from(measurements.entries()).forEach(\n ([attributes, value, hashCode]) => {\n const accumulation =\n 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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const previous = this._cumulativeMemoStorage.get(\n attributes,\n hashCode\n )!;\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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const active = this._activeCollectionStorage.get(\n attributes,\n hashCode\n )!;\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 /**\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 { HrTime } from '@opentelemetry/api';\nimport {\n Accumulation,\n AccumulationRecord,\n Aggregator,\n} from '../aggregator/types';\nimport { MetricData } from '../export/MetricData';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { Maybe } from '../utils';\nimport { 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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 { HrTime } from '@opentelemetry/api';\nimport { Accumulation, Aggregator } from '../aggregator/types';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { MetricStorage } from './MetricStorage';\nimport { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport { Maybe } from '../utils';\nimport { MetricCollectorHandle } from './MetricCollector';\nimport { AttributeHashMap } from './HashMap';\nimport { AsyncWritableMetricStorage } from './WritableMetricStorage';\nimport { 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,\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 const processed = new AttributeHashMap<number>();\n Array.from(measurements.entries()).forEach(([attributes, value]) => {\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 { InstrumentSelectorCriteria } from './InstrumentSelector';\nimport { 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 { MetricStorage } from './MetricStorage';\nimport {\n InstrumentDescriptor,\n isDescriptorCompatibleWith,\n} from '../InstrumentDescriptor';\nimport * as api from '@opentelemetry/api';\nimport {\n getConflictResolutionRecipe,\n getIncompatibilityDetails,\n} from '../view/RegistrationConflicts';\nimport { 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 { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { WritableMetricStorage } from './WritableMetricStorage';\n\n/**\n * Internal interface.\n */\nexport class MultiMetricStorage implements WritableMetricStorage {\n private readonly _backingStorages: WritableMetricStorage[];\n constructor(backingStorages: WritableMetricStorage[]) {\n this._backingStorages = backingStorages;\n }\n\n record(\n value: number,\n attributes: Attributes,\n context: Context,\n recordTime: HrTime\n ) {\n this._backingStorages.forEach(it => {\n it.record(value, attributes, context, recordTime);\n });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n diag,\n ObservableResult,\n Attributes,\n ValueType,\n BatchObservableResult,\n Observable,\n} from '@opentelemetry/api';\nimport { AttributeHashMap } from './state/HashMap';\nimport { isObservableInstrument, ObservableInstrument } 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 {\n diag,\n HrTime,\n BatchObservableCallback,\n Observable,\n ObservableCallback,\n} from '@opentelemetry/api';\nimport { isObservableInstrument, ObservableInstrument } 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 { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { WritableMetricStorage } from './WritableMetricStorage';\nimport { Accumulation, Aggregator } from '../aggregator/types';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { IAttributesProcessor } from '../view/AttributesProcessor';\nimport { MetricStorage } from './MetricStorage';\nimport { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport { Maybe } from '../utils';\nimport { 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,\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(\n value: number,\n attributes: Attributes,\n context: Context,\n recordTime: HrTime\n ) {\n attributes = this._attributesProcessor.process(attributes, context);\n this._deltaMetricStorage.record(value, attributes, context, 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 { 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 _allowedAttributeNames: string[];\n constructor(allowedAttributeNames: string[]) {\n this._allowedAttributeNames = allowedAttributeNames;\n }\n\n process(incoming: Attributes, _context?: Context): Attributes {\n const filteredAttributes: Attributes = {};\n Object.keys(incoming).forEach(attributeName => {\n if (this._allowedAttributeNames.includes(attributeName)) {\n filteredAttributes[attributeName] = incoming[attributeName];\n }\n });\n return filteredAttributes;\n }\n}\n\nclass DenyListProcessor implements IAttributesProcessor {\n private _deniedAttributeNames: string[];\n constructor(deniedAttributeNames: string[]) {\n this._deniedAttributeNames = deniedAttributeNames;\n }\n\n process(incoming: Attributes, _context?: Context): Attributes {\n const filteredAttributes: Attributes = {};\n Object.keys(incoming).forEach(attributeName => {\n if (!this._deniedAttributeNames.includes(attributeName)) {\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 { HrTime } from '@opentelemetry/api';\nimport { InstrumentationScope } from '@opentelemetry/core';\nimport { MetricCollectOptions } from '../export/MetricProducer';\nimport { MetricData, ScopeMetrics } from '../export/MetricData';\nimport {\n createInstrumentDescriptorWithView,\n InstrumentDescriptor,\n} from '../InstrumentDescriptor';\nimport { Meter } from '../Meter';\nimport { Maybe } from '../utils';\nimport { AsyncMetricStorage } from './AsyncMetricStorage';\nimport { MeterProviderSharedState } from './MeterProviderSharedState';\nimport { MetricCollectorHandle } from './MetricCollector';\nimport { MetricStorageRegistry } from './MetricStorageRegistry';\nimport { MultiMetricStorage } from './MultiWritableMetricStorage';\nimport { ObservableRegistry } from './ObservableRegistry';\nimport { SyncMetricStorage } from './SyncMetricStorage';\nimport { Accumulation, Aggregator } from '../aggregator/types';\nimport {\n createNoopAttributesProcessor,\n IAttributesProcessor,\n} from '../view/AttributesProcessor';\nimport { 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 createNoopAttributesProcessor(),\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,\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 { InstrumentationScope } from '@opentelemetry/core';\nimport { Resource } from '@opentelemetry/resources';\nimport { instrumentationScopeId } from '../utils';\nimport { ViewRegistry } from '../view/ViewRegistry';\nimport { MeterSharedState } from './MeterSharedState';\nimport { MetricCollector, MetricCollectorHandle } from './MetricCollector';\nimport { toAggregation } from '../view/AggregationOption';\nimport { Aggregation } from '../view/Aggregation';\nimport { 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 { AggregationTemporalitySelector } from '../export/AggregationSelector';\nimport {\n CollectionResult,\n InstrumentType,\n ScopeMetrics,\n} from '../export/MetricData';\nimport { MetricCollectOptions, MetricProducer } from '../export/MetricProducer';\nimport { IMetricReader } from '../export/MetricReader';\nimport { ForceFlushOptions, ShutdownOptions } from '../types';\nimport { 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 { ExactPredicate, PatternPredicate, Predicate } from './Predicate';\nimport { 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 { ExactPredicate, Predicate } 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 {\n createMultiAttributesProcessor,\n createNoopAttributesProcessor,\n IAttributesProcessor,\n} from './AttributesProcessor';\nimport { InstrumentSelector } from './InstrumentSelector';\nimport { MeterSelector } from './MeterSelector';\nimport { Aggregation } from './Aggregation';\nimport {\n AggregationOption,\n AggregationType,\n toAggregation,\n} from './AggregationOption';\nimport { 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 * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n diag,\n MeterProvider as IMeterProvider,\n Meter as IMeter,\n MeterOptions,\n createNoopMeter,\n} from '@opentelemetry/api';\nimport { defaultResource, Resource } from '@opentelemetry/resources';\nimport { IMetricReader } from './export/MetricReader';\nimport { MeterProviderSharedState } from './state/MeterProviderSharedState';\nimport { MetricCollector } from './state/MetricCollector';\nimport { ForceFlushOptions, ShutdownOptions } from './types';\nimport { View, ViewOptions } 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/**\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 }\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 */\nimport {\n Fixed64,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from '../common/internal-types';\n\n/** Properties of an ExportMetricsServiceRequest. */\nexport interface IExportMetricsServiceRequest {\n /** ExportMetricsServiceRequest resourceMetrics */\n resourceMetrics: IResourceMetrics[];\n}\n\n/** Properties of a ResourceMetrics. */\nexport interface IResourceMetrics {\n /** ResourceMetrics resource */\n resource?: Resource;\n\n /** ResourceMetrics scopeMetrics */\n scopeMetrics: IScopeMetrics[];\n\n /** ResourceMetrics schemaUrl */\n schemaUrl?: string;\n}\n\n/** Properties of an IScopeMetrics. */\nexport interface IScopeMetrics {\n /** ScopeMetrics scope */\n scope?: IInstrumentationScope;\n\n /** ScopeMetrics metrics */\n metrics: IMetric[];\n\n /** ScopeMetrics schemaUrl */\n schemaUrl?: string;\n}\n\n/** Properties of a Metric. */\nexport interface IMetric {\n /** Metric name */\n name: string;\n\n /** Metric description */\n description?: string;\n\n /** Metric unit */\n unit?: string;\n\n /** Metric gauge */\n gauge?: IGauge;\n\n /** Metric sum */\n sum?: ISum;\n\n /** Metric histogram */\n histogram?: IHistogram;\n\n /** Metric exponentialHistogram */\n exponentialHistogram?: IExponentialHistogram;\n\n /** Metric summary */\n summary?: ISummary;\n}\n\n/** Properties of a Gauge. */\nexport interface IGauge {\n /** Gauge dataPoints */\n dataPoints: INumberDataPoint[];\n}\n\n/** Properties of a Sum. */\nexport interface ISum {\n /** Sum dataPoints */\n dataPoints: INumberDataPoint[];\n\n /** Sum aggregationTemporality */\n aggregationTemporality: EAggregationTemporality;\n\n /** Sum isMonotonic */\n isMonotonic?: boolean | null;\n}\n\n/** Properties of a Histogram. */\nexport interface IHistogram {\n /** Histogram dataPoints */\n dataPoints: IHistogramDataPoint[];\n\n /** Histogram aggregationTemporality */\n aggregationTemporality?: EAggregationTemporality;\n}\n\n/** Properties of an ExponentialHistogram. */\nexport interface IExponentialHistogram {\n /** ExponentialHistogram dataPoints */\n dataPoints: IExponentialHistogramDataPoint[];\n\n /** ExponentialHistogram aggregationTemporality */\n aggregationTemporality?: EAggregationTemporality;\n}\n\n/** Properties of a Summary. */\nexport interface ISummary {\n /** Summary dataPoints */\n dataPoints: ISummaryDataPoint[];\n}\n\n/** Properties of a NumberDataPoint. */\nexport interface INumberDataPoint {\n /** NumberDataPoint attributes */\n attributes: IKeyValue[];\n\n /** NumberDataPoint startTimeUnixNano */\n startTimeUnixNano?: Fixed64;\n\n /** NumberDataPoint timeUnixNano */\n timeUnixNano?: Fixed64;\n\n /** NumberDataPoint asDouble */\n asDouble?: number | null;\n\n /** NumberDataPoint asInt */\n asInt?: number;\n\n /** NumberDataPoint exemplars */\n exemplars?: IExemplar[];\n\n /** NumberDataPoint flags */\n flags?: number;\n}\n\n/** Properties of a HistogramDataPoint. */\nexport interface IHistogramDataPoint {\n /** HistogramDataPoint attributes */\n attributes?: IKeyValue[];\n\n /** HistogramDataPoint startTimeUnixNano */\n startTimeUnixNano?: Fixed64;\n\n /** HistogramDataPoint timeUnixNano */\n timeUnixNano?: Fixed64;\n\n /** HistogramDataPoint count */\n count?: number;\n\n /** HistogramDataPoint sum */\n sum?: number;\n\n /** HistogramDataPoint bucketCounts */\n bucketCounts?: number[];\n\n /** HistogramDataPoint explicitBounds */\n explicitBounds?: number[];\n\n /** HistogramDataPoint exemplars */\n exemplars?: IExemplar[];\n\n /** HistogramDataPoint flags */\n flags?: number;\n\n /** HistogramDataPoint min */\n min?: number;\n\n /** HistogramDataPoint max */\n max?: number;\n}\n\n/** Properties of an ExponentialHistogramDataPoint. */\nexport interface IExponentialHistogramDataPoint {\n /** ExponentialHistogramDataPoint attributes */\n attributes?: IKeyValue[];\n\n /** ExponentialHistogramDataPoint startTimeUnixNano */\n startTimeUnixNano?: Fixed64;\n\n /** ExponentialHistogramDataPoint timeUnixNano */\n timeUnixNano?: Fixed64;\n\n /** ExponentialHistogramDataPoint count */\n count?: number;\n\n /** ExponentialHistogramDataPoint sum */\n sum?: number;\n\n /** ExponentialHistogramDataPoint scale */\n scale?: number;\n\n /** ExponentialHistogramDataPoint zeroCount */\n zeroCount?: number;\n\n /** ExponentialHistogramDataPoint positive */\n positive?: IBuckets;\n\n /** ExponentialHistogramDataPoint negative */\n negative?: IBuckets;\n\n /** ExponentialHistogramDataPoint flags */\n flags?: number;\n\n /** ExponentialHistogramDataPoint exemplars */\n exemplars?: IExemplar[];\n\n /** ExponentialHistogramDataPoint min */\n min?: number;\n\n /** ExponentialHistogramDataPoint max */\n max?: number;\n}\n\n/** Properties of a SummaryDataPoint. */\nexport interface ISummaryDataPoint {\n /** SummaryDataPoint attributes */\n attributes?: IKeyValue[];\n\n /** SummaryDataPoint startTimeUnixNano */\n startTimeUnixNano?: number;\n\n /** SummaryDataPoint timeUnixNano */\n timeUnixNano?: string;\n\n /** SummaryDataPoint count */\n count?: number;\n\n /** SummaryDataPoint sum */\n sum?: number;\n\n /** SummaryDataPoint quantileValues */\n quantileValues?: IValueAtQuantile[];\n\n /** SummaryDataPoint flags */\n flags?: number;\n}\n\n/** Properties of a ValueAtQuantile. */\nexport interface IValueAtQuantile {\n /** ValueAtQuantile quantile */\n quantile?: number;\n\n /** ValueAtQuantile value */\n value?: number;\n}\n\n/** Properties of a Buckets. */\nexport interface IBuckets {\n /** Buckets offset */\n offset?: number;\n\n /** Buckets bucketCounts */\n bucketCounts?: number[];\n}\n\n/** Properties of an Exemplar. */\nexport interface IExemplar {\n /** Exemplar filteredAttributes */\n filteredAttributes?: IKeyValue[];\n\n /** Exemplar timeUnixNano */\n timeUnixNano?: string;\n\n /** Exemplar asDouble */\n asDouble?: number;\n\n /** Exemplar asInt */\n asInt?: number;\n\n /** Exemplar spanId */\n spanId?: string | Uint8Array;\n\n /** Exemplar traceId */\n traceId?: string | Uint8Array;\n}\n\n/**\n * AggregationTemporality defines how a metric aggregator reports aggregated\n * values. It describes how those values relate to the time interval over\n * which they are aggregated.\n */\nexport const enum EAggregationTemporality {\n /* UNSPECIFIED is the default AggregationTemporality, it MUST not be used. */\n AGGREGATION_TEMPORALITY_UNSPECIFIED = 0,\n\n /** DELTA is an AggregationTemporality for a metric aggregator which reports\n changes since last report time. Successive metrics contain aggregation of\n values from continuous and non-overlapping intervals.\n\n The values for a DELTA metric are based only on the time interval\n associated with one measurement cycle. There is no dependency on\n previous measurements like is the case for CUMULATIVE metrics.\n\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n DELTA metric:\n\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0+1 to\n t_0+2 with a value of 2. */\n AGGREGATION_TEMPORALITY_DELTA = 1,\n\n /** CUMULATIVE is an AggregationTemporality for a metric aggregator which\n reports changes since a fixed start time. This means that current values\n of a CUMULATIVE metric depend on all previous measurements since the\n start time. Because of this, the sender is required to retain this state\n in some form. If this state is lost or invalidated, the CUMULATIVE metric\n values MUST be reset and a new fixed start time following the last\n reported measurement time sent MUST be used.\n\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n CUMULATIVE metric:\n\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+2 with a value of 5.\n 9. The system experiences a fault and loses state.\n 10. The system recovers and resumes receiving at time=t_1.\n 11. A request is received, the system measures 1 request.\n 12. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_1 to\n t_0+1 with a value of 1.\n\n Note: Even though, when reporting changes since last report time, using\n CUMULATIVE is valid, it is not recommended. This may cause problems for\n systems that do not use start_time to determine when the aggregation\n value was reset (e.g. Prometheus). */\n AGGREGATION_TEMPORALITY_CUMULATIVE = 2,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ValueType } from '@opentelemetry/api';\nimport {\n AggregationTemporality,\n DataPoint,\n DataPointType,\n ExponentialHistogram,\n Histogram,\n MetricData,\n ResourceMetrics,\n ScopeMetrics,\n} from '@opentelemetry/sdk-metrics';\nimport {\n EAggregationTemporality,\n IExponentialHistogramDataPoint,\n IExportMetricsServiceRequest,\n IHistogramDataPoint,\n IMetric,\n INumberDataPoint,\n IResourceMetrics,\n IScopeMetrics,\n} from './internal-types';\nimport { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\n\nexport function toResourceMetrics(\n resourceMetrics: ResourceMetrics,\n encoder: Encoder\n): IResourceMetrics {\n const processedResource = createResource(resourceMetrics.resource, encoder);\n return {\n resource: processedResource,\n schemaUrl: processedResource.schemaUrl,\n scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder),\n };\n}\n\nexport function toScopeMetrics(\n scopeMetrics: ScopeMetrics[],\n encoder: Encoder\n): IScopeMetrics[] {\n return Array.from(\n scopeMetrics.map(metrics => ({\n scope: createInstrumentationScope(metrics.scope),\n metrics: metrics.metrics.map(metricData => toMetric(metricData, encoder)),\n schemaUrl: metrics.scope.schemaUrl,\n }))\n );\n}\n\nexport function toMetric(metricData: MetricData, encoder: Encoder): IMetric {\n const out: IMetric = {\n name: metricData.descriptor.name,\n description: metricData.descriptor.description,\n unit: metricData.descriptor.unit,\n };\n\n const aggregationTemporality = toAggregationTemporality(\n metricData.aggregationTemporality\n );\n\n switch (metricData.dataPointType) {\n case DataPointType.SUM:\n out.sum = {\n aggregationTemporality,\n isMonotonic: metricData.isMonotonic,\n dataPoints: toSingularDataPoints(metricData, encoder),\n };\n break;\n case DataPointType.GAUGE:\n out.gauge = {\n dataPoints: toSingularDataPoints(metricData, encoder),\n };\n break;\n case DataPointType.HISTOGRAM:\n out.histogram = {\n aggregationTemporality,\n dataPoints: toHistogramDataPoints(metricData, encoder),\n };\n break;\n case DataPointType.EXPONENTIAL_HISTOGRAM:\n out.exponentialHistogram = {\n aggregationTemporality,\n dataPoints: toExponentialHistogramDataPoints(metricData, encoder),\n };\n break;\n }\n\n return out;\n}\n\nfunction toSingularDataPoint(\n dataPoint:\n | DataPoint<number>\n | DataPoint<Histogram>\n | DataPoint<ExponentialHistogram>,\n valueType: ValueType,\n encoder: Encoder\n) {\n const out: INumberDataPoint = {\n attributes: toAttributes(dataPoint.attributes, encoder),\n startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),\n timeUnixNano: encoder.encodeHrTime(dataPoint.endTime),\n };\n\n switch (valueType) {\n case ValueType.INT:\n out.asInt = dataPoint.value as number;\n break;\n case ValueType.DOUBLE:\n out.asDouble = dataPoint.value as number;\n break;\n }\n\n return out;\n}\n\nfunction toSingularDataPoints(\n metricData: MetricData,\n encoder: Encoder\n): INumberDataPoint[] {\n return metricData.dataPoints.map(dataPoint => {\n return toSingularDataPoint(\n dataPoint,\n metricData.descriptor.valueType,\n encoder\n );\n });\n}\n\nfunction toHistogramDataPoints(\n metricData: MetricData,\n encoder: Encoder\n): IHistogramDataPoint[] {\n return metricData.dataPoints.map(dataPoint => {\n const histogram = dataPoint.value as Histogram;\n return {\n attributes: toAttributes(dataPoint.attributes, encoder),\n bucketCounts: histogram.buckets.counts,\n explicitBounds: histogram.buckets.boundaries,\n count: histogram.count,\n sum: histogram.sum,\n min: histogram.min,\n max: histogram.max,\n startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),\n timeUnixNano: encoder.encodeHrTime(dataPoint.endTime),\n };\n });\n}\n\nfunction toExponentialHistogramDataPoints(\n metricData: MetricData,\n encoder: Encoder\n): IExponentialHistogramDataPoint[] {\n return metricData.dataPoints.map(dataPoint => {\n const histogram = dataPoint.value as ExponentialHistogram;\n return {\n attributes: toAttributes(dataPoint.attributes, encoder),\n count: histogram.count,\n min: histogram.min,\n max: histogram.max,\n sum: histogram.sum,\n positive: {\n offset: histogram.positive.offset,\n bucketCounts: histogram.positive.bucketCounts,\n },\n negative: {\n offset: histogram.negative.offset,\n bucketCounts: histogram.negative.bucketCounts,\n },\n scale: histogram.scale,\n zeroCount: histogram.zeroCount,\n startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),\n timeUnixNano: encoder.encodeHrTime(dataPoint.endTime),\n };\n });\n}\n\nfunction toAggregationTemporality(\n temporality: AggregationTemporality\n): EAggregationTemporality {\n switch (temporality) {\n case AggregationTemporality.DELTA:\n return EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;\n case AggregationTemporality.CUMULATIVE:\n return EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;\n }\n}\n\nexport function createExportMetricsServiceRequest(\n resourceMetrics: ResourceMetrics[],\n encoder: Encoder\n): IExportMetricsServiceRequest {\n return {\n resourceMetrics: resourceMetrics.map(metrics =>\n toResourceMetrics(metrics, encoder)\n ),\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\nimport {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n encoder: Encoder\n): IExportTraceServiceRequest {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n record.instrumentationScope.version || ''\n }:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans: IResourceSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ISerializer } from '../../i-serializer';\nimport { ReadableLogRecord } from '@opentelemetry/sdk-logs';\nimport { createExportLogsServiceRequest } from '../internal';\nimport { IExportLogsServiceResponse } from '../export-response';\nimport { JSON_ENCODER } from '../../common/utils';\n\n/*\n * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant\n */\nexport const JsonLogsSerializer: ISerializer<\n ReadableLogRecord[],\n IExportLogsServiceResponse\n> = {\n serializeRequest: (arg: ReadableLogRecord[]) => {\n const request = createExportLogsServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportLogsServiceResponse;\n },\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ISerializer } from '../../i-serializer';\nimport { ResourceMetrics } from '@opentelemetry/sdk-metrics';\nimport { createExportMetricsServiceRequest } from '../internal';\nimport { IExportMetricsServiceResponse } from '../export-response';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonMetricsSerializer: ISerializer<\n ResourceMetrics,\n IExportMetricsServiceResponse\n> = {\n serializeRequest: (arg: ResourceMetrics) => {\n const request = createExportMetricsServiceRequest([arg], JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportMetricsServiceResponse;\n },\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ISerializer } from '../../i-serializer';\nimport { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { IExporterTransport } from './exporter-transport';\nimport { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n private _transport: IExporterTransport;\n\n constructor(transport: IExporterTransport) {\n this._transport = transport;\n }\n\n private retry(\n data: Uint8Array,\n timeoutMillis: number,\n inMillis: number\n ): Promise<ExportResponse> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(\n Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n 0\n );\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(\n `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n remainingTimeoutMillis\n )}ms, not retrying further.`\n );\n return result;\n }\n\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n\n if (result.status === 'success') {\n diag.verbose(\n `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n );\n } else if (result.status === 'retryable') {\n diag.info(\n `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n );\n } else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n\n return result;\n }\n\n shutdown() {\n return this._transport.shutdown();\n }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n // Underlying transport to wrap.\n transport: IExporterTransport;\n}): IExporterTransport {\n return new RetryingTransport(options.transport);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n return (\n statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504\n );\n}\n\nexport function parseRetryAfterToMills(\n retryAfter?: string | undefined | null\n): number | undefined {\n if (retryAfter == null) {\n return undefined;\n }\n\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { IExporterTransport } from '../exporter-transport';\nimport { ExportResponse } from '../export-response';\nimport { diag } from '@opentelemetry/api';\nimport {\n isExportHTTPErrorRetryable,\n parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { HeadersFactory } from '../configuration/otlp-http-configuration';\n\n/**\n * Maximum total body size for concurrent keepalive requests.\n * Browsers enforce a 64KiB cumulative limit across all pending keepalive requests.\n * We use 60KB to leave headroom for headers.\n * @see https://github.com/whatwg/fetch/issues/679\n * @see https://blog.huli.tw/2025/01/06/en/navigator-sendbeacon-64kib-and-source-code/\n */\nconst MAX_KEEPALIVE_BODY_SIZE = 60 * 1024;\n\n/**\n * Maximum concurrent keepalive requests.\n * Chrome enforces 9 concurrent keepalive fetch requests per renderer process.\n * @see https://github.com/whatwg/fetch/issues/679\n * Quote: \"If the renderer process is processing more than 9 requests with keepalive set, we reject a new request\"\n */\nconst MAX_KEEPALIVE_REQUESTS = 9;\n\n/**\n * Track cumulative pending body size across all in-flight keepalive requests.\n * This is necessary because the 64KiB limit is cumulative, not per-request.\n */\nlet pendingBodySize = 0;\n\n/**\n * Track number of pending keepalive requests.\n */\nlet pendingKeepaliveCount = 0;\n\nexport interface FetchTransportParameters {\n url: string;\n headers: HeadersFactory;\n}\n\nclass FetchTransport implements IExporterTransport {\n private _parameters: FetchTransportParameters;\n\n constructor(parameters: FetchTransportParameters) {\n this._parameters = parameters;\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), timeoutMillis);\n // Fetch API may be wrapped by an instrumentation like `@opentelemetry/instrumentation-fetch`.\n // In that case the instrumentation would create a new Span for this request\n // because the context manager cannot keep the context after `await` calls.\n // This creates an indirect endless loop Export -> Span -> Export\n // By using the `__original` function the instrumentation can't intercept the call\n // and no Span will be created breaking the vicious cycle\n let fetchApi = globalThis.fetch;\n // @ts-expect-error -- fetch could be wrapped\n if (typeof fetchApi.__original === 'function') {\n // @ts-expect-error -- fetch could be wrapped\n fetchApi = fetchApi.__original;\n }\n\n const requestSize = data.byteLength;\n\n // Determine if we can use keepalive based on cumulative browser limits.\n // We must check BEFORE adding to pending totals to avoid exceeding limits.\n const wouldExceedSize =\n pendingBodySize + requestSize > MAX_KEEPALIVE_BODY_SIZE;\n const wouldExceedCount = pendingKeepaliveCount >= MAX_KEEPALIVE_REQUESTS;\n const useKeepalive = !wouldExceedSize && !wouldExceedCount;\n\n if (useKeepalive) {\n pendingBodySize += requestSize;\n pendingKeepaliveCount++;\n } else {\n const reason = wouldExceedSize ? 'size limit' : 'count limit';\n diag.debug(\n `keepalive disabled: ${(requestSize / 1024).toFixed(1)}KB payload, ${pendingKeepaliveCount} pending (${reason})`\n );\n }\n\n try {\n const url = new URL(this._parameters.url);\n const response = await fetchApi(url.href, {\n method: 'POST',\n headers: await this._parameters.headers(),\n body: data,\n signal: abortController.signal,\n keepalive: useKeepalive,\n mode: globalThis.location\n ? globalThis.location.origin === url.origin\n ? 'same-origin'\n : 'cors'\n : 'no-cors',\n });\n\n if (response.status >= 200 && response.status <= 299) {\n diag.debug(`export response success (status: ${response.status})`);\n return { status: 'success' };\n } else if (isExportHTTPErrorRetryable(response.status)) {\n diag.warn(`export response retryable (status: ${response.status})`);\n const retryAfter = response.headers.get('Retry-After');\n const retryInMillis = parseRetryAfterToMills(retryAfter);\n return { status: 'retryable', retryInMillis };\n }\n diag.error(`export response failure (status: ${response.status})`);\n return {\n status: 'failure',\n error: new Error(\n `Fetch request failed with non-retryable status ${response.status}`\n ),\n };\n } catch (error) {\n if (isFetchNetworkErrorRetryable(error)) {\n diag.warn(`export request retryable (network error: ${error})`);\n return {\n status: 'retryable',\n error: new Error('Fetch request encountered a network error', {\n cause: error,\n }),\n };\n }\n diag.error(`export request failure (error: ${error})`);\n return {\n status: 'failure',\n error: new Error('Fetch request errored', { cause: error }),\n };\n } finally {\n clearTimeout(timeout);\n if (useKeepalive) {\n pendingBodySize -= requestSize;\n pendingKeepaliveCount--;\n }\n }\n }\n\n shutdown() {\n // Intentionally left empty, nothing to do.\n }\n}\n\n/**\n * Creates an exporter transport that uses `fetch` to send the data\n * @param parameters applied to each request made by transport\n */\nexport function createFetchTransport(\n parameters: FetchTransportParameters\n): IExporterTransport {\n return new FetchTransport(parameters);\n}\n\nfunction isFetchNetworkErrorRetryable(error: unknown): boolean {\n return error instanceof TypeError && !error.cause;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { OtlpHttpConfiguration } from './configuration/otlp-http-configuration';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createRetryingTransport } from './retrying-transport';\nimport { createOtlpNetworkExportDelegate } from './otlp-network-export-delegate';\nimport { createFetchTransport } from './transport/fetch-transport';\n\nexport function createOtlpFetchExportDelegate<Internal, Response>(\n options: OtlpHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpNetworkExportDelegate(\n options,\n serializer,\n createRetryingTransport({\n transport: createFetchTransport(options),\n })\n );\n}\n\n/**\n * @deprecated Use {@link createOtlpFetchExportDelegate} instead. Modern browsers use `fetch` with `keepAlive: true` when `sendBeacon` is used. Use a `fetch` polyfill that mimics this behavior to keep using `sendBeacon`.\n */\nexport function createOtlpSendBeaconExportDelegate<Internal, Response>(\n options: OtlpHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpFetchExportDelegate(options, serializer);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n const headers: Record<string, string> = {};\n Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n OtlpSharedConfiguration,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n url: string;\n headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n userProvidedHeaders: HeadersFactory | undefined | null,\n fallbackHeaders: HeadersFactory | undefined | null,\n defaultHeaders: HeadersFactory\n): HeadersFactory {\n return async () => {\n const requiredHeaders = {\n ...(await defaultHeaders()),\n };\n const headers = {};\n\n // add fallback ones first\n if (fallbackHeaders != null) {\n Object.assign(headers, await fallbackHeaders());\n }\n\n // override with user-provided ones\n if (userProvidedHeaders != null) {\n Object.assign(\n headers,\n validateAndNormalizeHeaders(await userProvidedHeaders())\n );\n }\n\n // override required ones.\n return Object.assign(headers, requiredHeaders);\n };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n if (url == null) {\n return undefined;\n }\n try {\n // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n const base = globalThis.location?.href;\n return new URL(url, base).href;\n } catch {\n throw new Error(\n `Configuration: Could not parse user-provided export URL: '${url}'`\n );\n }\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n headers: mergeHeaders(\n userProvidedConfiguration.headers,\n fallbackConfiguration.headers,\n defaultConfiguration.headers\n ),\n url:\n validateUserProvidedUrl(userProvidedConfiguration.url) ??\n fallbackConfiguration.url ??\n defaultConfiguration.url,\n };\n}\n\nexport function getHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpHttpConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n headers: async () => requiredHeaders,\n url: 'http://localhost:4318/' + signalResourcePath,\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n if (typeof config.headers === 'function') {\n return config.headers;\n }\n return wrapStaticHeadersInFunction(config.headers);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n OtlpHttpConfiguration,\n} from './otlp-http-configuration';\nimport { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\n/**\n * @deprecated this will be removed in 2.0\n *\n * @param config\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyBrowserHttpOptions(\n config: OTLPExporterNodeConfigBase,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): OtlpHttpConfiguration {\n return mergeOtlpHttpConfigurationWithDefaults(\n {\n url: config.url,\n timeoutMillis: config.timeoutMillis,\n headers: convertLegacyHeaders(config),\n concurrencyLimit: config.concurrencyLimit,\n },\n {}, // no fallback for browser case\n getHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createOtlpFetchExportDelegate } from '../otlp-browser-http-export-delegate';\nimport { convertLegacyBrowserHttpOptions } from './convert-legacy-browser-http-options';\nimport { IOtlpExportDelegate } from '../otlp-export-delegate';\nimport { OTLPExporterConfigBase } from './legacy-base-configuration';\n\n/**\n * @deprecated\n * @param config\n * @param serializer\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function createLegacyOtlpBrowserExportDelegate<Internal, Response>(\n config: OTLPExporterConfigBase,\n serializer: ISerializer<Internal, Response>,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): IOtlpExportDelegate<Internal> {\n const options = convertLegacyBrowserHttpOptions(\n config,\n signalResourcePath,\n requiredHeaders\n );\n\n return createOtlpFetchExportDelegate(options, serializer);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n ReadableLogRecord,\n LogRecordExporter,\n} from '@opentelemetry/sdk-logs';\nimport type { OTLPExporterConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonLogsSerializer } from '@opentelemetry/otlp-transformer';\nimport { createLegacyOtlpBrowserExportDelegate } from '@opentelemetry/otlp-exporter-base/browser-http';\n\n/**\n * Collector Logs Exporter for Web\n */\nexport class OTLPLogExporter\n extends OTLPExporterBase<ReadableLogRecord[]>\n implements LogRecordExporter\n{\n constructor(config: OTLPExporterConfigBase = {}) {\n super(\n createLegacyOtlpBrowserExportDelegate(\n config,\n JsonLogsSerializer,\n 'v1/logs',\n { 'Content-Type': 'application/json' }\n )\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { OTLPExporterConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport {\n AggregationTemporality,\n AggregationSelector,\n} from '@opentelemetry/sdk-metrics';\n\nexport interface OTLPMetricExporterOptions extends OTLPExporterConfigBase {\n temporalityPreference?:\n | AggregationTemporalityPreference\n | AggregationTemporality;\n aggregationPreference?: AggregationSelector;\n}\n\nexport enum AggregationTemporalityPreference {\n DELTA,\n CUMULATIVE,\n LOWMEMORY,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getStringFromEnv } from '@opentelemetry/core';\nimport {\n AggregationTemporality,\n AggregationTemporalitySelector,\n InstrumentType,\n PushMetricExporter,\n ResourceMetrics,\n AggregationSelector,\n AggregationOption,\n AggregationType,\n} from '@opentelemetry/sdk-metrics';\nimport {\n AggregationTemporalityPreference,\n OTLPMetricExporterOptions,\n} from './OTLPMetricExporterOptions';\nimport {\n IOtlpExportDelegate,\n OTLPExporterBase,\n} from '@opentelemetry/otlp-exporter-base';\nimport { diag } from '@opentelemetry/api';\n\nexport const CumulativeTemporalitySelector: AggregationTemporalitySelector =\n () => AggregationTemporality.CUMULATIVE;\n\nexport const DeltaTemporalitySelector: AggregationTemporalitySelector = (\n instrumentType: InstrumentType\n) => {\n switch (instrumentType) {\n case InstrumentType.COUNTER:\n case InstrumentType.OBSERVABLE_COUNTER:\n case InstrumentType.GAUGE:\n case InstrumentType.HISTOGRAM:\n case InstrumentType.OBSERVABLE_GAUGE:\n return AggregationTemporality.DELTA;\n case InstrumentType.UP_DOWN_COUNTER:\n case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:\n return AggregationTemporality.CUMULATIVE;\n }\n};\n\nexport const LowMemoryTemporalitySelector: AggregationTemporalitySelector = (\n instrumentType: InstrumentType\n) => {\n switch (instrumentType) {\n case InstrumentType.COUNTER:\n case InstrumentType.HISTOGRAM:\n return AggregationTemporality.DELTA;\n case InstrumentType.GAUGE:\n case InstrumentType.UP_DOWN_COUNTER:\n case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:\n case InstrumentType.OBSERVABLE_COUNTER:\n case InstrumentType.OBSERVABLE_GAUGE:\n return AggregationTemporality.CUMULATIVE;\n }\n};\n\nfunction chooseTemporalitySelectorFromEnvironment() {\n const configuredTemporality = (\n getStringFromEnv('OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE') ??\n 'cumulative'\n ).toLowerCase();\n\n if (configuredTemporality === 'cumulative') {\n return CumulativeTemporalitySelector;\n }\n if (configuredTemporality === 'delta') {\n return DeltaTemporalitySelector;\n }\n if (configuredTemporality === 'lowmemory') {\n return LowMemoryTemporalitySelector;\n }\n\n diag.warn(\n `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`\n );\n return CumulativeTemporalitySelector;\n}\n\nfunction chooseTemporalitySelector(\n temporalityPreference?:\n | AggregationTemporalityPreference\n | AggregationTemporality\n): AggregationTemporalitySelector {\n // Directly passed preference has priority.\n if (temporalityPreference != null) {\n if (temporalityPreference === AggregationTemporalityPreference.DELTA) {\n return DeltaTemporalitySelector;\n } else if (\n temporalityPreference === AggregationTemporalityPreference.LOWMEMORY\n ) {\n return LowMemoryTemporalitySelector;\n }\n return CumulativeTemporalitySelector;\n }\n\n return chooseTemporalitySelectorFromEnvironment();\n}\n\nconst DEFAULT_AGGREGATION = Object.freeze({\n type: AggregationType.DEFAULT,\n});\n\nfunction chooseAggregationSelector(\n config: OTLPMetricExporterOptions | undefined\n): AggregationSelector {\n return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION);\n}\n\nexport class OTLPMetricExporterBase\n extends OTLPExporterBase<ResourceMetrics>\n implements PushMetricExporter\n{\n private readonly _aggregationTemporalitySelector: AggregationTemporalitySelector;\n private readonly _aggregationSelector: AggregationSelector;\n\n constructor(\n delegate: IOtlpExportDelegate<ResourceMetrics>,\n config?: OTLPMetricExporterOptions\n ) {\n super(delegate);\n this._aggregationSelector = chooseAggregationSelector(config);\n this._aggregationTemporalitySelector = chooseTemporalitySelector(\n config?.temporalityPreference\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", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { OTLPMetricExporterOptions } from '../../OTLPMetricExporterOptions';\nimport { OTLPMetricExporterBase } from '../../OTLPMetricExporterBase';\nimport { OTLPExporterConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonMetricsSerializer } from '@opentelemetry/otlp-transformer';\nimport { createLegacyOtlpBrowserExportDelegate } from '@opentelemetry/otlp-exporter-base/browser-http';\n\n/**\n * Collector Metric Exporter for Web\n */\nexport class OTLPMetricExporter extends OTLPMetricExporterBase {\n constructor(config?: OTLPExporterConfigBase & OTLPMetricExporterOptions) {\n super(\n createLegacyOtlpBrowserExportDelegate(\n config ?? {},\n JsonMetricsSerializer,\n 'v1/metrics',\n { 'Content-Type': 'application/json' }\n ),\n config\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport {\n OTLPExporterConfigBase,\n OTLPExporterBase,\n} from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport { createLegacyOtlpBrowserExportDelegate } from '@opentelemetry/otlp-exporter-base/browser-http';\n\n/**\n * Collector Trace Exporter for Web\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBase<ReadableSpan[]>\n implements SpanExporter\n{\n constructor(config: OTLPExporterConfigBase = {}) {\n super(\n createLegacyOtlpBrowserExportDelegate(\n config,\n JsonTraceSerializer,\n 'v1/traces',\n { 'Content-Type': 'application/json' }\n )\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { AnyValue } from '@opentelemetry/api-logs';\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 return val.every(item => isLogAttributeValueInternal(item, visited));\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 return Object.values(obj).every(item =>\n isLogAttributeValueInternal(item, visited)\n );\n }\n\n return false;\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 { timeInputToHrTime, InstrumentationScope } 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 { isLogAttributeValue } from './utils/validation';\nimport { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';\n\nexport class LogRecordImpl implements ReadableLogRecord {\n readonly hrTime: api.HrTime;\n readonly hrTimeObserved: api.HrTime;\n readonly spanContext?: api.SpanContext;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly attributes: LogAttributes = {};\n private _severityText?: string;\n private _severityNumber?: SeverityNumber;\n private _body?: LogBody;\n private _eventName?: string;\n private totalAttributesCount: number = 0;\n\n private _isReadonly: boolean = false;\n private readonly _logRecordLimits: Required<LogRecordLimits>;\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.totalAttributesCount - Object.keys(this.attributes).length;\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 if (key.length === 0) {\n api.diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isLogAttributeValue(value)) {\n api.diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n this.totalAttributesCount += 1;\n if (\n Object.keys(this.attributes).length >=\n this._logRecordLimits.attributeCountLimit &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n // This logic is to create drop message at most once per LogRecord to prevent excessive logging.\n if (this.droppedAttributesCount === 1) {\n api.diag.warn('Dropping extra attributes.');\n }\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\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 _truncateToSize(value: AnyValue): AnyValue {\n const limit = this._logRecordLimits.attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n api.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 return this._truncateToLimitUtil(value, 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 => this._truncateToSize(val));\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] = this._truncateToSize(v);\n }\n return truncatedObj;\n }\n\n // Other types (number, boolean), no need to apply value length limit\n return value;\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 _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\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 type * as logsAPI from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n context,\n trace,\n TraceFlags,\n isSpanContextValid,\n} from '@opentelemetry/api';\n\nimport { LogRecordImpl } from './LogRecordImpl';\nimport { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';\nimport { LoggerConfig } from './types';\n\nexport class Logger implements logsAPI.Logger {\n public readonly instrumentationScope: InstrumentationScope;\n private _sharedState: LoggerProviderSharedState;\n private readonly _loggerConfig: Required<LoggerConfig>;\n\n constructor(\n instrumentationScope: InstrumentationScope,\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: logsAPI.LogRecord): void {\n const loggerConfig = this._loggerConfig;\n\n const currentContext = logRecord.context || context.active();\n\n // Apply minimum severity filtering\n const recordSeverity =\n logRecord.severityNumber ?? SeverityNumber.UNSPECIFIED;\n\n // 1. Minimum severity: If the log record's SeverityNumber is specified\n // (i.e. not 0) and is less than the configured minimum_severity,\n // the log record MUST be dropped.\n if (\n recordSeverity !== SeverityNumber.UNSPECIFIED &&\n recordSeverity < loggerConfig.minimumSeverity\n ) {\n // Log record is dropped due to minimum severity filter\n return;\n }\n\n // 2. Trace-based: If trace_based is true, and if the log record has a\n // SpanId and the TraceFlags SAMPLED flag is unset, the log record MUST be dropped.\n if (loggerConfig.traceBased) {\n const spanContext = trace.getSpanContext(currentContext);\n if (spanContext && isSpanContextValid(spanContext)) {\n // Check if the trace is unsampled (SAMPLED flag is unset)\n const isSampled =\n (spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED;\n if (!isSampled) {\n // Log record is dropped due to trace-based filter\n return;\n }\n }\n // If there's no valid span context, the log record is not associated with a trace\n // and therefore bypasses trace-based filtering (as per spec)\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 /**\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", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { LogRecordProcessor } from '../LogRecordProcessor';\nimport { ReadableLogRecord } from './ReadableLogRecord';\n\nexport class NoopLogRecordProcessor implements LogRecordProcessor {\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n onEmit(_logRecord: ReadableLogRecord, _context: Context): void {}\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { callWithTimeout } from '@opentelemetry/core';\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from './LogRecordProcessor';\nimport type { SdkLogRecord } from './export/SdkLogRecord';\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 public readonly forceFlushTimeoutMillis: number;\n constructor(\n processors: LogRecordProcessor[],\n forceFlushTimeoutMillis: number\n ) {\n this.processors = processors;\n this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;\n }\n\n public async forceFlush(): Promise<void> {\n const timeout = this.forceFlushTimeoutMillis;\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", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\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: InstrumentationScope\n): string {\n return `${scope.name}@${scope.version || ''}:${scope.schemaUrl || ''}`;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Logger } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { LogRecordProcessor } from '../LogRecordProcessor';\nimport { LogRecordLimits, LoggerConfig, LoggerConfigurator } from '../types';\nimport { NoopLogRecordProcessor } from '../export/NoopLogRecordProcessor';\nimport { MultiLogRecordProcessor } from '../MultiLogRecordProcessor';\nimport { getInstrumentationScopeKey } from './utils';\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 forceFlushTimeoutMillis: number;\n readonly logRecordLimits: Required<LogRecordLimits>;\n readonly processors: LogRecordProcessor[];\n private _loggerConfigurator: LoggerConfigurator;\n private _loggerConfigs: Map<string, Required<LoggerConfig>> = new Map();\n\n constructor(\n resource: Resource,\n forceFlushTimeoutMillis: number,\n logRecordLimits: Required<LogRecordLimits>,\n processors: LogRecordProcessor[],\n loggerConfigurator?: LoggerConfigurator\n ) {\n this.resource = resource;\n this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;\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 this.forceFlushTimeoutMillis\n );\n } else {\n this.activeProcessor = new NoopLogRecordProcessor();\n }\n\n this._loggerConfigurator =\n loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR;\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 */\nimport { diag } from '@opentelemetry/api';\nimport type * as logsAPI from '@opentelemetry/api-logs';\nimport { NOOP_LOGGER } from '@opentelemetry/api-logs';\nimport { defaultResource } from '@opentelemetry/resources';\nimport { BindOnceFuture } from '@opentelemetry/core';\n\nimport type { LoggerProviderConfig } from './types';\nimport { Logger } from './Logger';\nimport {\n DEFAULT_LOGGER_CONFIGURATOR,\n LoggerProviderSharedState,\n} from './internal/LoggerProviderSharedState';\n\nexport const DEFAULT_LOGGER_NAME = 'unknown';\n\nexport class LoggerProvider implements logsAPI.LoggerProvider {\n private _shutdownOnce: BindOnceFuture<void>;\n private readonly _sharedState: LoggerProviderSharedState;\n\n constructor(config: LoggerProviderConfig = {}) {\n const mergedConfig = {\n resource: config.resource ?? defaultResource(),\n forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 30000,\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 };\n this._sharedState = new LoggerProviderSharedState(\n mergedConfig.resource,\n mergedConfig.forceFlushTimeoutMillis,\n mergedConfig.logRecordLimits,\n mergedConfig.processors,\n mergedConfig.loggerConfigurator\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?: logsAPI.LoggerOptions\n ): logsAPI.Logger {\n if (this._shutdownOnce.isCalled) {\n diag.warn('A shutdown LoggerProvider cannot provide a Logger');\n return NOOP_LOGGER;\n }\n\n if (!name) {\n diag.warn('Logger requested without instrumentation scope name.');\n }\n const loggerName = name || DEFAULT_LOGGER_NAME;\n const key = `${loggerName}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._sharedState.loggers.has(key)) {\n this._sharedState.loggers.set(\n key,\n new Logger(\n { name: loggerName, version, schemaUrl: options?.schemaUrl },\n this._sharedState\n )\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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(): 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();\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 return this._sharedState.activeProcessor.shutdown();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport {\n ExportResult,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n internal,\n callWithTimeout,\n} from '@opentelemetry/core';\n\nimport type { BufferConfig } from '../types';\nimport type { SdkLogRecord } from './SdkLogRecord';\nimport type { LogRecordExporter } from './LogRecordExporter';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\n\nexport abstract class BatchLogRecordProcessorBase<T extends BufferConfig>\n implements LogRecordProcessor\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: LogRecordExporter;\n\n private _isExporting = false;\n private _finishedLogRecords: SdkLogRecord[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n\n constructor(exporter: LogRecordExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize = config?.maxExportBatchSize ?? 512;\n this._maxQueueSize = config?.maxQueueSize ?? 2048;\n this._scheduledDelayMillis = config?.scheduledDelayMillis ?? 5000;\n this._exportTimeoutMillis = config?.exportTimeoutMillis ?? 30000;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n public onEmit(logRecord: SdkLogRecord): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n this._addToBuffer(logRecord);\n }\n\n public forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n public shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private async _shutdown(): Promise<void> {\n this.onShutdown();\n await this._flushAll();\n await this._exporter.shutdown();\n }\n\n /** Add a LogRecord in the buffer. */\n private _addToBuffer(logRecord: SdkLogRecord) {\n if (this._finishedLogRecords.length >= this._maxQueueSize) {\n return;\n }\n this._finishedLogRecords.push(logRecord);\n this._maybeStartTimer();\n }\n\n /**\n * Send all LogRecords 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 const batchCount = Math.ceil(\n this._finishedLogRecords.length / this._maxExportBatchSize\n );\n for (let i = 0; i < batchCount; 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._finishedLogRecords.length === 0) {\n return Promise.resolve();\n }\n return callWithTimeout(\n this._export(\n this._finishedLogRecords.splice(0, this._maxExportBatchSize)\n ),\n this._exportTimeoutMillis\n );\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .then(() => {\n this._isExporting = false;\n if (this._finishedLogRecords.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._finishedLogRecords.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\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 private _export(logRecords: SdkLogRecord[]): Promise<void> {\n const doExport = () =>\n internal\n ._export(this._exporter, logRecords)\n .then((result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n globalErrorHandler(\n result.error ??\n new Error(\n `BatchLogRecordProcessor: log record export failed (status ${result})`\n )\n );\n }\n })\n .catch(globalErrorHandler);\n\n const pendingResources = [];\n\n for (let i = 0; i < logRecords.length; i++) {\n const resource = logRecords[i].resource;\n if (\n resource.asyncAttributesPending &&\n typeof resource.waitForAsyncAttributes === 'function'\n ) {\n pendingResources.push(resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources.length === 0) {\n return doExport();\n } else {\n return Promise.all(pendingResources).then(doExport, globalErrorHandler);\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 type { LogRecordExporter } from './../../../export/LogRecordExporter';\nimport type { BatchLogRecordProcessorBrowserConfig } from '../../../types';\nimport { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';\n\nexport class BatchLogRecordProcessor extends BatchLogRecordProcessorBase<BatchLogRecordProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n exporter: LogRecordExporter,\n config?: BatchLogRecordProcessorBrowserConfig\n ) {\n super(exporter, config);\n this._onInit(config);\n }\n\n protected onShutdown(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n\n private _onInit(config?: BatchLogRecordProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide === true ||\n typeof document === 'undefined'\n ) {\n return;\n }\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n void this.forceFlush();\n }\n };\n this._pageHideListener = () => {\n void this.forceFlush();\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n}\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 {\n Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n InstrumentationScope,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { SpanLimits } from './types';\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\ninterface SpanOptions {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n links?: Link[];\n startTime?: TimeInput;\n attributes?: Attributes;\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 this.links = opts.links || [];\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 [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\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 attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n addLink(link: Link): this {\n this.links.push(link);\n return this;\n }\n\n addLinks(links: Link[]): this {\n this.links.push(...links);\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = { ...status };\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 (this.status.message != null && typeof status.message !== 'string') {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n delete this.status.message;\n }\n\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._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", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\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\nimport { Sampler, SamplingDecision, SamplingResult } 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 { Sampler, SamplingDecision, SamplingResult } 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 {\n Context,\n isSpanContextValid,\n Link,\n Attributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport { 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 { isValidTraceId } from '@opentelemetry/api';\nimport { Sampler, SamplingDecision, SamplingResult } 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 = 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 < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\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\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\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 { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { Sampler } from './Sampler';\nimport { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\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 { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\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<T extends BufferConfig>\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\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(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 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\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 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\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 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 { SpanExporter } from '../../../export/SpanExporter';\nimport { BatchSpanProcessorBrowserConfig } from '../../../types';\nimport { globalErrorHandler } from '@opentelemetry/core';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BatchSpanProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n }\n };\n this._pageHideListener = () => {\n this.forceFlush().catch(error => {\n globalErrorHandler(error);\n });\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { IdGenerator } from '../../IdGenerator';\n\nconst TRACE_ID_BYTES = 16;\nconst SPAN_ID_BYTES = 8;\n\nconst TRACE_BUFFER = new Uint8Array(TRACE_ID_BYTES);\nconst SPAN_BUFFER = new Uint8Array(SPAN_ID_BYTES);\n\n// Byte-to-hex lookup is faster than toString(16) in browsers\nconst HEX: string[] = Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Fills buffer with random bytes, ensuring at least one is non-zero\n * per W3C Trace Context spec.\n */\nfunction randomFill(buf: Uint8Array): void {\n for (let i = 0; i < buf.length; i++) {\n buf[i] = (Math.random() * 256) >>> 0;\n }\n // Ensure non-zero\n for (let i = 0; i < buf.length; i++) {\n if (buf[i] > 0) return;\n }\n buf[buf.length - 1] = 1;\n}\n\nfunction toHex(buf: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < buf.length; i++) {\n hex += HEX[buf[i]];\n }\n return hex;\n}\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(): string {\n randomFill(TRACE_BUFFER);\n return toHex(TRACE_BUFFER);\n }\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(): string {\n randomFill(SPAN_BUFFER);\n return toHex(SPAN_BUFFER);\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 * 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 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 * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { Counter, Meter, SpanContext, UpDownCounter } 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 *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n InstrumentationScope,\n sanitizeAttributes,\n isTracingSuppressed,\n} from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Sampler } from './Sampler';\nimport { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\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 config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\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 * @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 /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\nimport { 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 { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport { defaultResource, Resource } from '@opentelemetry/resources';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum 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 BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\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._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.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", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Context, ContextManager, ROOT_CONTEXT } from '@opentelemetry/api';\n\n/**\n * Stack Context Manager for managing the state in web\n * it doesn't fully support the async calls though\n */\nexport class StackContextManager implements ContextManager {\n /**\n * whether the context manager is enabled or not\n */\n private _enabled = false;\n\n /**\n * Keeps the reference to current context\n */\n public _currentContext = ROOT_CONTEXT;\n\n /**\n *\n * @param context\n * @param target Function to be executed within the context\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n private _bindFunction<T extends Function>(\n context = ROOT_CONTEXT,\n target: T\n ): T {\n const manager = this;\n const contextWrapper = function (this: unknown, ...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 return contextWrapper as unknown as T;\n }\n\n /**\n * Returns the active context\n */\n active(): Context {\n return this._currentContext;\n }\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 no specific context to propagate is given, we use the current one\n if (context === undefined) {\n context = this.active();\n }\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n /**\n * Disable the context manager (clears the current context)\n */\n disable(): this {\n this._currentContext = ROOT_CONTEXT;\n this._enabled = false;\n return this;\n }\n\n /**\n * Enables the context manager and creates a default(root) context\n */\n enable(): this {\n if (this._enabled) {\n return this;\n }\n this._enabled = true;\n this._currentContext = ROOT_CONTEXT;\n return this;\n }\n\n /**\n * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.\n * The context will be set as active\n * @param context\n * @param fn Callback function\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context | null,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n const previousContext = this._currentContext;\n this._currentContext = context || ROOT_CONTEXT;\n\n try {\n return fn.call(thisArg, ...args);\n } finally {\n this._currentContext = previousContext;\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n BasicTracerProvider,\n SDKRegistrationConfig,\n TracerConfig,\n} from '@opentelemetry/sdk-trace-base';\nimport { StackContextManager } from './StackContextManager';\nimport {\n trace,\n context,\n ContextManager,\n propagation,\n TextMapPropagator,\n} 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 StackContextManager();\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 * WebTracerConfig provides an interface for configuring a Web Tracer.\n */\nexport type WebTracerConfig = TracerConfig;\n\n/**\n * This class represents a web tracer with {@link StackContextManager}\n */\nexport class WebTracerProvider extends BasicTracerProvider {\n /**\n * Constructs a new Tracer instance.\n * @param config Web Tracer config\n */\n constructor(config: WebTracerConfig = {}) {\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 setupPropagator(config.propagator);\n setupContextManager(config.contextManager);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport enum PerformanceTimingNames {\n CONNECT_END = 'connectEnd',\n CONNECT_START = 'connectStart',\n DECODED_BODY_SIZE = 'decodedBodySize',\n DOM_COMPLETE = 'domComplete',\n DOM_CONTENT_LOADED_EVENT_END = 'domContentLoadedEventEnd',\n DOM_CONTENT_LOADED_EVENT_START = 'domContentLoadedEventStart',\n DOM_INTERACTIVE = 'domInteractive',\n DOMAIN_LOOKUP_END = 'domainLookupEnd',\n DOMAIN_LOOKUP_START = 'domainLookupStart',\n ENCODED_BODY_SIZE = 'encodedBodySize',\n FETCH_START = 'fetchStart',\n LOAD_EVENT_END = 'loadEventEnd',\n LOAD_EVENT_START = 'loadEventStart',\n NAVIGATION_START = 'navigationStart',\n REDIRECT_END = 'redirectEnd',\n REDIRECT_START = 'redirectStart',\n REQUEST_START = 'requestStart',\n RESPONSE_END = 'responseEnd',\n RESPONSE_START = 'responseStart',\n SECURE_CONNECTION_START = 'secureConnectionStart',\n START_TIME = 'startTime',\n UNLOAD_EVENT_END = 'unloadEventEnd',\n UNLOAD_EVENT_START = 'unloadEventStart',\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 * Deprecated, use `http.response.header.<key>` instead.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.header.<key>`.\n */\nexport const ATTR_HTTP_RESPONSE_CONTENT_LENGTH =\n 'http.response_content_length' as const;\n\n/**\n * Deprecated, use `http.response.body.size` instead.\n *\n * @example 5493\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replace by `http.response.body.size`.\n */\nexport const ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.response_content_length_uncompressed' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n PerformanceEntries,\n PerformanceResourceTimingInfo,\n PropagateTraceHeaderCorsUrls,\n} from './types';\nimport { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';\nimport * as api from '@opentelemetry/api';\nimport {\n hrTimeToNanoseconds,\n timeInputToHrTime,\n urlMatches,\n} from '@opentelemetry/core';\nimport {\n ATTR_HTTP_RESPONSE_CONTENT_LENGTH,\n ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n} from './semconv';\n\n// Used to normalize relative URLs\nlet urlNormalizingAnchor: HTMLAnchorElement | undefined;\nfunction getUrlNormalizingAnchor(): HTMLAnchorElement {\n if (!urlNormalizingAnchor) {\n urlNormalizingAnchor = document.createElement('a');\n }\n\n return urlNormalizingAnchor;\n}\n\n/**\n * Helper function to be able to use enum as typed key in type and in interface when using forEach\n * @param obj\n * @param key\n */\nexport function hasKey<O extends object>(\n obj: O,\n key: PropertyKey\n): key is keyof O {\n return key in obj;\n}\n\n/**\n * Helper function for starting an event on span based on {@link PerformanceEntries}\n * @param span\n * @param performanceName name of performance entry for time start\n * @param entries\n * @param ignoreZeros\n */\nexport function addSpanNetworkEvent(\n span: api.Span,\n performanceName: string,\n entries: PerformanceEntries,\n ignoreZeros = true\n): api.Span | undefined {\n if (\n hasKey(entries, performanceName) &&\n typeof entries[performanceName] === 'number' &&\n !(ignoreZeros && entries[performanceName] === 0)\n ) {\n return span.addEvent(performanceName, entries[performanceName]);\n }\n\n return undefined;\n}\n\n/**\n * Helper function for adding network events and content length attributes.\n */\nexport function addSpanNetworkEvents(\n span: api.Span,\n resource: PerformanceEntries,\n ignoreNetworkEvents = false,\n ignoreZeros?: boolean,\n skipOldSemconvContentLengthAttrs?: boolean\n): void {\n if (ignoreZeros === undefined) {\n ignoreZeros = resource[PTN.START_TIME] !== 0;\n }\n\n if (!ignoreNetworkEvents) {\n addSpanNetworkEvent(span, PTN.FETCH_START, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_START, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_END, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.CONNECT_START, resource, ignoreZeros);\n addSpanNetworkEvent(\n span,\n PTN.SECURE_CONNECTION_START,\n resource,\n ignoreZeros\n );\n addSpanNetworkEvent(span, PTN.CONNECT_END, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.REQUEST_START, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.RESPONSE_START, resource, ignoreZeros);\n addSpanNetworkEvent(span, PTN.RESPONSE_END, resource, ignoreZeros);\n }\n\n if (!skipOldSemconvContentLengthAttrs) {\n // This block adds content-length-related span attributes using the\n // *old* HTTP semconv (v1.7.0).\n const encodedLength = resource[PTN.ENCODED_BODY_SIZE];\n if (encodedLength !== undefined) {\n span.setAttribute(ATTR_HTTP_RESPONSE_CONTENT_LENGTH, encodedLength);\n }\n\n const decodedLength = resource[PTN.DECODED_BODY_SIZE];\n // Spec: Not set if transport encoding not used (in which case encoded and decoded sizes match)\n if (decodedLength !== undefined && encodedLength !== decodedLength) {\n span.setAttribute(\n ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n decodedLength\n );\n }\n }\n}\n\n/**\n * sort resources by startTime\n * @param filteredResources\n */\nexport function sortResources(\n filteredResources: PerformanceResourceTiming[]\n): PerformanceResourceTiming[] {\n return filteredResources.slice().sort((a, b) => {\n const valueA = a[PTN.FETCH_START];\n const valueB = b[PTN.FETCH_START];\n if (valueA > valueB) {\n return 1;\n } else if (valueA < valueB) {\n return -1;\n }\n return 0;\n });\n}\n\n/** Returns the origin if present (if in browser context). */\nfunction getOrigin(): string | undefined {\n return typeof location !== 'undefined' ? location.origin : undefined;\n}\n\n/**\n * Get closest performance resource ignoring the resources that have been\n * already used.\n * @param spanUrl\n * @param startTimeHR\n * @param endTimeHR\n * @param resources\n * @param ignoredResources\n * @param initiatorType\n */\nexport function getResource(\n spanUrl: string,\n startTimeHR: api.HrTime,\n endTimeHR: api.HrTime,\n resources: PerformanceResourceTiming[],\n ignoredResources: WeakSet<PerformanceResourceTiming> = new WeakSet<PerformanceResourceTiming>(),\n initiatorType?: string\n): PerformanceResourceTimingInfo {\n // de-relativize the URL before usage (does no harm to absolute URLs)\n const parsedSpanUrl = parseUrl(spanUrl);\n spanUrl = parsedSpanUrl.toString();\n\n const filteredResources = filterResourcesForSpan(\n spanUrl,\n startTimeHR,\n endTimeHR,\n resources,\n ignoredResources,\n initiatorType\n );\n\n if (filteredResources.length === 0) {\n return {\n mainRequest: undefined,\n };\n }\n if (filteredResources.length === 1) {\n return {\n mainRequest: filteredResources[0],\n };\n }\n const sorted = sortResources(filteredResources);\n\n if (parsedSpanUrl.origin !== getOrigin() && sorted.length > 1) {\n let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];\n let mainRequest: PerformanceResourceTiming = findMainRequest(\n sorted,\n corsPreFlightRequest[PTN.RESPONSE_END],\n endTimeHR\n );\n\n const responseEnd = corsPreFlightRequest[PTN.RESPONSE_END];\n const fetchStart = mainRequest[PTN.FETCH_START];\n\n // no corsPreFlightRequest\n if (fetchStart < responseEnd) {\n mainRequest = corsPreFlightRequest;\n corsPreFlightRequest = undefined;\n }\n\n return {\n corsPreFlightRequest,\n mainRequest,\n };\n } else {\n return {\n mainRequest: filteredResources[0],\n };\n }\n}\n\n/**\n * Will find the main request skipping the cors pre flight requests\n * @param resources\n * @param corsPreFlightRequestEndTime\n * @param spanEndTimeHR\n */\nfunction findMainRequest(\n resources: PerformanceResourceTiming[],\n corsPreFlightRequestEndTime: number,\n spanEndTimeHR: api.HrTime\n): PerformanceResourceTiming {\n const spanEndTime = hrTimeToNanoseconds(spanEndTimeHR);\n const minTime = hrTimeToNanoseconds(\n timeInputToHrTime(corsPreFlightRequestEndTime)\n );\n\n let mainRequest: PerformanceResourceTiming = resources[1];\n let bestGap;\n\n const length = resources.length;\n for (let i = 1; i < length; i++) {\n const resource = resources[i];\n const resourceStartTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.FETCH_START])\n );\n\n const resourceEndTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.RESPONSE_END])\n );\n\n const currentGap = spanEndTime - resourceEndTime;\n\n if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) {\n bestGap = currentGap;\n mainRequest = resource;\n }\n }\n return mainRequest;\n}\n\n/**\n * Filter all resources that has started and finished according to span start time and end time.\n * It will return the closest resource to a start time\n * @param spanUrl\n * @param startTimeHR\n * @param endTimeHR\n * @param resources\n * @param ignoredResources\n */\nfunction filterResourcesForSpan(\n spanUrl: string,\n startTimeHR: api.HrTime,\n endTimeHR: api.HrTime,\n resources: PerformanceResourceTiming[],\n ignoredResources: WeakSet<PerformanceResourceTiming>,\n initiatorType?: string\n) {\n const startTime = hrTimeToNanoseconds(startTimeHR);\n const endTime = hrTimeToNanoseconds(endTimeHR);\n let filteredResources = resources.filter(resource => {\n const resourceStartTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.FETCH_START])\n );\n const resourceEndTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.RESPONSE_END])\n );\n\n return (\n resource.initiatorType.toLowerCase() ===\n (initiatorType || 'xmlhttprequest') &&\n resource.name === spanUrl &&\n resourceStartTime >= startTime &&\n resourceEndTime <= endTime\n );\n });\n\n if (filteredResources.length > 0) {\n filteredResources = filteredResources.filter(resource => {\n return !ignoredResources.has(resource);\n });\n }\n\n return filteredResources;\n}\n\n/**\n * The URLLike interface represents an URL and HTMLAnchorElement compatible fields.\n */\nexport interface URLLike {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n username: string;\n}\n\n/**\n * Parses url using URL constructor or fallback to anchor element.\n * @param url\n */\nexport function parseUrl(url: string): URLLike {\n if (typeof URL === 'function') {\n return new URL(\n url,\n typeof document !== 'undefined'\n ? document.baseURI\n : typeof location !== 'undefined' // Some JS runtimes (e.g. Deno) don't define this\n ? location.href\n : undefined\n );\n }\n const element = getUrlNormalizingAnchor();\n element.href = url;\n return element;\n}\n\n/**\n * Parses url using URL constructor or fallback to anchor element and serialize\n * it to a string.\n *\n * Performs the steps described in https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url\n *\n * @param url\n */\nexport function normalizeUrl(url: string): string {\n const urlLike = parseUrl(url);\n return urlLike.href;\n}\n\n/**\n * Get element XPath\n * @param target - target element\n * @param optimised - when id attribute of element is present the xpath can be\n * simplified to contain id\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function getElementXPath(target: any, optimised?: boolean): string {\n if (target.nodeType === Node.DOCUMENT_NODE) {\n return '/';\n }\n const targetValue = getNodeValue(target, optimised);\n if (optimised && targetValue.indexOf('@id') > 0) {\n return targetValue;\n }\n let xpath = '';\n if (target.parentNode) {\n xpath += getElementXPath(target.parentNode, optimised);\n }\n xpath += targetValue;\n\n return xpath;\n}\n\n/**\n * get node index within the siblings\n * @param target\n */\nfunction getNodeIndex(target: HTMLElement): number {\n if (!target.parentNode) {\n return 0;\n }\n const allowedTypes = [target.nodeType];\n if (target.nodeType === Node.CDATA_SECTION_NODE) {\n allowedTypes.push(Node.TEXT_NODE);\n }\n let elements = Array.from(target.parentNode.childNodes);\n elements = elements.filter((element: Node) => {\n const localName = (element as HTMLElement).localName;\n return (\n allowedTypes.indexOf(element.nodeType) >= 0 &&\n localName === target.localName\n );\n });\n if (elements.length >= 1) {\n return elements.indexOf(target) + 1; // xpath starts from 1\n }\n // if there are no other similar child xpath doesn't need index\n return 0;\n}\n\n/**\n * get node value for xpath\n * @param target\n * @param optimised\n */\nfunction getNodeValue(target: HTMLElement, optimised?: boolean): string {\n const nodeType = target.nodeType;\n const index = getNodeIndex(target);\n let nodeValue = '';\n if (nodeType === Node.ELEMENT_NODE) {\n const id = target.getAttribute('id');\n if (optimised && id) {\n return `//*[@id=\"${id}\"]`;\n }\n nodeValue = target.localName;\n } else if (\n nodeType === Node.TEXT_NODE ||\n nodeType === Node.CDATA_SECTION_NODE\n ) {\n nodeValue = 'text()';\n } else if (nodeType === Node.COMMENT_NODE) {\n nodeValue = 'comment()';\n } else {\n return '';\n }\n // if index is 1 it can be omitted in xpath\n if (nodeValue && index > 1) {\n return `/${nodeValue}[${index}]`;\n }\n return `/${nodeValue}`;\n}\n\n/**\n * Checks if trace headers should be propagated\n * @param spanUrl\n * @private\n */\nexport function shouldPropagateTraceHeaders(\n spanUrl: string,\n propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls\n): boolean {\n let propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || [];\n if (\n typeof propagateTraceHeaderUrls === 'string' ||\n propagateTraceHeaderUrls instanceof RegExp\n ) {\n propagateTraceHeaderUrls = [propagateTraceHeaderUrls];\n }\n const parsedSpanUrl = parseUrl(spanUrl);\n\n if (parsedSpanUrl.origin === getOrigin()) {\n return true;\n } else {\n return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>\n urlMatches(spanUrl, propagateTraceHeaderUrl)\n );\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/**\n * Enable instrumentations\n * @param instrumentations\n * @param tracerProvider\n * @param meterProvider\n */\nexport function enableInstrumentations(\n instrumentations: Instrumentation[],\n tracerProvider?: TracerProvider,\n meterProvider?: MeterProvider,\n loggerProvider?: LoggerProvider\n): void {\n for (let i = 0, j = instrumentations.length; i < j; i++) {\n const instrumentation = instrumentations[i];\n if (tracerProvider) {\n instrumentation.setTracerProvider(tracerProvider);\n }\n if (meterProvider) {\n instrumentation.setMeterProvider(meterProvider);\n }\n if (loggerProvider && instrumentation.setLoggerProvider) {\n instrumentation.setLoggerProvider(loggerProvider);\n }\n // instrumentations have been already enabled during creation\n // so enable only if user prevented that by setting enabled to false\n // this is to prevent double enabling but when calling register all\n // instrumentations should be now enabled\n if (!instrumentation.getConfig().enabled) {\n instrumentation.enable();\n }\n }\n}\n\n/**\n * Disable instrumentations\n * @param instrumentations\n */\nexport function disableInstrumentations(\n instrumentations: Instrumentation[]\n): void {\n instrumentations.forEach(instrumentation => instrumentation.disable());\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { trace, metrics } from '@opentelemetry/api';\nimport { logs } from '@opentelemetry/api-logs';\nimport {\n disableInstrumentations,\n enableInstrumentations,\n} from './autoLoaderUtils';\nimport { AutoLoaderOptions } from './types_internal';\n\n/**\n * It will register instrumentations and plugins\n * @param options\n * @return returns function to unload instrumentation and plugins that were\n * registered\n */\nexport function registerInstrumentations(\n options: AutoLoaderOptions\n): () => void {\n const tracerProvider = options.tracerProvider || trace.getTracerProvider();\n const meterProvider = options.meterProvider || metrics.getMeterProvider();\n const loggerProvider = options.loggerProvider || logs.getLoggerProvider();\n const instrumentations = options.instrumentations?.flat() ?? [];\n\n enableInstrumentations(\n instrumentations,\n tracerProvider,\n meterProvider,\n loggerProvider\n );\n\n return () => {\n disableInstrumentations(instrumentations);\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * BSD 2-Clause License\n *\n * Copyright (c) 2013-2019, Forrest L Norvell\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* Modified by OpenTelemetry Authors\n * - converted to TypeScript\n * - aligned with style-guide\n */\n\nimport { ShimWrapped } from './types';\n\n// Default to complaining loudly when things don't go according to plan.\n// eslint-disable-next-line no-console\nlet logger: typeof console.error = console.error.bind(console);\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty(obj: object, name: PropertyKey, value: unknown): void {\n const enumerable =\n !!obj[name as keyof typeof obj] &&\n Object.prototype.propertyIsEnumerable.call(obj, name);\n\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable,\n writable: true,\n value,\n });\n}\n\nexport const wrap = <Nodule extends object, FieldName extends keyof Nodule>(\n nodule: Nodule,\n name: FieldName,\n wrapper: (original: Nodule[FieldName], name: FieldName) => Nodule[FieldName]\n): ShimWrapped | undefined => {\n if (!nodule || !nodule[name]) {\n logger('no original function ' + String(name) + ' to wrap');\n return;\n }\n\n if (!wrapper) {\n logger('no wrapper function');\n logger(new Error().stack);\n return;\n }\n\n const original = nodule[name];\n\n if (typeof original !== 'function' || typeof wrapper !== 'function') {\n logger('original object and wrapper must be functions');\n return;\n }\n\n const wrapped = wrapper(original, name) as object;\n\n defineProperty(wrapped, '__original', original);\n defineProperty(wrapped, '__unwrap', () => {\n if (nodule[name] === wrapped) {\n defineProperty(nodule, name, original);\n }\n });\n defineProperty(wrapped, '__wrapped', true);\n defineProperty(nodule, name, wrapped);\n return wrapped as ShimWrapped;\n};\n\nexport const massWrap = <Nodule extends object, FieldName extends keyof Nodule>(\n nodules: Nodule[],\n names: FieldName[],\n wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]\n): void => {\n if (!nodules) {\n logger('must provide one or more modules to patch');\n logger(new Error().stack);\n return;\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules];\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to wrap on modules');\n return;\n }\n\n nodules.forEach(nodule => {\n names.forEach(name => {\n wrap(nodule, name, wrapper);\n });\n });\n};\n\nexport const unwrap = <Nodule extends object>(\n nodule: Nodule,\n name: keyof Nodule\n): void => {\n if (!nodule || !nodule[name]) {\n logger('no function to unwrap.');\n logger(new Error().stack);\n return;\n }\n\n const wrapped = nodule[name] as unknown as ShimWrapped;\n\n if (!wrapped.__unwrap) {\n logger(\n 'no original to unwrap to -- has ' +\n String(name) +\n ' already been unwrapped?'\n );\n } else {\n wrapped.__unwrap();\n return;\n }\n};\n\nexport const massUnwrap = <Nodule extends object>(\n nodules: Nodule[],\n names: Array<keyof Nodule>\n): void => {\n if (!nodules) {\n logger('must provide one or more modules to patch');\n logger(new Error().stack);\n return;\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules];\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to unwrap on modules');\n return;\n }\n\n nodules.forEach(nodule => {\n names.forEach(name => {\n unwrap(nodule, name);\n });\n });\n};\n\nexport interface ShimmerOptions {\n logger?: typeof console.error;\n}\n\nexport default function shimmer(options: ShimmerOptions): void {\n if (options && options.logger) {\n if (typeof options.logger !== 'function') {\n logger(\"new logger isn't a function, not replacing\");\n } else {\n logger = options.logger;\n }\n }\n}\n\nshimmer.wrap = wrap;\nshimmer.massWrap = massWrap;\nshimmer.unwrap = unwrap;\nshimmer.massUnwrap = massUnwrap;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n diag,\n DiagLogger,\n metrics,\n Meter,\n MeterProvider,\n trace,\n Tracer,\n TracerProvider,\n Span,\n} from '@opentelemetry/api';\nimport { Logger, LoggerProvider, logs } from '@opentelemetry/api-logs';\nimport * as shimmer from './shimmer';\nimport {\n InstrumentationModuleDefinition,\n Instrumentation,\n InstrumentationConfig,\n SpanCustomizationHook,\n} from './types';\n\n/**\n * Base abstract internal class for instrumenting node and web plugins\n */\nexport abstract class InstrumentationAbstract<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n> implements Instrumentation<ConfigType>\n{\n protected _config: ConfigType = {} as ConfigType;\n\n private _tracer: Tracer;\n private _meter: Meter;\n private _logger: Logger;\n protected _diag: DiagLogger;\n public readonly instrumentationName: string;\n public readonly instrumentationVersion: string;\n\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n this.instrumentationName = instrumentationName;\n this.instrumentationVersion = instrumentationVersion;\n\n this.setConfig(config);\n\n this._diag = diag.createComponentLogger({\n namespace: instrumentationName,\n });\n\n this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);\n this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);\n this._logger = logs.getLogger(instrumentationName, instrumentationVersion);\n this._updateMetricInstruments();\n }\n\n /* Api to wrap instrumented method */\n protected _wrap = shimmer.wrap;\n /* Api to unwrap instrumented methods */\n protected _unwrap = shimmer.unwrap;\n /* Api to mass wrap instrumented method */\n protected _massWrap = shimmer.massWrap;\n /* Api to mass unwrap instrumented methods */\n protected _massUnwrap = shimmer.massUnwrap;\n\n /* Returns meter */\n protected get meter(): Meter {\n return this._meter;\n }\n\n /**\n * Sets MeterProvider to this plugin\n * @param meterProvider\n */\n public setMeterProvider(meterProvider: MeterProvider): void {\n this._meter = meterProvider.getMeter(\n this.instrumentationName,\n this.instrumentationVersion\n );\n\n this._updateMetricInstruments();\n }\n\n /* Returns logger */\n protected get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Sets LoggerProvider to this plugin\n * @param loggerProvider\n */\n public setLoggerProvider(loggerProvider: LoggerProvider): void {\n this._logger = loggerProvider.getLogger(\n this.instrumentationName,\n this.instrumentationVersion\n );\n }\n\n /**\n * @experimental\n *\n * Get module definitions defined by {@link init}.\n * This can be used for experimental compile-time instrumentation.\n *\n * @returns an array of {@link InstrumentationModuleDefinition}\n */\n public getModuleDefinitions(): InstrumentationModuleDefinition[] {\n const initResult = this.init() ?? [];\n if (!Array.isArray(initResult)) {\n return [initResult];\n }\n\n return initResult;\n }\n\n /**\n * Sets the new metric instruments with the current Meter.\n */\n protected _updateMetricInstruments(): void {\n return;\n }\n\n /* Returns InstrumentationConfig */\n public getConfig(): ConfigType {\n return this._config;\n }\n\n /**\n * Sets InstrumentationConfig to this plugin\n * @param config\n */\n public setConfig(config: ConfigType): void {\n // copy config first level properties to ensure they are immutable.\n // nested properties are not copied, thus are mutable from the outside.\n this._config = {\n enabled: true,\n ...config,\n };\n }\n\n /**\n * Sets TraceProvider to this plugin\n * @param tracerProvider\n */\n public setTracerProvider(tracerProvider: TracerProvider): void {\n this._tracer = tracerProvider.getTracer(\n this.instrumentationName,\n this.instrumentationVersion\n );\n }\n\n /* Returns tracer */\n protected get tracer(): Tracer {\n return this._tracer;\n }\n\n /* Enable plugin */\n public abstract enable(): void;\n\n /* Disable plugin */\n public abstract disable(): void;\n\n /**\n * Init method in which plugin should define _modules and patches for\n * methods.\n */\n protected abstract init():\n | InstrumentationModuleDefinition\n | InstrumentationModuleDefinition[]\n | void;\n\n /**\n * Execute span customization hook, if configured, and log any errors.\n * Any semantics of the trigger and info are defined by the specific instrumentation.\n * @param hookHandler The optional hook handler which the user has configured via instrumentation config\n * @param triggerName The name of the trigger for executing the hook for logging purposes\n * @param span The span to which the hook should be applied\n * @param info The info object to be passed to the hook, with useful data the hook may use\n */\n protected _runSpanCustomizationHook<SpanCustomizationInfoType>(\n hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined,\n triggerName: string,\n span: Span,\n info: SpanCustomizationInfoType\n ) {\n if (!hookHandler) {\n return;\n }\n\n try {\n hookHandler(span, info);\n } catch (e) {\n this._diag.error(\n `Error running span customization hook due to exception in handler`,\n { triggerName },\n e\n );\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport * as types from '../../types';\nimport { InstrumentationConfig } from '../../types';\n\n/**\n * Base abstract class for instrumenting web plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ShimWrapped } from './types';\n\n/**\n * function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport function safeExecuteInTheMiddle<T>(\n execute: () => T,\n onFinish: (e: Error | undefined, result: T | undefined) => void,\n preventThrowingError?: boolean\n): T {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = execute();\n } catch (e) {\n error = e;\n } finally {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\n}\n\n/**\n * Async function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport async function safeExecuteInTheMiddleAsync<T>(\n execute: () => T,\n onFinish: (\n e: Error | undefined,\n result: T | undefined\n ) => Promise<void> | void,\n preventThrowingError?: boolean\n): Promise<T> {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = await execute();\n } catch (e) {\n error = e;\n } finally {\n await onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\n}\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nexport function isWrapped(func: unknown): func is ShimWrapped {\n return (\n typeof func === 'function' &&\n typeof (func as ShimWrapped).__original === 'function' &&\n typeof (func as ShimWrapped).__unwrap === 'function' &&\n (func as ShimWrapped).__wrapped === true\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport enum SemconvStability {\n /** Emit only stable semantic conventions. */\n STABLE = 0x1,\n /** Emit only old semantic conventions. */\n OLD = 0x2,\n /** Emit both stable and old semantic conventions. */\n DUPLICATE = 0x1 | 0x2,\n}\n\n// Common namespaces mentioned in semantic-conventions docs, but allow\n// other custom strings.\ntype SemConvStabilityNamespace =\n | 'http'\n | 'messaging'\n | 'database'\n | 'k8s'\n | (string & {});\n\n/**\n * Determine the appropriate semconv stability for the given namespace.\n *\n * This will parse the given string of comma-separated values (often\n * `process.env.OTEL_SEMCONV_STABILITY_OPT_IN`) looking for the `${namespace}`\n * or `${namespace}/dup` tokens. This is a pattern defined by a number of\n * non-normative semconv documents.\n *\n * For example:\n * - namespace 'http': https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/\n * - namespace 'database': https://opentelemetry.io/docs/specs/semconv/non-normative/database-migration/\n * - namespace 'k8s': https://opentelemetry.io/docs/specs/semconv/non-normative/k8s-migration/\n *\n * Usage:\n *\n * import {SemconvStability, semconvStabilityFromStr} from '@opentelemetry/instrumentation';\n *\n * export class FooInstrumentation extends InstrumentationBase<FooInstrumentationConfig> {\n * private _semconvStability: SemconvStability;\n * constructor(config: FooInstrumentationConfig = {}) {\n * super('@opentelemetry/instrumentation-foo', VERSION, config);\n *\n * // When supporting the OTEL_SEMCONV_STABILITY_OPT_IN envvar\n * this._semconvStability = semconvStabilityFromStr(\n * 'http',\n * process.env.OTEL_SEMCONV_STABILITY_OPT_IN\n * );\n *\n * // or when supporting a `semconvStabilityOptIn` config option (e.g. for\n * // the web where there are no envvars).\n * this._semconvStability = semconvStabilityFromStr(\n * 'http',\n * config?.semconvStabilityOptIn\n * );\n * }\n * }\n *\n * // Then, to apply semconv, use the following or similar:\n * if (this._semconvStability & SemconvStability.OLD) {\n * // ...\n * }\n * if (this._semconvStability & SemconvStability.STABLE) {\n * // ...\n * }\n *\n */\nexport function semconvStabilityFromStr(\n namespace: SemConvStabilityNamespace,\n str: string | undefined\n) {\n let semconvStability = SemconvStability.OLD;\n\n // The same parsing of `str` as `getStringListFromEnv` from the core pkg.\n const entries = str\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n for (const entry of entries ?? []) {\n if (entry.toLowerCase() === namespace + '/dup') {\n // DUPLICATE takes highest precedence.\n semconvStability = SemconvStability.DUPLICATE;\n break;\n } else if (entry.toLowerCase() === namespace) {\n semconvStability = SemconvStability.STABLE;\n }\n }\n\n return semconvStability;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum AttributeNames {\n DOCUMENT_LOAD = 'documentLoad',\n DOCUMENT_FETCH = 'documentFetch',\n RESOURCE_FETCH = 'resourceFetch',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.58.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-document-load';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\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 * Deprecated, use `http.response.header.content-length` instead.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.header.content-length`.\n */\nexport const ATTR_HTTP_RESPONSE_CONTENT_LENGTH =\n 'http.response_content_length' as const;\n\n/**\n * Deprecated, use `url.full` instead.\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `url.full`.\n */\nexport const ATTR_HTTP_URL = 'http.url' as const;\n\n/**\n * Deprecated, use `user_agent.original` instead.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `user_agent.original`.\n */\nexport const ATTR_HTTP_USER_AGENT = 'http.user_agent' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum EventNames {\n FIRST_PAINT = 'firstPaint',\n FIRST_CONTENTFUL_PAINT = 'firstContentfulPaint',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { otperformance } from '@opentelemetry/core';\nimport {\n hasKey,\n PerformanceEntries,\n PerformanceLegacy,\n PerformanceTimingNames as PTN,\n} from '@opentelemetry/sdk-trace-web';\nimport { EventNames } from './enums/EventNames';\n\nexport const getPerformanceNavigationEntries = (): PerformanceEntries => {\n const entries: PerformanceEntries = {};\n const performanceNavigationTiming = (\n otperformance as unknown as Performance\n ).getEntriesByType?.('navigation')[0] as PerformanceEntries;\n\n if (performanceNavigationTiming) {\n const keys = Object.values(PTN);\n keys.forEach((key: string) => {\n if (hasKey(performanceNavigationTiming, key)) {\n const value = performanceNavigationTiming[key];\n if (typeof value === 'number') {\n entries[key] = value;\n }\n }\n });\n } else {\n // // fallback to previous version\n const perf: typeof otperformance & PerformanceLegacy = otperformance;\n const performanceTiming = perf.timing;\n if (performanceTiming) {\n const keys = Object.values(PTN);\n keys.forEach((key: string) => {\n if (hasKey(performanceTiming, key)) {\n const value = performanceTiming[key];\n if (typeof value === 'number') {\n entries[key] = value;\n }\n }\n });\n }\n }\n\n return entries;\n};\n\nconst performancePaintNames = {\n 'first-paint': EventNames.FIRST_PAINT,\n 'first-contentful-paint': EventNames.FIRST_CONTENTFUL_PAINT,\n};\n\nexport const addSpanPerformancePaintEvents = (span: Span) => {\n const performancePaintTiming = (\n otperformance as unknown as Performance\n ).getEntriesByType?.('paint');\n if (performancePaintTiming) {\n performancePaintTiming.forEach(({ name, startTime }) => {\n if (hasKey(performancePaintNames, name)) {\n span.addEvent(performancePaintNames[name], startTime);\n }\n });\n }\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n context,\n propagation,\n trace,\n Span,\n ROOT_CONTEXT,\n} from '@opentelemetry/api';\nimport { otperformance, TRACE_PARENT_HEADER } from '@opentelemetry/core';\nimport {\n addSpanNetworkEvent,\n addSpanNetworkEvents,\n hasKey,\n PerformanceEntries,\n PerformanceTimingNames as PTN,\n} from '@opentelemetry/sdk-trace-web';\nimport {\n SemconvStability,\n semconvStabilityFromStr,\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport {\n ATTR_URL_FULL,\n ATTR_USER_AGENT_ORIGINAL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n DocumentLoadCustomAttributeFunction,\n DocumentLoadInstrumentationConfig,\n ResourceFetchCustomAttributeFunction,\n} from './types';\nimport { AttributeNames } from './enums/AttributeNames';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { ATTR_HTTP_URL, ATTR_HTTP_USER_AGENT } from './semconv';\nimport {\n addSpanPerformancePaintEvents,\n getPerformanceNavigationEntries,\n} from './utils';\n\n/**\n * This class represents a document load plugin\n */\nexport class DocumentLoadInstrumentation extends InstrumentationBase<DocumentLoadInstrumentationConfig> {\n readonly component: string = 'document-load';\n readonly version: string = '1';\n moduleName = this.component;\n\n private _semconvStability: SemconvStability;\n\n constructor(config: DocumentLoadInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n this._semconvStability = semconvStabilityFromStr(\n 'http',\n config?.semconvStabilityOptIn\n );\n }\n\n init() {}\n\n /**\n * callback to be executed when page is loaded\n */\n private _onDocumentLoaded() {\n // Timeout is needed as load event doesn't have yet the performance metrics for loadEnd.\n // Support for event \"loadend\" is very limited and cannot be used\n window.setTimeout(() => {\n this._collectPerformance();\n });\n }\n\n /**\n * Adds spans for all resources\n * @param rootSpan\n */\n private _addResourcesSpans(rootSpan: Span): void {\n const resources: PerformanceResourceTiming[] = (\n otperformance as unknown as Performance\n ).getEntriesByType?.('resource') as PerformanceResourceTiming[];\n if (resources) {\n resources.forEach(resource => {\n this._initResourceSpan(resource, rootSpan);\n });\n }\n }\n\n /**\n * Collects information about performance and creates appropriate spans\n */\n private _collectPerformance() {\n const metaElement = Array.from(document.getElementsByTagName('meta')).find(\n e => e.getAttribute('name') === TRACE_PARENT_HEADER\n );\n const entries = getPerformanceNavigationEntries();\n const traceparent = (metaElement && metaElement.content) || '';\n context.with(propagation.extract(ROOT_CONTEXT, { traceparent }), () => {\n const rootSpan = this._startSpan(\n AttributeNames.DOCUMENT_LOAD,\n PTN.FETCH_START,\n entries\n );\n if (!rootSpan) {\n return;\n }\n context.with(trace.setSpan(context.active(), rootSpan), () => {\n const fetchSpan = this._startSpan(\n AttributeNames.DOCUMENT_FETCH,\n PTN.FETCH_START,\n entries\n );\n if (fetchSpan) {\n if (this._semconvStability & SemconvStability.OLD) {\n fetchSpan.setAttribute(ATTR_HTTP_URL, location.href);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n fetchSpan.setAttribute(ATTR_URL_FULL, location.href);\n }\n context.with(trace.setSpan(context.active(), fetchSpan), () => {\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n addSpanNetworkEvents(\n fetchSpan,\n entries,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n this._addCustomAttributesOnSpan(\n fetchSpan,\n this.getConfig().applyCustomAttributesOnSpan?.documentFetch\n );\n this._endSpan(fetchSpan, PTN.RESPONSE_END, entries);\n });\n }\n });\n\n if (this._semconvStability & SemconvStability.OLD) {\n rootSpan.setAttribute(ATTR_HTTP_URL, location.href);\n rootSpan.setAttribute(ATTR_HTTP_USER_AGENT, navigator.userAgent);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n rootSpan.setAttribute(ATTR_URL_FULL, location.href);\n rootSpan.setAttribute(ATTR_USER_AGENT_ORIGINAL, navigator.userAgent);\n }\n\n this._addResourcesSpans(rootSpan);\n\n if (!this.getConfig().ignoreNetworkEvents) {\n addSpanNetworkEvent(rootSpan, PTN.FETCH_START, entries);\n addSpanNetworkEvent(rootSpan, PTN.UNLOAD_EVENT_START, entries);\n addSpanNetworkEvent(rootSpan, PTN.UNLOAD_EVENT_END, entries);\n addSpanNetworkEvent(rootSpan, PTN.DOM_INTERACTIVE, entries);\n addSpanNetworkEvent(\n rootSpan,\n PTN.DOM_CONTENT_LOADED_EVENT_START,\n entries\n );\n addSpanNetworkEvent(\n rootSpan,\n PTN.DOM_CONTENT_LOADED_EVENT_END,\n entries\n );\n addSpanNetworkEvent(rootSpan, PTN.DOM_COMPLETE, entries);\n addSpanNetworkEvent(rootSpan, PTN.LOAD_EVENT_START, entries);\n addSpanNetworkEvent(rootSpan, PTN.LOAD_EVENT_END, entries);\n }\n\n if (!this.getConfig().ignorePerformancePaintEvents) {\n addSpanPerformancePaintEvents(rootSpan);\n }\n\n this._addCustomAttributesOnSpan(\n rootSpan,\n this.getConfig().applyCustomAttributesOnSpan?.documentLoad\n );\n this._endSpan(rootSpan, PTN.LOAD_EVENT_END, entries);\n });\n }\n\n /**\n * Helper function for ending span\n * @param span\n * @param performanceName name of performance entry for time end\n * @param entries\n */\n private _endSpan(\n span: Span | undefined,\n performanceName: string,\n entries: PerformanceEntries\n ) {\n // span can be undefined when entries are missing the certain performance - the span will not be created\n if (span) {\n if (hasKey(entries, performanceName)) {\n span.end(entries[performanceName]);\n } else {\n // just end span\n span.end();\n }\n }\n }\n\n /**\n * Creates and ends a span with network information about resource added as timed events\n * @param resource\n * @param parentSpan\n */\n private _initResourceSpan(\n resource: PerformanceResourceTiming,\n parentSpan: Span\n ) {\n const span = this._startSpan(\n AttributeNames.RESOURCE_FETCH,\n PTN.FETCH_START,\n resource,\n parentSpan\n );\n if (span) {\n if (this._semconvStability & SemconvStability.OLD) {\n span.setAttribute(ATTR_HTTP_URL, resource.name);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n span.setAttribute(ATTR_URL_FULL, resource.name);\n }\n\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n addSpanNetworkEvents(\n span,\n resource,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n this._addCustomAttributesOnResourceSpan(\n span,\n resource,\n this.getConfig().applyCustomAttributesOnSpan?.resourceFetch\n );\n this._endSpan(span, PTN.RESPONSE_END, resource);\n }\n }\n\n /**\n * Helper function for starting a span\n * @param spanName name of span\n * @param performanceName name of performance entry for time start\n * @param entries\n * @param parentSpan\n */\n private _startSpan(\n spanName: string,\n performanceName: string,\n entries: PerformanceEntries,\n parentSpan?: Span\n ): Span | undefined {\n if (\n hasKey(entries, performanceName) &&\n typeof entries[performanceName] === 'number'\n ) {\n const span = this.tracer.startSpan(\n spanName,\n {\n startTime: entries[performanceName],\n },\n parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined\n );\n return span;\n }\n return undefined;\n }\n\n /**\n * executes callback {_onDocumentLoaded} when the page is loaded\n */\n private _waitForPageLoad() {\n if (window.document.readyState === 'complete') {\n this._onDocumentLoaded();\n } else {\n this._onDocumentLoaded = this._onDocumentLoaded.bind(this);\n window.addEventListener('load', this._onDocumentLoaded);\n }\n }\n\n /**\n * adds custom attributes to root span if configured\n */\n private _addCustomAttributesOnSpan(\n span: Span,\n applyCustomAttributesOnSpan: DocumentLoadCustomAttributeFunction | undefined\n ) {\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('addCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * adds custom attributes to span if configured\n */\n private _addCustomAttributesOnResourceSpan(\n span: Span,\n resource: PerformanceResourceTiming,\n applyCustomAttributesOnSpan:\n | ResourceFetchCustomAttributeFunction\n | undefined\n ) {\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, resource),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('addCustomAttributesOnResourceSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * implements enable function\n */\n override enable() {\n // remove previously attached load to avoid adding the same event twice\n // in case of multiple enable calling.\n window.removeEventListener('load', this._onDocumentLoaded);\n this._waitForPageLoad();\n }\n\n /**\n * implements disable function\n */\n override disable() {\n window.removeEventListener('load', this._onDocumentLoaded);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md\n */\nexport enum AttributeNames {\n COMPONENT = 'component',\n HTTP_STATUS_TEXT = 'http.status_text',\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 * Deprecated, use one of `server.address`, `client.address` or `http.request.header.host` instead, depending on the usage.\n *\n * @example www.example.org\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by one of `server.address`, `client.address` or `http.request.header.host`, depending on the usage.\n */\nexport const ATTR_HTTP_HOST = 'http.host' as const;\n\n/**\n * Deprecated, use `http.request.method` instead.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.request.method`.\n */\nexport const ATTR_HTTP_METHOD = 'http.method' as const;\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HTTP_REQUEST_BODY_SIZE = 'http.request.body.size' as const;\n\n/**\n * Deprecated, use `http.request.body.size` instead.\n *\n * @example 5493\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.request.body.size`.\n */\nexport const ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.request_content_length_uncompressed' as const;\n\n/**\n * Deprecated, use `http.response.header.<key>` instead.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.header.<key>`.\n */\nexport const ATTR_HTTP_RESPONSE_CONTENT_LENGTH =\n 'http.response_content_length' as const;\n\n/**\n * Deprecated, use `url.scheme` instead.\n *\n * @example http\n * @example https\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `url.scheme` instead.\n */\nexport const ATTR_HTTP_SCHEME = 'http.scheme' as const;\n\n/**\n * Deprecated, use `http.response.status_code` instead.\n *\n * @example 200\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.status_code`.\n */\nexport const ATTR_HTTP_STATUS_CODE = 'http.status_code' as const;\n\n/**\n * Deprecated, use `url.full` instead.\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `url.full`.\n */\nexport const ATTR_HTTP_URL = 'http.url' as const;\n\n/**\n * Deprecated, use `user_agent.original` instead.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `user_agent.original`.\n */\nexport const ATTR_HTTP_USER_AGENT = 'http.user_agent' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Much of the logic here overlaps with the same utils file in opentelemetry-instrumentation-xml-http-request\n// These may be unified in the future.\n\nimport { diag } from '@opentelemetry/api';\nimport { getStringListFromEnv } from '@opentelemetry/core';\nimport { URLLike } from '@opentelemetry/sdk-trace-web';\n\nconst DIAG_LOGGER = diag.createComponentLogger({\n namespace: '@opentelemetry/opentelemetry-instrumentation-fetch/utils',\n});\n\n/**\n * Helper function to determine payload content length for fetch requests\n *\n * The fetch API is kinda messy: there are a couple of ways the body can be passed in.\n *\n * In all cases, the body param can be some variation of ReadableStream,\n * and ReadableStreams can only be read once! We want to avoid consuming the body here,\n * because that would mean that the body never gets sent with the actual fetch request.\n *\n * Either the first arg is a Request object, which can be cloned\n * so we can clone that object and read the body of the clone\n * without disturbing the original argument\n * However, reading the body here can only be done async; the body() method returns a promise\n * this means this entire function has to return a promise\n *\n * OR the first arg is a url/string\n * in which case the second arg has type RequestInit\n * RequestInit is NOT cloneable, but RequestInit.body is writable\n * so we can chain it into ReadableStream.pipeThrough()\n *\n * ReadableStream.pipeThrough() lets us process a stream and returns a new stream\n * So we can measure the body length as it passes through the pie, but need to attach\n * the new stream to the original request\n * so that the browser still has access to the body.\n *\n * @param body\n * @returns promise that resolves to the content length of the body\n */\nexport function getFetchBodyLength(...args: Parameters<typeof fetch>) {\n if (args[0] instanceof URL || typeof args[0] === 'string') {\n const requestInit = args[1];\n if (!requestInit?.body) {\n return Promise.resolve();\n }\n if (requestInit.body instanceof ReadableStream) {\n const { body, length } = _getBodyNonDestructively(requestInit.body);\n requestInit.body = body;\n\n return length;\n } else {\n return Promise.resolve(getXHRBodyLength(requestInit.body));\n }\n } else {\n const info = args[0];\n if (!info?.body) {\n return Promise.resolve();\n }\n\n return info\n .clone()\n .text()\n .then(t => getByteLength(t));\n }\n}\n\nfunction _getBodyNonDestructively(body: ReadableStream) {\n // can't read a ReadableStream without destroying it\n // but we CAN pipe it through and return a new ReadableStream\n\n // some (older) platforms don't expose the pipeThrough method and in that scenario, we're out of luck;\n // there's no way to read the stream without consuming it.\n if (!body.pipeThrough) {\n DIAG_LOGGER.warn('Platform has ReadableStream but not pipeThrough!');\n return {\n body,\n length: Promise.resolve(undefined),\n };\n }\n\n let length = 0;\n let resolveLength: (l: number) => void;\n const lengthPromise = new Promise<number>(resolve => {\n resolveLength = resolve;\n });\n\n const transform = new TransformStream({\n start() {},\n async transform(chunk, controller) {\n const bytearray = (await chunk) as Uint8Array;\n length += bytearray.byteLength;\n\n controller.enqueue(chunk);\n },\n flush() {\n resolveLength(length);\n },\n });\n\n return {\n body: body.pipeThrough(transform),\n length: lengthPromise,\n };\n}\n\nfunction isDocument(value: unknown): value is Document {\n return typeof Document !== 'undefined' && value instanceof Document;\n}\n\n/**\n * Helper function to determine payload content length for XHR requests\n * @param body\n * @returns content length\n */\nexport function getXHRBodyLength(\n body: Document | XMLHttpRequestBodyInit\n): number | undefined {\n if (isDocument(body)) {\n return new XMLSerializer().serializeToString(document).length;\n }\n\n // XMLHttpRequestBodyInit expands to the following:\n if (typeof body === 'string') {\n return getByteLength(body);\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof FormData) {\n return getFormDataSize(body);\n }\n\n if (body instanceof URLSearchParams) {\n return getByteLength(body.toString());\n }\n\n // ArrayBuffer | ArrayBufferView\n if (body.byteLength !== undefined) {\n return body.byteLength;\n }\n\n DIAG_LOGGER.warn('unknown body type');\n return undefined;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\nfunction getByteLength(s: string): number {\n return TEXT_ENCODER.encode(s).byteLength;\n}\n\nfunction getFormDataSize(formData: FormData): number {\n let size = 0;\n for (const [key, value] of formData.entries()) {\n size += key.length;\n if (value instanceof Blob) {\n size += value.size;\n } else {\n size += value.length;\n }\n }\n return size;\n}\n\n/**\n * Normalize an HTTP request method string per `http.request.method` spec\n * https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md#http-client-span\n */\nexport function normalizeHttpRequestMethod(method: string): string {\n const knownMethods = getKnownMethods();\n const methUpper = method.toUpperCase();\n if (methUpper in knownMethods) {\n return methUpper;\n } else {\n return '_OTHER';\n }\n}\n\nconst DEFAULT_KNOWN_METHODS = {\n CONNECT: true,\n DELETE: true,\n GET: true,\n HEAD: true,\n OPTIONS: true,\n PATCH: true,\n POST: true,\n PUT: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/\n QUERY: true,\n};\nlet knownMethods: { [key: string]: boolean };\nfunction getKnownMethods() {\n if (knownMethods === undefined) {\n const cfgMethods = getStringListFromEnv(\n 'OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS'\n );\n if (cfgMethods && cfgMethods.length > 0) {\n knownMethods = {};\n cfgMethods.forEach(m => {\n knownMethods[m] = true;\n });\n } else {\n knownMethods = DEFAULT_KNOWN_METHODS;\n }\n }\n return knownMethods;\n}\n\nconst HTTP_PORT_FROM_PROTOCOL: { [key: string]: string } = {\n 'https:': '443',\n 'http:': '80',\n};\nexport function serverPortFromUrl(url: URLLike): number | undefined {\n const serverPort = Number(url.port || HTTP_PORT_FROM_PROTOCOL[url.protocol]);\n // Guard with `if (serverPort)` because `Number('') === 0`.\n if (serverPort && !isNaN(serverPort)) {\n return serverPort;\n } else {\n return undefined;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.213.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n} from '@opentelemetry/api';\nimport type { Attributes, HrTime, Span } from '@opentelemetry/api';\nimport {\n SemconvStability,\n semconvStabilityFromStr,\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport * as core from '@opentelemetry/core';\nimport * as web from '@opentelemetry/sdk-trace-web';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ATTR_HTTP_STATUS_CODE,\n ATTR_HTTP_HOST,\n ATTR_HTTP_USER_AGENT,\n ATTR_HTTP_SCHEME,\n ATTR_HTTP_URL,\n ATTR_HTTP_METHOD,\n ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n ATTR_HTTP_REQUEST_BODY_SIZE,\n} from './semconv';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n} from '@opentelemetry/semantic-conventions';\nimport { FetchError, FetchResponse, SpanData } from './types';\nimport {\n getFetchBodyLength,\n normalizeHttpRequestMethod,\n serverPortFromUrl,\n} from './utils';\nimport { VERSION } from './version';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nconst hasBrowserPerformanceAPI = typeof PerformanceObserver !== 'undefined';\n\nexport interface FetchCustomAttributeFunction {\n (\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ): void;\n}\n\nexport interface FetchRequestHookFunction {\n (span: Span, request: Request | RequestInit): void;\n}\n\n/**\n * FetchPlugin Config\n */\nexport interface FetchInstrumentationConfig extends InstrumentationConfig {\n // the number of timing resources is limited, after the limit\n // (chrome 250, safari 150) the information is not collected anymore\n // the only way to prevent that is to regularly clean the resources\n // whenever it is possible, this is needed only when PerformanceObserver\n // is not available\n clearTimingResources?: boolean;\n // urls which should include trace headers when origin doesn't match\n propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n /** Function for adding custom attributes or headers before the request is handled */\n requestHook?: FetchRequestHookFunction;\n // Ignore adding network events as span events\n ignoreNetworkEvents?: boolean;\n /** Measure outgoing request size */\n measureRequestSize?: boolean;\n /** Select the HTTP semantic conventions version(s) used. */\n semconvStabilityOptIn?: string;\n}\n\n/**\n * This class represents a fetch plugin for auto instrumentation\n */\nexport class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {\n readonly component: string = 'fetch';\n readonly version: string = VERSION;\n moduleName = this.component;\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _tasksCount = 0;\n\n private _semconvStability: SemconvStability;\n\n constructor(config: FetchInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-fetch', VERSION, config);\n this._semconvStability = semconvStabilityFromStr(\n 'http',\n config?.semconvStabilityOptIn\n );\n }\n\n init(): void {}\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n */\n private _addChildSpan(\n span: Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n const childSpan = this.tracer.startSpan(\n 'CORS Preflight',\n {\n startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],\n },\n trace.setSpan(context.active(), span)\n );\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n web.addSpanNetworkEvents(\n childSpan,\n corsPreFlightRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n childSpan.end(\n corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]\n );\n }\n\n /**\n * Adds more attributes to span just before ending it\n * @param span\n * @param response\n */\n private _addFinalSpanAttributes(span: Span, response: FetchResponse): void {\n const parsedUrl = web.parseUrl(response.url);\n\n if (this._semconvStability & SemconvStability.OLD) {\n span.setAttribute(ATTR_HTTP_STATUS_CODE, response.status);\n if (response.statusText != null) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, response.statusText);\n }\n span.setAttribute(ATTR_HTTP_HOST, parsedUrl.host);\n span.setAttribute(ATTR_HTTP_SCHEME, parsedUrl.protocol.replace(':', ''));\n if (typeof navigator !== 'undefined') {\n span.setAttribute(ATTR_HTTP_USER_AGENT, navigator.userAgent);\n }\n }\n\n if (this._semconvStability & SemconvStability.STABLE) {\n span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n // TODO: Set server.{address,port} at span creation for sampling decisions\n // (a \"SHOULD\" requirement in semconv).\n span.setAttribute(ATTR_SERVER_ADDRESS, parsedUrl.hostname);\n const serverPort = serverPortFromUrl(parsedUrl);\n if (serverPort) {\n span.setAttribute(ATTR_SERVER_PORT, serverPort);\n }\n }\n }\n\n /**\n * Add headers\n * @param options\n * @param spanUrl\n */\n private _addHeaders(options: Request | RequestInit, spanUrl: string): void {\n if (\n !web.shouldPropagateTraceHeaders(\n spanUrl,\n this.getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n propagation.inject(context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n\n if (options instanceof Request) {\n // This mutates `Request.headers` in-place, because it is read-only\n // (per https://developer.mozilla.org/en-US/docs/Web/API/Request/headers),\n // so we cannot (easily) replace it.\n propagation.inject(context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else {\n // Otherwise, create a new Headers to avoid mutating the caller's\n // possibly re-used headers.\n const headers = new Headers(options.headers);\n propagation.inject(context.active(), headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n options.headers = headers;\n }\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link FetchPluginConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {\n performance.clearResourceTimings();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Creates a new span\n * @param url\n * @param options\n */\n private _createSpan(\n url: string,\n options: Partial<Request | RequestInit> = {}\n ): Span | undefined {\n if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n\n let name = '';\n const attributes = {} as Attributes;\n if (this._semconvStability & SemconvStability.OLD) {\n const method = (options.method || 'GET').toUpperCase();\n name = `HTTP ${method}`;\n attributes[AttributeNames.COMPONENT] = this.moduleName;\n attributes[ATTR_HTTP_METHOD] = method;\n attributes[ATTR_HTTP_URL] = url;\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n const origMethod = options.method;\n const normMethod = normalizeHttpRequestMethod(options.method || 'GET');\n if (!name) {\n // The \"old\" span name wins if emitting both old and stable semconv\n // ('http/dup').\n name = normMethod;\n }\n attributes[ATTR_HTTP_REQUEST_METHOD] = normMethod;\n if (normMethod !== origMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;\n }\n attributes[ATTR_URL_FULL] = url;\n }\n\n return this.tracer.startSpan(name, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n * @param resourcesObserver\n * @param endTime\n */\n private _findResourceAndAddNetworkEvents(\n span: Span,\n resourcesObserver: SpanData,\n endTime: HrTime\n ): void {\n let resources: PerformanceResourceTiming[] = resourcesObserver.entries;\n if (!resources.length) {\n if (!performance.getEntriesByType) {\n return;\n }\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n const resource = web.getResource(\n resourcesObserver.spanUrl,\n resourcesObserver.startTime,\n endTime,\n resources,\n this._usedResources,\n 'fetch'\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n web.addSpanNetworkEvents(\n span,\n mainRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n }\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming): void {\n this._usedResources.add(resource);\n }\n\n /**\n * Finish span, add attributes, network events etc.\n * @param span\n * @param spanData\n * @param response\n */\n private _endSpan(span: Span, spanData: SpanData, response: FetchResponse) {\n const endTime = core.millisToHrTime(Date.now());\n const performanceEndTime = core.hrTime();\n this._addFinalSpanAttributes(span, response);\n\n if (this._semconvStability & SemconvStability.STABLE) {\n // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md#status\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.setAttribute(ATTR_ERROR_TYPE, String(response.status));\n }\n }\n\n setTimeout(() => {\n spanData.observer?.disconnect();\n this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);\n this._tasksCount--;\n this._clearResources();\n span.end(endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n /**\n * Patches the constructor of fetch\n */\n private _patchConstructor(): (original: typeof fetch) => typeof fetch {\n return original => {\n const plugin = this;\n const readOnlyProps = new Set(['url', 'type', 'redirected']);\n function createResponseProxy(\n target: Response,\n originalResponse: Response\n ): Response {\n return new Proxy(target, {\n get(t, prop, _receiver) {\n if (typeof prop === 'string' && readOnlyProps.has(prop)) {\n return Reflect.get(originalResponse, prop);\n }\n if (prop === 'clone') {\n return function clone() {\n return createResponseProxy(t.clone(), originalResponse);\n };\n }\n // Use target as receiver so getters (e.g. headers) run with correct this and avoid \"Illegal invocation\"\n const value = Reflect.get(t, prop, t);\n return typeof value === 'function' ? value.bind(t) : value;\n },\n }) as Response;\n }\n\n return function patchConstructor(\n this: typeof globalThis,\n ...args: Parameters<typeof fetch>\n ): Promise<Response> {\n const self = this;\n const url = web.parseUrl(\n args[0] instanceof Request ? args[0].url : String(args[0])\n ).href;\n\n const options = args[0] instanceof Request ? args[0] : args[1] || {};\n const createdSpan = plugin._createSpan(url, options);\n if (!createdSpan) {\n return original.apply(this, args);\n }\n const spanData = plugin._prepareSpanData(url);\n\n if (plugin.getConfig().measureRequestSize) {\n getFetchBodyLength(...args)\n .then(bodyLength => {\n if (!bodyLength) return;\n if (plugin._semconvStability & SemconvStability.OLD) {\n createdSpan.setAttribute(\n ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n bodyLength\n );\n }\n if (plugin._semconvStability & SemconvStability.STABLE) {\n createdSpan.setAttribute(\n ATTR_HTTP_REQUEST_BODY_SIZE,\n bodyLength\n );\n }\n })\n .catch(error => {\n plugin._diag.warn('getFetchBodyLength', error);\n });\n }\n\n function endSpanOnError(span: Span, error: FetchError) {\n plugin._applyAttributesAfterFetch(span, options, error);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n statusText: error.message,\n url,\n });\n }\n\n function endSpanOnSuccess(span: Span, response: Response) {\n plugin._applyAttributesAfterFetch(span, options, response);\n if (response.status >= 200 && response.status < 400) {\n plugin._endSpan(span, spanData, response);\n } else {\n plugin._endSpan(span, spanData, {\n status: response.status,\n statusText: response.statusText,\n url,\n });\n }\n }\n\n function withCancelPropagation(\n body: ReadableStream<Uint8Array> | null,\n readerClone: ReadableStreamDefaultReader<Uint8Array>\n ): ReadableStream<Uint8Array> | null {\n if (!body) return null;\n\n const reader = body.getReader();\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const { value, done } = await reader.read();\n if (done) {\n reader.releaseLock();\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (err) {\n controller.error(err);\n reader.cancel(err).catch(_ => {});\n\n try {\n reader.releaseLock();\n } catch {\n // Spec reference:\n // https://streams.spec.whatwg.org/#default-reader-release-lock\n //\n // releaseLock() only throws if called on an invalid reader\n // (i.e. reader.[[stream]] is undefined, meaning the lock is already released\n // or the reader was never associated). In normal use this cannot happen.\n // This catch is defensive only.\n }\n }\n },\n cancel(reason) {\n readerClone.cancel(reason).catch(_ => {});\n return reader.cancel(reason);\n },\n });\n }\n\n function onSuccess(\n span: Span,\n resolve: (value: Response | PromiseLike<Response>) => void,\n response: Response\n ): void {\n let proxiedResponse: Response | null = null;\n\n try {\n // TODO: Switch to a consumer-driven model and drop `resClone`.\n // Keeping eager consumption here to preserve current behavior and avoid breaking existing tests.\n // Context: discussion in PR #5894 → https://github.com/open-telemetry/opentelemetry-js/pull/5894\n const resClone = response.clone();\n const body = resClone.body;\n if (body) {\n const reader = body.getReader();\n const isNullBodyStatus =\n // 101 responses and protocol upgrading is handled internally by the browser\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304;\n const wrappedBody = isNullBodyStatus\n ? null\n : withCancelPropagation(response.body, reader);\n\n const newResponse = new Response(wrappedBody, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n\n // Response url, type, and redirected are read-only properties that can't be set via constructor\n // Use a Proxy to forward them from the original response and maintain the wrapped body\n proxiedResponse = createResponseProxy(newResponse, response);\n\n const read = (): void => {\n reader.read().then(\n ({ done }) => {\n if (done) {\n endSpanOnSuccess(span, response);\n } else {\n read();\n }\n },\n error => {\n endSpanOnError(span, error);\n }\n );\n };\n read();\n } else {\n // some older browsers don't have .body implemented\n endSpanOnSuccess(span, response);\n }\n } finally {\n resolve(proxiedResponse ?? response);\n }\n }\n\n function onError(\n span: Span,\n reject: (reason?: unknown) => void,\n error: FetchError\n ) {\n try {\n endSpanOnError(span, error);\n } finally {\n reject(error);\n }\n }\n\n return new Promise((resolve, reject) => {\n return context.with(\n trace.setSpan(context.active(), createdSpan),\n () => {\n // Call request hook before injection so hooks cannot tamper with propagation headers.\n // Also, this means the hook will see `options.headers` in the same type as passed in,\n // rather than as a `Headers` instance set by `_addHeaders()`.\n plugin._callRequestHook(createdSpan, options);\n plugin._addHeaders(options, url);\n plugin._tasksCount++;\n\n return original\n .apply(\n self,\n options instanceof Request ? [options] : [url, options]\n )\n .then(\n onSuccess.bind(self, createdSpan, resolve),\n onError.bind(self, createdSpan, reject)\n );\n }\n );\n });\n };\n };\n }\n\n private _applyAttributesAfterFetch(\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) {\n const applyCustomAttributesOnSpan =\n this.getConfig().applyCustomAttributesOnSpan;\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, request, result),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n private _callRequestHook(span: Span, request: Request | RequestInit) {\n const requestHook = this.getConfig().requestHook;\n if (requestHook) {\n safeExecuteInTheMiddle(\n () => requestHook(span, request),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('requestHook', error);\n },\n true\n );\n }\n }\n\n /**\n * Prepares a span data - needed later for matching appropriate network\n * resources\n * @param spanUrl\n */\n private _prepareSpanData(spanUrl: string): SpanData {\n const startTime = core.hrTime();\n const entries: PerformanceResourceTiming[] = [];\n if (typeof PerformanceObserver !== 'function') {\n return { entries, startTime, spanUrl };\n }\n\n const observer = new PerformanceObserver(list => {\n const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];\n perfObsEntries.forEach(entry => {\n if (entry.initiatorType === 'fetch' && entry.name === spanUrl) {\n entries.push(entry);\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n return { entries, observer, startTime, spanUrl };\n }\n\n /**\n * implements enable function\n */\n override enable(): void {\n if (!hasBrowserPerformanceAPI) {\n this._diag.warn(\n 'this instrumentation is intended for web usage only, it does not instrument server-side fetch()'\n );\n return;\n }\n if (isWrapped(fetch)) {\n this._unwrap(globalThis, 'fetch');\n this._diag.debug('removing previous patch for constructor');\n }\n this._wrap(globalThis, 'fetch', this._patchConstructor());\n }\n\n /**\n * implements unpatch function\n */\n override disable(): void {\n if (!hasBrowserPerformanceAPI) {\n return;\n }\n this._unwrap(globalThis, 'fetch');\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.57.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-long-task';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// PerformanceLongTaskTiming is experimental and may change in future versions.\n// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming\n/* eslint-disable baseline-js/use-baseline */\n\nimport { hrTime } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport type {\n PerformanceLongTaskTiming,\n LongtaskInstrumentationConfig,\n} from './types';\n\nconst LONGTASK_PERFORMANCE_TYPE = 'longtask';\n\nexport class LongTaskInstrumentation extends InstrumentationBase<LongtaskInstrumentationConfig> {\n readonly version: string = PACKAGE_VERSION;\n\n private _observer?: PerformanceObserver;\n\n constructor(config: LongtaskInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {}\n\n private isSupported() {\n if (\n typeof PerformanceObserver === 'undefined' ||\n !PerformanceObserver.supportedEntryTypes\n ) {\n return false;\n }\n\n return PerformanceObserver.supportedEntryTypes.includes(\n LONGTASK_PERFORMANCE_TYPE\n );\n }\n\n private _createSpanFromEntry(entry: PerformanceLongTaskTiming) {\n const span = this.tracer.startSpan(LONGTASK_PERFORMANCE_TYPE, {\n startTime: hrTime(entry.startTime),\n });\n const { observerCallback } = this.getConfig();\n if (observerCallback) {\n try {\n observerCallback(span, { longtaskEntry: entry });\n } catch (err) {\n diag.error('longtask instrumentation: observer callback failed', err);\n }\n }\n span.setAttribute('longtask.name', entry.name);\n span.setAttribute('longtask.entry_type', entry.entryType);\n span.setAttribute('longtask.duration', entry.duration);\n\n if (Array.isArray(entry.attribution)) {\n entry.attribution.forEach((attribution, index) => {\n const prefix =\n entry.attribution.length > 1\n ? `longtask.attribution[${index}]`\n : 'longtask.attribution';\n span.setAttribute(`${prefix}.name`, attribution.name);\n span.setAttribute(`${prefix}.entry_type`, attribution.entryType);\n span.setAttribute(`${prefix}.start_time`, attribution.startTime);\n span.setAttribute(`${prefix}.duration`, attribution.duration);\n span.setAttribute(\n `${prefix}.container_type`,\n attribution.containerType\n );\n span.setAttribute(`${prefix}.container_src`, attribution.containerSrc);\n span.setAttribute(`${prefix}.container_id`, attribution.containerId);\n span.setAttribute(\n `${prefix}.container_name`,\n attribution.containerName\n );\n });\n }\n\n span.end(hrTime(entry.startTime + entry.duration));\n }\n\n override enable() {\n if (!this.isSupported()) {\n this._diag.debug('Environment not supported');\n return;\n }\n\n if (this._observer) {\n // Already enabled\n return;\n }\n\n this._observer = new PerformanceObserver(list => {\n list\n .getEntries()\n .forEach(entry =>\n this._createSpanFromEntry(entry as PerformanceLongTaskTiming)\n );\n });\n this._observer.observe({\n type: LONGTASK_PERFORMANCE_TYPE,\n buffered: true,\n });\n }\n\n override disable() {\n if (!this._observer) {\n return;\n }\n\n this._observer.disconnect();\n this._observer = undefined;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum AttributeNames {\n EVENT_TYPE = 'event_type',\n TARGET_ELEMENT = 'target_element',\n TARGET_XPATH = 'target_xpath',\n HTTP_URL = 'http.url',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.57.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-user-interaction';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/// <reference types=\"zone.js\" />\n\nimport { isWrapped, InstrumentationBase } from '@opentelemetry/instrumentation';\n\nimport * as api from '@opentelemetry/api';\nimport { hrTime } from '@opentelemetry/core';\nimport { getElementXPath } from '@opentelemetry/sdk-trace-web';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n EventName,\n ShouldPreventSpanCreation,\n UserInteractionInstrumentationConfig,\n} from './types';\nimport {\n AsyncTask,\n RunTaskFunction,\n SpanData,\n WindowWithZone,\n ZoneTypeWithPrototype,\n} from './internal-types';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\nconst ZONE_CONTEXT_KEY = 'OT_ZONE_CONTEXT';\nconst EVENT_NAVIGATION_NAME = 'Navigation:';\nconst DEFAULT_EVENT_NAMES: EventName[] = ['click'];\n\nfunction defaultShouldPreventSpanCreation() {\n return false;\n}\n\n/**\n * This class represents a UserInteraction plugin for auto instrumentation.\n * If zone.js is available then it patches the zone otherwise it patches\n * addEventListener of HTMLElement\n */\nexport class UserInteractionInstrumentation extends InstrumentationBase<UserInteractionInstrumentationConfig> {\n readonly version = PACKAGE_VERSION;\n readonly moduleName: string = 'user-interaction';\n private _spansData = new WeakMap<api.Span, SpanData>();\n declare private _zonePatched?: boolean;\n // for addEventListener/removeEventListener state\n private _wrappedListeners = new WeakMap<\n Function | EventListenerObject,\n Map<string, Map<HTMLElement, Function>>\n >();\n // for event bubbling\n private _eventsSpanMap: WeakMap<Event, api.Span> = new WeakMap<\n Event,\n api.Span\n >();\n private _eventNames: Set<EventName>;\n private _shouldPreventSpanCreation: ShouldPreventSpanCreation;\n\n constructor(config: UserInteractionInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n this._eventNames = new Set(config?.eventNames ?? DEFAULT_EVENT_NAMES);\n this._shouldPreventSpanCreation =\n typeof config?.shouldPreventSpanCreation === 'function'\n ? config.shouldPreventSpanCreation\n : defaultShouldPreventSpanCreation;\n }\n\n init() {}\n\n /**\n * This will check if last task was timeout and will save the time to\n * fix the user interaction when nothing happens\n * This timeout comes from xhr plugin which is needed to collect information\n * about last xhr main request from observer\n * @param task\n * @param span\n */\n private _checkForTimeout(task: AsyncTask, span: api.Span) {\n const spanData = this._spansData.get(span);\n if (spanData) {\n if (task.source === 'setTimeout') {\n spanData.hrTimeLastTimeout = hrTime();\n } else if (\n task.source !== 'Promise.then' &&\n task.source !== 'setTimeout'\n ) {\n spanData.hrTimeLastTimeout = undefined;\n }\n }\n }\n\n /**\n * Controls whether or not to create a span, based on the event type.\n */\n protected _allowEventName(eventName: EventName): boolean {\n return this._eventNames.has(eventName);\n }\n\n /**\n * Creates a new span\n * @param element\n * @param eventName\n * @param parentSpan\n */\n private _createSpan(\n element: EventTarget | null | undefined,\n eventName: EventName,\n parentSpan?: api.Span\n ): api.Span | undefined {\n if (!(element instanceof HTMLElement)) {\n return undefined;\n }\n if (!element.getAttribute) {\n return undefined;\n }\n if (element.hasAttribute('disabled')) {\n return undefined;\n }\n if (!this._allowEventName(eventName)) {\n return undefined;\n }\n const xpath = getElementXPath(element, true);\n try {\n const span = this.tracer.startSpan(\n eventName,\n {\n attributes: {\n [AttributeNames.EVENT_TYPE]: eventName,\n [AttributeNames.TARGET_ELEMENT]: element.tagName,\n [AttributeNames.TARGET_XPATH]: xpath,\n [AttributeNames.HTTP_URL]: window.location.href,\n },\n },\n parentSpan\n ? api.trace.setSpan(api.context.active(), parentSpan)\n : undefined\n );\n\n if (this._shouldPreventSpanCreation(eventName, element, span) === true) {\n return undefined;\n }\n\n this._spansData.set(span, {\n taskCount: 0,\n });\n\n return span;\n } catch (e) {\n this._diag.error('failed to start create new user interaction span', e);\n }\n return undefined;\n }\n\n /**\n * Decrement number of tasks that left in zone,\n * This is needed to be able to end span when no more tasks left\n * @param span\n */\n private _decrementTask(span: api.Span) {\n const spanData = this._spansData.get(span);\n if (spanData) {\n spanData.taskCount--;\n if (spanData.taskCount === 0) {\n this._tryToEndSpan(span, spanData.hrTimeLastTimeout);\n }\n }\n }\n\n /**\n * Return the current span\n * @param zone\n * @private\n */\n private _getCurrentSpan(zone: Zone): api.Span | undefined {\n const context: api.Context | undefined = zone.get(ZONE_CONTEXT_KEY);\n if (context) {\n return api.trace.getSpan(context);\n }\n return context;\n }\n\n /**\n * Increment number of tasks that are run within the same zone.\n * This is needed to be able to end span when no more tasks left\n * @param span\n */\n private _incrementTask(span: api.Span) {\n const spanData = this._spansData.get(span);\n if (spanData) {\n spanData.taskCount++;\n }\n }\n\n /**\n * Returns true iff we should use the patched callback; false if it's already been patched\n */\n private addPatchedListener(\n on: HTMLElement,\n type: string,\n listener: Function | EventListenerObject,\n wrappedListener: Function\n ): boolean {\n let listener2Type = this._wrappedListeners.get(listener);\n if (!listener2Type) {\n listener2Type = new Map();\n this._wrappedListeners.set(listener, listener2Type);\n }\n let element2patched = listener2Type.get(type);\n if (!element2patched) {\n element2patched = new Map();\n listener2Type.set(type, element2patched);\n }\n if (element2patched.has(on)) {\n return false;\n }\n element2patched.set(on, wrappedListener);\n return true;\n }\n\n /**\n * Returns the patched version of the callback (or undefined)\n */\n private removePatchedListener(\n on: HTMLElement,\n type: string,\n listener: Function | EventListenerObject\n ): Function | undefined {\n const listener2Type = this._wrappedListeners.get(listener);\n if (!listener2Type) {\n return undefined;\n }\n const element2patched = listener2Type.get(type);\n if (!element2patched) {\n return undefined;\n }\n const patched = element2patched.get(on);\n if (patched) {\n element2patched.delete(on);\n if (element2patched.size === 0) {\n listener2Type.delete(type);\n if (listener2Type.size === 0) {\n this._wrappedListeners.delete(listener);\n }\n }\n }\n return patched;\n }\n\n // utility method to deal with the Function|EventListener nature of addEventListener\n private _invokeListener(\n listener: Function | EventListenerObject,\n target: any,\n args: any[]\n ): any {\n if (typeof listener === 'function') {\n return listener.apply(target, args);\n } else {\n return listener.handleEvent(args[0]);\n }\n }\n\n /**\n * This patches the addEventListener of HTMLElement to be able to\n * auto instrument the click events\n * This is done when zone is not available\n */\n private _patchAddEventListener() {\n const plugin = this;\n return (original: EventTarget['addEventListener']) => {\n return function addEventListenerPatched(\n this: HTMLElement,\n type: keyof HTMLElementEventMap,\n listener: EventListenerOrEventListenerObject | null,\n useCapture?: boolean | AddEventListenerOptions\n ) {\n // Forward calls with listener = null\n if (!listener) {\n return original.call(this, type, listener, useCapture);\n }\n\n // filter out null (typeof null === 'object')\n const once =\n useCapture && typeof useCapture === 'object' && useCapture.once;\n const patchedListener = function (this: HTMLElement, ...args: any[]) {\n let parentSpan: api.Span | undefined;\n const event: Event | undefined = args[0];\n const target = event?.target;\n if (event) {\n parentSpan = plugin._eventsSpanMap.get(event);\n }\n if (once) {\n plugin.removePatchedListener(this, type, listener);\n }\n const span = plugin._createSpan(target, type, parentSpan);\n if (span) {\n if (event) {\n plugin._eventsSpanMap.set(event, span);\n }\n return api.context.with(\n api.trace.setSpan(api.context.active(), span),\n () => {\n const result = plugin._invokeListener(listener, this, args);\n // no zone so end span immediately\n span.end();\n return result;\n }\n );\n } else {\n return plugin._invokeListener(listener, this, args);\n }\n };\n if (plugin.addPatchedListener(this, type, listener, patchedListener)) {\n return original.call(this, type, patchedListener, useCapture);\n }\n };\n };\n }\n\n /**\n * This patches the removeEventListener of HTMLElement to handle the fact that\n * we patched the original callbacks\n * This is done when zone is not available\n */\n private _patchRemoveEventListener() {\n const plugin = this;\n return (original: Function) => {\n return function removeEventListenerPatched(\n this: HTMLElement,\n type: any,\n listener: any,\n useCapture: any\n ) {\n const wrappedListener = plugin.removePatchedListener(\n this,\n type,\n listener\n );\n if (wrappedListener) {\n return original.call(this, type, wrappedListener, useCapture);\n } else {\n return original.call(this, type, listener, useCapture);\n }\n };\n };\n }\n\n /**\n * Most browser provide event listener api via EventTarget in prototype chain.\n * Exception to this is IE 11 which has it on the prototypes closest to EventTarget:\n *\n * * - has addEventListener in IE\n * ** - has addEventListener in all other browsers\n * ! - missing in IE\n *\n * HTMLElement -> Element -> Node * -> EventTarget **! -> Object\n * Document -> Node * -> EventTarget **! -> Object\n * Window * -> WindowProperties ! -> EventTarget **! -> Object\n */\n private _getPatchableEventTargets(): EventTarget[] {\n return window.EventTarget\n ? [EventTarget.prototype]\n : [Node.prototype, Window.prototype];\n }\n\n /**\n * Patches the history api\n */\n _patchHistoryApi() {\n this._unpatchHistoryApi();\n\n this._wrap(history, 'replaceState', this._patchHistoryMethod());\n this._wrap(history, 'pushState', this._patchHistoryMethod());\n this._wrap(history, 'back', this._patchHistoryMethod());\n this._wrap(history, 'forward', this._patchHistoryMethod());\n this._wrap(history, 'go', this._patchHistoryMethod());\n }\n\n /**\n * Patches the certain history api method\n */\n _patchHistoryMethod() {\n const plugin = this;\n return (original: any) => {\n return function patchHistoryMethod(this: History, ...args: unknown[]) {\n const url = `${location.pathname}${location.hash}${location.search}`;\n const result = original.apply(this, args);\n const urlAfter = `${location.pathname}${location.hash}${location.search}`;\n if (url !== urlAfter) {\n plugin._updateInteractionName(urlAfter);\n }\n return result;\n };\n };\n }\n\n /**\n * unpatch the history api methods\n */\n _unpatchHistoryApi() {\n if (isWrapped(history.replaceState)) this._unwrap(history, 'replaceState');\n if (isWrapped(history.pushState)) this._unwrap(history, 'pushState');\n if (isWrapped(history.back)) this._unwrap(history, 'back');\n if (isWrapped(history.forward)) this._unwrap(history, 'forward');\n if (isWrapped(history.go)) this._unwrap(history, 'go');\n }\n\n /**\n * Updates interaction span name\n * @param url\n */\n _updateInteractionName(url: string) {\n const span: api.Span | undefined = api.trace.getSpan(api.context.active());\n if (span && typeof span.updateName === 'function') {\n span.updateName(`${EVENT_NAVIGATION_NAME} ${url}`);\n }\n }\n\n /**\n * Patches zone cancel task - this is done to be able to correctly\n * decrement the number of remaining tasks\n */\n private _patchZoneCancelTask() {\n const plugin = this;\n return (original: any) => {\n return function patchCancelTask<T extends Task>(\n this: Zone,\n task: AsyncTask\n ) {\n const currentZone = Zone.current;\n const currentSpan = plugin._getCurrentSpan(currentZone);\n if (currentSpan && plugin._shouldCountTask(task, currentZone)) {\n plugin._decrementTask(currentSpan);\n }\n return original.call(this, task) as T;\n };\n };\n }\n\n /**\n * Patches zone schedule task - this is done to be able to correctly\n * increment the number of tasks running within current zone but also to\n * save time in case of timeout running from xhr plugin when waiting for\n * main request from PerformanceResourceTiming\n */\n private _patchZoneScheduleTask() {\n const plugin = this;\n return (original: any) => {\n return function patchScheduleTask<T extends Task>(\n this: Zone,\n task: AsyncTask\n ) {\n const currentZone = Zone.current;\n const currentSpan = plugin._getCurrentSpan(currentZone);\n if (currentSpan && plugin._shouldCountTask(task, currentZone)) {\n plugin._incrementTask(currentSpan);\n plugin._checkForTimeout(task, currentSpan);\n }\n return original.call(this, task) as T;\n };\n };\n }\n\n /**\n * Patches zone run task - this is done to be able to create a span when\n * user interaction starts\n * @private\n */\n private _patchZoneRunTask() {\n const plugin = this;\n return (original: RunTaskFunction): RunTaskFunction => {\n return function patchRunTask(\n this: Zone,\n task: AsyncTask,\n applyThis?: any,\n applyArgs?: any\n ): Zone {\n const event =\n Array.isArray(applyArgs) && applyArgs[0] instanceof Event\n ? applyArgs[0]\n : undefined;\n const target = event?.target;\n let span: api.Span | undefined;\n const activeZone = this;\n if (target) {\n span = plugin._createSpan(target, task.eventName);\n if (span) {\n plugin._incrementTask(span);\n return activeZone.run(() => {\n try {\n return api.context.with(\n api.trace.setSpan(api.context.active(), span!),\n () => {\n const currentZone = Zone.current;\n task._zone = currentZone;\n return original.call(\n currentZone,\n task,\n applyThis,\n applyArgs\n );\n }\n );\n } finally {\n plugin._decrementTask(span as api.Span);\n }\n });\n }\n } else {\n span = plugin._getCurrentSpan(activeZone);\n }\n\n try {\n return original.call(activeZone, task, applyThis, applyArgs);\n } finally {\n if (span && plugin._shouldCountTask(task, activeZone)) {\n plugin._decrementTask(span);\n }\n }\n };\n };\n }\n\n /**\n * Decides if task should be counted.\n * @param task\n * @param currentZone\n * @private\n */\n private _shouldCountTask(task: AsyncTask, currentZone: Zone): boolean {\n if (task._zone) {\n currentZone = task._zone;\n }\n if (!currentZone || !task.data || task.data.isPeriodic) {\n return false;\n }\n const currentSpan = this._getCurrentSpan(currentZone);\n if (!currentSpan) {\n return false;\n }\n if (!this._spansData.get(currentSpan)) {\n return false;\n }\n return task.type === 'macroTask' || task.type === 'microTask';\n }\n\n /**\n * Will try to end span when such span still exists.\n * @param span\n * @param endTime\n * @private\n */\n private _tryToEndSpan(span: api.Span, endTime?: api.HrTime) {\n if (span) {\n const spanData = this._spansData.get(span);\n if (spanData) {\n span.end(endTime);\n this._spansData.delete(span);\n }\n }\n }\n\n /**\n * implements enable function\n */\n override enable() {\n const ZoneWithPrototype = this._getZoneWithPrototype();\n this._diag.debug(\n 'applying patch to',\n this.moduleName,\n this.version,\n 'zone:',\n !!ZoneWithPrototype\n );\n if (ZoneWithPrototype) {\n if (isWrapped(ZoneWithPrototype.prototype.runTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'runTask');\n this._diag.debug('removing previous patch from method runTask');\n }\n if (isWrapped(ZoneWithPrototype.prototype.scheduleTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'scheduleTask');\n this._diag.debug('removing previous patch from method scheduleTask');\n }\n if (isWrapped(ZoneWithPrototype.prototype.cancelTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'cancelTask');\n this._diag.debug('removing previous patch from method cancelTask');\n }\n\n this._zonePatched = true;\n this._wrap(\n ZoneWithPrototype.prototype,\n 'runTask',\n this._patchZoneRunTask()\n );\n this._wrap(\n ZoneWithPrototype.prototype,\n 'scheduleTask',\n this._patchZoneScheduleTask()\n );\n this._wrap(\n ZoneWithPrototype.prototype,\n 'cancelTask',\n this._patchZoneCancelTask()\n );\n } else {\n this._zonePatched = false;\n const targets = this._getPatchableEventTargets();\n targets.forEach(target => {\n if (isWrapped(target.addEventListener)) {\n this._unwrap(target, 'addEventListener');\n this._diag.debug(\n 'removing previous patch from method addEventListener'\n );\n }\n if (isWrapped(target.removeEventListener)) {\n this._unwrap(target, 'removeEventListener');\n this._diag.debug(\n 'removing previous patch from method removeEventListener'\n );\n }\n this._wrap(target, 'addEventListener', this._patchAddEventListener());\n this._wrap(\n target,\n 'removeEventListener',\n this._patchRemoveEventListener()\n );\n });\n }\n\n this._patchHistoryApi();\n }\n\n /**\n * implements unpatch function\n */\n override disable() {\n const ZoneWithPrototype = this._getZoneWithPrototype();\n this._diag.debug(\n 'removing patch from',\n this.moduleName,\n this.version,\n 'zone:',\n !!ZoneWithPrototype\n );\n if (ZoneWithPrototype && this._zonePatched) {\n if (isWrapped(ZoneWithPrototype.prototype.runTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'runTask');\n }\n if (isWrapped(ZoneWithPrototype.prototype.scheduleTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'scheduleTask');\n }\n if (isWrapped(ZoneWithPrototype.prototype.cancelTask)) {\n this._unwrap(ZoneWithPrototype.prototype, 'cancelTask');\n }\n } else {\n const targets = this._getPatchableEventTargets();\n targets.forEach(target => {\n if (isWrapped(target.addEventListener)) {\n this._unwrap(target, 'addEventListener');\n }\n if (isWrapped(target.removeEventListener)) {\n this._unwrap(target, 'removeEventListener');\n }\n });\n }\n this._unpatchHistoryApi();\n }\n\n /**\n * returns Zone\n */\n private _getZoneWithPrototype(): ZoneTypeWithPrototype | undefined {\n const _window: WindowWithZone = window as unknown as WindowWithZone;\n return _window.Zone;\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 * Deprecated, use one of `server.address`, `client.address` or `http.request.header.host` instead, depending on the usage.\n *\n * @example www.example.org\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by one of `server.address`, `client.address` or `http.request.header.host`, depending on the usage.\n */\nexport const ATTR_HTTP_HOST = 'http.host' as const;\n\n/**\n * Deprecated, use `http.request.method` instead.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.request.method`.\n */\nexport const ATTR_HTTP_METHOD = 'http.method' as const;\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HTTP_REQUEST_BODY_SIZE = 'http.request.body.size' as const;\n\n/**\n * Deprecated, use `http.request.body.size` instead.\n *\n * @example 5493\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.request.body.size`.\n */\nexport const ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED =\n 'http.request_content_length_uncompressed' as const;\n\n/**\n * Deprecated, use `http.response.header.<key>` instead.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.header.<key>`.\n */\nexport const ATTR_HTTP_RESPONSE_CONTENT_LENGTH =\n 'http.response_content_length' as const;\n\n/**\n * Deprecated, use `url.scheme` instead.\n *\n * @example http\n * @example https\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `url.scheme` instead.\n */\nexport const ATTR_HTTP_SCHEME = 'http.scheme' as const;\n\n/**\n * Deprecated, use `http.response.status_code` instead.\n *\n * @example 200\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `http.response.status_code`.\n */\nexport const ATTR_HTTP_STATUS_CODE = 'http.status_code' as const;\n\n/**\n * Deprecated, use `url.full` instead.\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `url.full`.\n */\nexport const ATTR_HTTP_URL = 'http.url' as const;\n\n/**\n * Deprecated, use `user_agent.original` instead.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n *\n * @deprecated Replaced by `user_agent.original`.\n */\nexport const ATTR_HTTP_USER_AGENT = 'http.user_agent' as const;\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport enum EventNames {\n METHOD_OPEN = 'open',\n METHOD_SEND = 'send',\n EVENT_ABORT = 'abort',\n EVENT_ERROR = 'error',\n EVENT_LOAD = 'loaded',\n EVENT_TIMEOUT = 'timeout',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Much of the logic here overlaps with the same utils file in opentelemetry-instrumentation-fetch\n// These may be unified in the future.\n\nimport * as api from '@opentelemetry/api';\nimport { getStringListFromEnv } from '@opentelemetry/core';\nimport { URLLike } from '@opentelemetry/sdk-trace-web';\n\nconst DIAG_LOGGER = api.diag.createComponentLogger({\n namespace:\n '@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils',\n});\n\nfunction isDocument(value: unknown): value is Document {\n return typeof Document !== 'undefined' && value instanceof Document;\n}\n\n/**\n * Helper function to determine payload content length for XHR requests\n * @param body\n * @returns content length\n */\nexport function getXHRBodyLength(\n body: Document | XMLHttpRequestBodyInit\n): number | undefined {\n if (isDocument(body)) {\n return new XMLSerializer().serializeToString(document).length;\n }\n\n // XMLHttpRequestBodyInit expands to the following:\n if (typeof body === 'string') {\n return getByteLength(body);\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof FormData) {\n return getFormDataSize(body);\n }\n\n if (body instanceof URLSearchParams) {\n return getByteLength(body.toString());\n }\n\n // ArrayBuffer | ArrayBufferView\n if (body.byteLength !== undefined) {\n return body.byteLength;\n }\n\n DIAG_LOGGER.warn('unknown body type');\n return undefined;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\nfunction getByteLength(s: string): number {\n return TEXT_ENCODER.encode(s).byteLength;\n}\n\nfunction getFormDataSize(formData: FormData): number {\n let size = 0;\n for (const [key, value] of formData.entries()) {\n size += key.length;\n if (value instanceof Blob) {\n size += value.size;\n } else {\n size += value.length;\n }\n }\n return size;\n}\n\n/**\n * Normalize an HTTP request method string per `http.request.method` spec\n * https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md#http-client-span\n */\nexport function normalizeHttpRequestMethod(method: string): string {\n const knownMethods = getKnownMethods();\n const methUpper = method.toUpperCase();\n if (methUpper in knownMethods) {\n return methUpper;\n } else {\n return '_OTHER';\n }\n}\n\nconst DEFAULT_KNOWN_METHODS = {\n CONNECT: true,\n DELETE: true,\n GET: true,\n HEAD: true,\n OPTIONS: true,\n PATCH: true,\n POST: true,\n PUT: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/\n QUERY: true,\n};\nlet knownMethods: { [key: string]: boolean };\nfunction getKnownMethods() {\n if (knownMethods === undefined) {\n const cfgMethods = getStringListFromEnv(\n 'OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS'\n );\n if (cfgMethods && cfgMethods.length > 0) {\n knownMethods = {};\n cfgMethods.forEach(m => {\n knownMethods[m] = true;\n });\n } else {\n knownMethods = DEFAULT_KNOWN_METHODS;\n }\n }\n return knownMethods;\n}\n\nconst HTTP_PORT_FROM_PROTOCOL: { [key: string]: string } = {\n 'https:': '443',\n 'http:': '80',\n};\nexport function serverPortFromUrl(url: URLLike): number | undefined {\n const serverPort = Number(url.port || HTTP_PORT_FROM_PROTOCOL[url.protocol]);\n // Guard with `if (serverPort)` because `Number('') === 0`.\n if (serverPort && !isNaN(serverPort)) {\n return serverPort;\n } else {\n return undefined;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.213.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md\n */\nexport enum AttributeNames {\n HTTP_STATUS_TEXT = 'http.status_text',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n SemconvStability,\n semconvStabilityFromStr,\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';\nimport {\n addSpanNetworkEvents,\n getResource,\n PerformanceTimingNames as PTN,\n shouldPropagateTraceHeaders,\n parseUrl,\n} from '@opentelemetry/sdk-trace-web';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_HTTP_HOST,\n ATTR_HTTP_METHOD,\n ATTR_HTTP_SCHEME,\n ATTR_HTTP_STATUS_CODE,\n ATTR_HTTP_URL,\n ATTR_HTTP_USER_AGENT,\n ATTR_HTTP_REQUEST_BODY_SIZE,\n ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n} from './semconv';\nimport { EventNames } from './enums/EventNames';\nimport {\n OpenFunction,\n PropagateTraceHeaderCorsUrls,\n SendFunction,\n XhrMem,\n} from './types';\nimport {\n normalizeHttpRequestMethod,\n serverPortFromUrl,\n getXHRBodyLength,\n} from './utils';\nimport { VERSION } from './version';\nimport { AttributeNames } from './enums/AttributeNames';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nexport type XHRCustomAttributeFunction = (\n span: api.Span,\n xhr: XMLHttpRequest\n) => void;\n\n/**\n * XMLHttpRequest config\n */\nexport interface XMLHttpRequestInstrumentationConfig\n extends InstrumentationConfig {\n /**\n * The number of timing resources is limited, after the limit\n * (chrome 250, safari 150) the information is not collected anymore.\n * The only way to prevent that is to regularly clean the resources\n * whenever it is possible. This is needed only when PerformanceObserver\n * is not available\n */\n clearTimingResources?: boolean;\n /** URLs which should include trace headers when origin doesn't match */\n propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;\n /** Ignore adding network events as span events */\n ignoreNetworkEvents?: boolean;\n /** Measure outgoing request size */\n measureRequestSize?: boolean;\n /** Select the HTTP semantic conventions version(s) used. */\n semconvStabilityOptIn?: string;\n}\n\n/**\n * This class represents a XMLHttpRequest plugin for auto instrumentation\n */\nexport class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequestInstrumentationConfig> {\n readonly component: string = 'xml-http-request';\n readonly version: string = VERSION;\n moduleName = this.component;\n\n private _tasksCount = 0;\n private _xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _semconvStability: SemconvStability;\n\n constructor(config: XMLHttpRequestInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-xml-http-request', VERSION, config);\n this._semconvStability = semconvStabilityFromStr(\n 'http',\n config?.semconvStabilityOptIn\n );\n }\n\n init() {}\n\n /**\n * Adds custom headers to XMLHttpRequest\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addHeaders(xhr: XMLHttpRequest, spanUrl: string) {\n const url = parseUrl(spanUrl).href;\n if (\n !shouldPropagateTraceHeaders(\n url,\n this.getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n const headers: { [key: string]: unknown } = {};\n api.propagation.inject(api.context.active(), headers);\n Object.keys(headers).forEach(key => {\n xhr.setRequestHeader(key, String(headers[key]));\n });\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n * @private\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n api.context.with(api.trace.setSpan(api.context.active(), span), () => {\n const childSpan = this.tracer.startSpan('CORS Preflight', {\n startTime: corsPreFlightRequest[PTN.FETCH_START],\n });\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n addSpanNetworkEvents(\n childSpan,\n corsPreFlightRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n childSpan.end(corsPreFlightRequest[PTN.RESPONSE_END]);\n });\n }\n\n /**\n * Add attributes when span is going to end\n * @param span\n * @param xhr\n * @param spanUrl\n * @private\n */\n _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem, spanUrl?: string) {\n if (this._semconvStability & SemconvStability.OLD) {\n if (xhrMem.status !== undefined) {\n span.setAttribute(ATTR_HTTP_STATUS_CODE, xhrMem.status);\n }\n if (xhrMem.statusText !== undefined) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, xhrMem.statusText);\n }\n if (typeof spanUrl === 'string') {\n const parsedUrl = parseUrl(spanUrl);\n span.setAttribute(ATTR_HTTP_HOST, parsedUrl.host);\n span.setAttribute(\n ATTR_HTTP_SCHEME,\n parsedUrl.protocol.replace(':', '')\n );\n }\n\n // @TODO do we want to collect this or it will be collected earlier once only or\n // maybe when parent span is not available ?\n span.setAttribute(ATTR_HTTP_USER_AGENT, navigator.userAgent);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n if (xhrMem.status) {\n // Intentionally exclude status=0, because XHR uses 0 for before a\n // response is received and semconv says to only add the attribute if\n // received a response.\n span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, xhrMem.status);\n }\n }\n }\n\n private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {\n const applyCustomAttributesOnSpan =\n this.getConfig().applyCustomAttributesOnSpan;\n if (typeof applyCustomAttributesOnSpan === 'function') {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, xhr),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * will collect information about all resources created\n * between \"send\" and \"end\" with additional waiting for main resource\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addResourceObserver(xhr: XMLHttpRequest, spanUrl: string) {\n const xhrMem = this._xhrMem.get(xhr);\n if (\n !xhrMem ||\n typeof PerformanceObserver !== 'function' ||\n typeof PerformanceResourceTiming !== 'function'\n ) {\n return;\n }\n xhrMem.createdResources = {\n observer: new PerformanceObserver(list => {\n const entries = list.getEntries() as PerformanceResourceTiming[];\n const parsedUrl = parseUrl(spanUrl);\n\n entries.forEach(entry => {\n if (\n entry.initiatorType === 'xmlhttprequest' &&\n entry.name === parsedUrl.href\n ) {\n if (xhrMem.createdResources) {\n xhrMem.createdResources.entries.push(entry);\n }\n }\n });\n }),\n entries: [],\n };\n xhrMem.createdResources.observer.observe({\n entryTypes: ['resource'],\n });\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {\n (otperformance as unknown as Performance).clearResourceTimings();\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n */\n private _findResourceAndAddNetworkEvents(\n xhrMem: XhrMem,\n span: api.Span,\n spanUrl?: string,\n startTime?: api.HrTime,\n endTime?: api.HrTime\n ): void {\n if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) {\n return;\n }\n\n let resources: PerformanceResourceTiming[] =\n xhrMem.createdResources.entries;\n\n if (!resources || !resources.length) {\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n // ts thinks this is the perf_hooks module, but it is the browser performance api\n resources = (otperformance as unknown as Performance).getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n\n const resource = getResource(\n parseUrl(spanUrl).href,\n startTime,\n endTime,\n resources,\n this._usedResources\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n const skipOldSemconvContentLengthAttrs = !(\n this._semconvStability & SemconvStability.OLD\n );\n addSpanNetworkEvents(\n span,\n mainRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n skipOldSemconvContentLengthAttrs\n );\n }\n }\n\n /**\n * Removes the previous information about span.\n * This might happened when the same xhr is used again.\n * @param xhr\n * @private\n */\n private _cleanPreviousSpanInformation(xhr: XMLHttpRequest) {\n const xhrMem = this._xhrMem.get(xhr);\n if (xhrMem) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n if (callbackToRemoveEvents) {\n callbackToRemoveEvents();\n }\n this._xhrMem.delete(xhr);\n }\n }\n\n /**\n * Creates a new span when method \"open\" is called\n * @param xhr\n * @param url\n * @param method\n * @private\n */\n private _createSpan(\n xhr: XMLHttpRequest,\n url: string,\n method: string\n ): api.Span | undefined {\n if (isUrlIgnored(url, this.getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n\n let name = '';\n const parsedUrl = parseUrl(url);\n const attributes = {} as api.Attributes;\n if (this._semconvStability & SemconvStability.OLD) {\n name = method.toUpperCase();\n attributes[ATTR_HTTP_METHOD] = method;\n attributes[ATTR_HTTP_URL] = parsedUrl.toString();\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n const origMethod = method;\n const normMethod = normalizeHttpRequestMethod(method);\n if (!name) {\n // The \"old\" span name wins if emitting both old and stable semconv\n // ('http/dup').\n name = normMethod;\n }\n attributes[ATTR_HTTP_REQUEST_METHOD] = normMethod;\n if (normMethod !== origMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;\n }\n attributes[ATTR_URL_FULL] = parsedUrl.toString();\n attributes[ATTR_SERVER_ADDRESS] = parsedUrl.hostname;\n const serverPort = serverPortFromUrl(parsedUrl);\n if (serverPort) {\n attributes[ATTR_SERVER_PORT] = serverPort;\n }\n }\n\n const currentSpan = this.tracer.startSpan(name, {\n kind: api.SpanKind.CLIENT,\n attributes,\n });\n\n currentSpan.addEvent(EventNames.METHOD_OPEN);\n\n this._cleanPreviousSpanInformation(xhr);\n\n this._xhrMem.set(xhr, {\n span: currentSpan,\n spanUrl: url,\n });\n\n return currentSpan;\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n * @private\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming) {\n this._usedResources.add(resource);\n }\n\n /**\n * Patches the method open\n * @private\n */\n protected _patchOpen() {\n return (original: OpenFunction): OpenFunction => {\n const plugin = this;\n return function patchOpen(this: XMLHttpRequest, ...args): void {\n const method: string = args[0];\n const url: string = args[1];\n plugin._createSpan(this, url, method);\n\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * Patches the method send\n * @private\n */\n protected _patchSend() {\n const plugin = this;\n\n function endSpanTimeout(\n eventName: string,\n xhrMem: XhrMem,\n performanceEndTime: api.HrTime,\n endTime: number\n ) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n\n if (typeof callbackToRemoveEvents === 'function') {\n callbackToRemoveEvents();\n }\n\n const { span, spanUrl, sendStartTime } = xhrMem;\n\n if (span) {\n plugin._findResourceAndAddNetworkEvents(\n xhrMem,\n span,\n spanUrl,\n sendStartTime,\n performanceEndTime\n );\n span.addEvent(eventName, endTime);\n plugin._addFinalSpanAttributes(span, xhrMem, spanUrl);\n span.end(endTime);\n plugin._tasksCount--;\n }\n plugin._clearResources();\n }\n\n function endSpan(\n eventName: string,\n xhr: XMLHttpRequest,\n isError: boolean,\n errorType?: string\n ) {\n const xhrMem = plugin._xhrMem.get(xhr);\n if (!xhrMem) {\n return;\n }\n xhrMem.status = xhr.status;\n xhrMem.statusText = xhr.statusText;\n plugin._xhrMem.delete(xhr);\n\n if (xhrMem.span) {\n const span = xhrMem.span;\n plugin._applyAttributesAfterXHR(span, xhr);\n\n if (plugin._semconvStability & SemconvStability.STABLE) {\n if (isError) {\n if (errorType) {\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: errorType,\n });\n span.setAttribute(ATTR_ERROR_TYPE, errorType);\n }\n } else if (xhrMem.status && xhrMem.status >= 400) {\n span.setStatus({ code: api.SpanStatusCode.ERROR });\n span.setAttribute(ATTR_ERROR_TYPE, String(xhrMem.status));\n }\n }\n }\n\n const performanceEndTime = hrTime();\n const endTime = Date.now();\n\n // the timeout is needed as observer doesn't have yet information\n // when event \"load\" is called. Also the time may differ depends on\n // browser and speed of computer\n setTimeout(() => {\n endSpanTimeout(eventName, xhrMem, performanceEndTime, endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n function onError(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ERROR, this, true, 'error');\n }\n\n function onAbort(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ABORT, this, false);\n }\n\n function onTimeout(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_TIMEOUT, this, true, 'timeout');\n }\n\n function onLoad(this: XMLHttpRequest) {\n if (this.status < 299) {\n endSpan(EventNames.EVENT_LOAD, this, false);\n } else {\n endSpan(EventNames.EVENT_ERROR, this, false);\n }\n }\n\n function unregister(xhr: XMLHttpRequest) {\n xhr.removeEventListener('abort', onAbort);\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onTimeout);\n const xhrMem = plugin._xhrMem.get(xhr);\n if (xhrMem) {\n xhrMem.callbackToRemoveEvents = undefined;\n }\n }\n\n return (original: SendFunction): SendFunction => {\n return function patchSend(this: XMLHttpRequest, ...args): void {\n const xhrMem = plugin._xhrMem.get(this);\n if (!xhrMem) {\n return original.apply(this, args);\n }\n const currentSpan = xhrMem.span;\n const spanUrl = xhrMem.spanUrl;\n\n if (currentSpan && spanUrl) {\n if (plugin.getConfig().measureRequestSize && args?.[0]) {\n const body = args[0];\n const bodyLength = getXHRBodyLength(body);\n if (bodyLength !== undefined) {\n if (plugin._semconvStability & SemconvStability.OLD) {\n currentSpan.setAttribute(\n ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n bodyLength\n );\n }\n if (plugin._semconvStability & SemconvStability.STABLE) {\n currentSpan.setAttribute(\n ATTR_HTTP_REQUEST_BODY_SIZE,\n bodyLength\n );\n }\n }\n }\n\n api.context.with(\n api.trace.setSpan(api.context.active(), currentSpan),\n () => {\n plugin._tasksCount++;\n xhrMem.sendStartTime = hrTime();\n currentSpan.addEvent(EventNames.METHOD_SEND);\n\n this.addEventListener('abort', onAbort);\n this.addEventListener('error', onError);\n this.addEventListener('load', onLoad);\n this.addEventListener('timeout', onTimeout);\n\n xhrMem.callbackToRemoveEvents = () => {\n unregister(this);\n if (xhrMem.createdResources) {\n xhrMem.createdResources.observer.disconnect();\n }\n };\n plugin._addHeaders(this, spanUrl);\n plugin._addResourceObserver(this, spanUrl);\n }\n );\n }\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * implements enable function\n */\n override enable() {\n this._diag.debug('applying patch to', this.moduleName, this.version);\n\n if (isWrapped(XMLHttpRequest.prototype.open)) {\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._diag.debug('removing previous patch from method open');\n }\n\n if (isWrapped(XMLHttpRequest.prototype.send)) {\n this._unwrap(XMLHttpRequest.prototype, 'send');\n this._diag.debug('removing previous patch from method send');\n }\n\n this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());\n this._wrap(XMLHttpRequest.prototype, 'send', this._patchSend());\n }\n\n /**\n * implements disable function\n */\n override disable() {\n this._diag.debug('removing patch from', this.moduleName, this.version);\n\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._unwrap(XMLHttpRequest.prototype, 'send');\n\n this._tasksCount = 0;\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.6.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-web-exception';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n InstrumentationBase,\n type InstrumentationConfig,\n} from '@opentelemetry/instrumentation';\nimport {\n ATTR_EXCEPTION_TYPE,\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n} from '@opentelemetry/semantic-conventions';\nimport type { Attributes } from '@opentelemetry/api';\nimport {\n SeverityNumber,\n logs,\n type LogRecord,\n type AnyValueMap,\n} from '@opentelemetry/api-logs';\nimport { hrTime } from '@opentelemetry/core';\n\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\nexport interface GlobalErrorsInstrumentationConfig\n extends InstrumentationConfig {\n /**\n * A callback function for adding custom attributes to the log event when an error is recorded.\n *\n * @param {Error} error - The error object that is being recorded.\n * @returns {Attributes} - The attributes to add to the span.\n */\n applyCustomAttributes?: (error: Error | string) => Attributes;\n}\n\nexport class ExceptionInstrumentation extends InstrumentationBase<GlobalErrorsInstrumentationConfig> {\n declare private _onErrorHandler?: (\n event: ErrorEvent | PromiseRejectionEvent\n ) => void;\n\n constructor(config: GlobalErrorsInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {}\n\n onError(event: ErrorEvent | PromiseRejectionEvent) {\n const EXCEPTION_EVENT_NAME = 'exception';\n const error: Error | string | undefined =\n 'reason' in event ? event.reason : event.error;\n\n if (error === undefined) {\n return;\n }\n\n const logger = logs\n .getLoggerProvider()\n .getLogger(this.instrumentationName, this.instrumentationVersion);\n\n const config = this.getConfig();\n const customAttributes = config.applyCustomAttributes\n ? config.applyCustomAttributes(error)\n : {};\n\n let errorAttributes: AnyValueMap = {};\n\n if (typeof error === 'string') {\n errorAttributes = { [ATTR_EXCEPTION_MESSAGE]: error };\n } else {\n errorAttributes = {\n [ATTR_EXCEPTION_TYPE]: error.name,\n [ATTR_EXCEPTION_MESSAGE]: error.message,\n [ATTR_EXCEPTION_STACKTRACE]: error.stack,\n };\n }\n\n const errorLog: LogRecord = {\n eventName: EXCEPTION_EVENT_NAME,\n severityNumber: SeverityNumber.ERROR,\n attributes: { ...errorAttributes, ...customAttributes },\n timestamp: hrTime(),\n observedTimestamp: hrTime(),\n };\n\n logger.emit(errorLog);\n }\n\n override disable(): void {\n if (this._onErrorHandler) {\n window.removeEventListener('error', this._onErrorHandler);\n window.removeEventListener('unhandledrejection', this._onErrorHandler);\n }\n }\n\n override enable(): void {\n if (!this._onErrorHandler) {\n this._onErrorHandler = this.onError.bind(this);\n }\n window.addEventListener('error', this._onErrorHandler);\n window.addEventListener('unhandledrejection', this._onErrorHandler);\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\nexport const WEB_VITAL_EVENT_NAME = 'browser.web_vital';\n\n// Core metric attributes\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_NAME = 'browser.web_vital.name';\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_VALUE = 'browser.web_vital.value';\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_RATING = 'browser.web_vital.rating';\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_DELTA = 'browser.web_vital.delta';\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_ID = 'browser.web_vital.id';\n\n/**\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_WEB_VITAL_NAVIGATION_TYPE =\n 'browser.web_vital.navigation_type';\n", "class t{t;o=0;i=[];u(t){if(t.hadRecentInput)return;const e=this.i[0],n=this.i.at(-1);this.o&&e&&n&&t.startTime-n.startTime<1e3&&t.startTime-e.startTime<5e3?(this.o+=t.value,this.i.push(t)):(this.o=t.value,this.i=[t]),this.t?.(t)}}const e=()=>{const t=performance.getEntriesByType(\"navigation\")[0];if(t&&t.responseStart>0&&t.responseStart<performance.now())return t},n=t=>{if(\"loading\"===document.readyState)return\"loading\";{const n=e();if(n){if(t<n.domInteractive)return\"loading\";if(0===n.domContentLoadedEventStart||t<n.domContentLoadedEventStart)return\"dom-interactive\";if(0===n.domComplete||t<n.domComplete)return\"dom-content-loaded\"}}return\"complete\"},o=t=>{const e=t.nodeName;return 1===t.nodeType?e.toLowerCase():e.toUpperCase().replace(/^#/,\"\")},i=t=>{let e=\"\";try{for(;9!==t?.nodeType;){const n=t,i=n.id?\"#\"+n.id:[o(n),...Array.from(n.classList).sort()].join(\".\");if(e.length+i.length>99)return e||i;if(e=e?i+\">\"+e:i,n.id)break;t=n.parentNode}}catch{}return e},r=new WeakMap;function s(t,e){return r.get(t)||r.set(t,new e),r.get(t)}let a=-1;const c=()=>a,f=t=>{addEventListener(\"pageshow\",(e=>{e.persisted&&(a=e.timeStamp,t(e))}),!0)},u=(t,e,n,o)=>{let i,r;return s=>{e.value>=0&&(s||o)&&(r=e.value-(i??0),(r||void 0===i)&&(i=e.value,e.delta=r,e.rating=((t,e)=>t>e[1]?\"poor\":t>e[0]?\"needs-improvement\":\"good\")(e.value,n),t(e)))}},d=t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))},l=()=>{const t=e();return t?.activationStart??0},h=(t,n=-1)=>{const o=e();let i=\"navigate\";c()>=0?i=\"back-forward-cache\":o&&(document.prerendering||l()>0?i=\"prerender\":document.wasDiscarded?i=\"restore\":o.type&&(i=o.type.replace(/_/g,\"-\")));return{name:t,value:n,rating:\"good\",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},m=(t,e,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){const o=new PerformanceObserver((t=>{Promise.resolve().then((()=>{e(t.getEntries())}))}));return o.observe({type:t,buffered:!0,...n}),o}}catch{}},p=t=>{let e=!1;return()=>{e||(t(),e=!0)}};let g=-1;const y=new Set,v=()=>\"hidden\"!==document.visibilityState||document.prerendering?1/0:0,b=t=>{if(\"hidden\"===document.visibilityState){if(\"visibilitychange\"===t.type)for(const t of y)t();isFinite(g)||(g=\"visibilitychange\"===t.type?t.timeStamp:0,removeEventListener(\"prerenderingchange\",b,!0))}},M=()=>{if(g<0){const t=l(),e=document.prerendering?void 0:globalThis.performance.getEntriesByType(\"visibility-state\").filter((e=>\"hidden\"===e.name&&e.startTime>t))[0]?.startTime;g=e??v(),addEventListener(\"visibilitychange\",b,!0),addEventListener(\"prerenderingchange\",b,!0),f((()=>{setTimeout((()=>{g=v()}))}))}return{get firstHiddenTime(){return g},onHidden(t){y.add(t)}}},T=t=>{document.prerendering?addEventListener(\"prerenderingchange\",(()=>t()),!0):t()},E=[1800,3e3],D=(t,e={})=>{T((()=>{const n=M();let o,i=h(\"FCP\");const r=m(\"paint\",(t=>{for(const e of t)\"first-contentful-paint\"===e.name&&(r.disconnect(),e.startTime<n.firstHiddenTime&&(i.value=Math.max(e.startTime-l(),0),i.entries.push(e),o(!0)))}));r&&(o=u(t,i,E,e.reportAllChanges),f((n=>{i=h(\"FCP\"),o=u(t,i,E,e.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,o(!0)}))})))}))},L=[.1,.25],P=t=>t.find((t=>1===t.node?.nodeType))||t[0],S=(e,o={})=>{const r=s(o=Object.assign({},o),t),a=new WeakMap;r.t=t=>{if(t?.sources?.length){const e=P(t.sources),n=e?.node;if(n){const t=o.generateTarget?.(n)??i(n);a.set(e,t)}}};((e,n={})=>{const o=M();D(p((()=>{let i,r=h(\"CLS\",0);const a=s(n,t),c=t=>{for(const e of t)a.u(e);a.o>r.value&&(r.value=a.o,r.entries=a.i,i())},l=m(\"layout-shift\",c);l&&(i=u(e,r,L,n.reportAllChanges),o.onHidden((()=>{c(l.takeRecords()),i(!0)})),f((()=>{a.o=0,r=h(\"CLS\",0),i=u(e,r,L,n.reportAllChanges),d((()=>i()))})),setTimeout(i))})))})((t=>{const o=(t=>{let e={};if(t.entries.length){const o=t.entries.reduce(((t,e)=>t.value>e.value?t:e));if(o?.sources?.length){const t=P(o.sources);t&&(e={largestShiftTarget:a.get(t),largestShiftTime:o.startTime,largestShiftValue:o.value,largestShiftSource:t,largestShiftEntry:o,loadState:n(o.startTime)})}}return Object.assign(t,{attribution:e})})(t);e(o)}),o)},w=(t,o={})=>{D((o=>{const i=(t=>{let o={timeToFirstByte:0,firstByteToFCP:t.value,loadState:n(c())};if(t.entries.length){const i=e(),r=t.entries.at(-1);if(i){const e=i.activationStart||0,s=Math.max(0,i.responseStart-e);o={timeToFirstByte:s,firstByteToFCP:t.value-s,loadState:n(t.entries[0].startTime),navigationEntry:i,fcpEntry:r}}}return Object.assign(t,{attribution:o})})(o);t(i)}),o)};let _=0,F=1/0,k=0;const B=t=>{for(const e of t)e.interactionId&&(F=Math.min(F,e.interactionId),k=Math.max(k,e.interactionId),_=k?(k-F)/7+1:0)};let C;const O=()=>C?_:performance.interactionCount??0,j=()=>{\"interactionCount\"in performance||C||(C=m(\"event\",B,{type:\"event\",buffered:!0,durationThreshold:0}))};let I=0;class A{l=[];h=new Map;m;p;v(){I=O(),this.l.length=0,this.h.clear()}M(){const t=Math.min(this.l.length-1,Math.floor((O()-I)/50));return this.l[t]}u(t){if(this.m?.(t),!t.interactionId&&\"first-input\"!==t.entryType)return;const e=this.l.at(-1);let n=this.h.get(t.interactionId);if(n||this.l.length<10||t.duration>e.T){if(n?t.duration>n.T?(n.entries=[t],n.T=t.duration):t.duration===n.T&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],T:t.duration},this.h.set(n.id,n),this.l.push(n)),this.l.sort(((t,e)=>e.T-t.T)),this.l.length>10){const t=this.l.splice(10);for(const e of t)this.h.delete(e.id)}this.p?.(n)}}}const W=t=>{const e=globalThis.requestIdleCallback||setTimeout;\"hidden\"===document.visibilityState?t():(t=p(t),addEventListener(\"visibilitychange\",t,{once:!0,capture:!0}),e((()=>{t(),removeEventListener(\"visibilitychange\",t,{capture:!0})})))},q=[200,500],x=(t,e={})=>{const o=s(e=Object.assign({},e),A);let r=[],a=[],c=0;const d=new WeakMap,l=new WeakMap;let p=!1;const g=()=>{p||(W(y),p=!0)},y=()=>{const t=o.l.map((t=>d.get(t.entries[0]))),e=a.length-50;a=a.filter(((n,o)=>o>=e||t.includes(n)));const n=new Set;for(const t of a){const e=v(t.startTime,t.processingEnd);for(const t of e)n.add(t)}const i=r.length-1-50;r=r.filter(((t,e)=>t.startTime>c&&e>i||n.has(t))),p=!1};o.m=t=>{const e=t.startTime+t.duration;let n;c=Math.max(c,t.processingEnd);for(let o=a.length-1;o>=0;o--){const i=a[o];if(Math.abs(e-i.renderTime)<=8){n=i,n.startTime=Math.min(t.startTime,n.startTime),n.processingStart=Math.min(t.processingStart,n.processingStart),n.processingEnd=Math.max(t.processingEnd,n.processingEnd),n.entries.push(t);break}}n||(n={startTime:t.startTime,processingStart:t.processingStart,processingEnd:t.processingEnd,renderTime:e,entries:[t]},a.push(n)),(t.interactionId||\"first-input\"===t.entryType)&&d.set(t,n),g()},o.p=t=>{if(!l.get(t)){const n=t.entries[0].target;if(n){const o=e.generateTarget?.(n)??i(n);l.set(t,o)}}};const v=(t,e)=>{const n=[];for(const o of r)if(!(o.startTime+o.duration<t)){if(o.startTime>e)break;n.push(o)}return n},b=t=>{const e=t.entries[0],i=d.get(e),r=e.processingStart,s=Math.max(e.startTime+e.duration,r),a=Math.min(i.processingEnd,s),c=i.entries.sort(((t,e)=>t.processingStart-e.processingStart)),f=v(e.startTime,a),u=o.h.get(e.interactionId),h={interactionTarget:l.get(u),interactionType:e.name.startsWith(\"key\")?\"keyboard\":\"pointer\",interactionTime:e.startTime,nextPaintTime:s,processedEventEntries:c,longAnimationFrameEntries:f,inputDelay:r-e.startTime,processingDuration:a-r,presentationDelay:s-a,loadState:n(e.startTime),longestScript:void 0,totalScriptDuration:void 0,totalStyleAndLayoutDuration:void 0,totalPaintDuration:void 0,totalUnattributedDuration:void 0};(t=>{if(!t.longAnimationFrameEntries?.length)return;const e=t.interactionTime,n=t.inputDelay,o=t.processingDuration;let i,r,s=0,a=0,c=0,f=0;for(const c of t.longAnimationFrameEntries){a=a+c.startTime+c.duration-c.styleAndLayoutStart;for(const t of c.scripts){const c=t.startTime+t.duration;if(c<e)continue;const u=c-Math.max(e,t.startTime),d=t.duration?u/t.duration*t.forcedStyleAndLayoutDuration:0;s+=u-d,a+=d,u>f&&(r=t.startTime<e+n?\"input-delay\":t.startTime>=e+n+o?\"presentation-delay\":\"processing-duration\",i=t,f=u)}}const u=t.longAnimationFrameEntries.at(-1),d=u?u.startTime+u.duration:0;d>=e+n+o&&(c=t.nextPaintTime-d),i&&r&&(t.longestScript={entry:i,subpart:r,intersectingDuration:f}),t.totalScriptDuration=s,t.totalStyleAndLayoutDuration=a,t.totalPaintDuration=c,t.totalUnattributedDuration=t.nextPaintTime-e-s-a-c})(h);return Object.assign(t,{attribution:h})};m(\"long-animation-frame\",(t=>{r=r.concat(t),g()})),((t,e={})=>{if(!globalThis.PerformanceEventTiming||!(\"interactionId\"in PerformanceEventTiming.prototype))return;const n=M();T((()=>{j();let o,i=h(\"INP\");const r=s(e,A),a=t=>{W((()=>{for(const e of t)r.u(e);const e=r.M();e&&e.T!==i.value&&(i.value=e.T,i.entries=e.entries,o())}))},c=m(\"event\",a,{durationThreshold:e.durationThreshold??40});o=u(t,i,q,e.reportAllChanges),c&&(c.observe({type:\"first-input\",buffered:!0}),n.onHidden((()=>{a(c.takeRecords()),o(!0)})),f((()=>{r.v(),i=h(\"INP\"),o=u(t,i,q,e.reportAllChanges)})))}))})((e=>{const n=b(e);t(n)}),e)};class N{m;u(t){this.m?.(t)}}const H=[2500,4e3],R=(t,n={})=>{const o=s(n=Object.assign({},n),N),r=new WeakMap;o.m=t=>{const e=t.element;if(e){const o=n.generateTarget?.(e)??i(e);r.set(t,o)}};((t,e={})=>{T((()=>{const n=M();let o,i=h(\"LCP\");const r=s(e,N),a=t=>{e.reportAllChanges||(t=t.slice(-1));for(const e of t)r.u(e),e.startTime<n.firstHiddenTime&&(i.value=Math.max(e.startTime-l(),0),i.entries=[e],o())},c=m(\"largest-contentful-paint\",a);if(c){o=u(t,i,H,e.reportAllChanges);const n=p((()=>{a(c.takeRecords()),c.disconnect(),o(!0)})),r=t=>{t.isTrusted&&(W(n),removeEventListener(t.type,r,{capture:!0}))};for(const t of[\"keydown\",\"click\",\"visibilitychange\"])addEventListener(t,r,{capture:!0});f((n=>{i=h(\"LCP\"),o=u(t,i,H,e.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,o(!0)}))}))}}))})((n=>{const o=(t=>{let n={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:t.value};if(t.entries.length){const o=e();if(o){const e=o.activationStart||0,i=t.entries.at(-1),s=i.url&&performance.getEntriesByType(\"resource\").filter((t=>t.name===i.url))[0],a=Math.max(0,o.responseStart-e),c=Math.max(a,s?(s.requestStart||s.startTime)-e:0),f=Math.min(t.value,Math.max(c,s?s.responseEnd-e:0));n={target:r.get(i),timeToFirstByte:a,resourceLoadDelay:c-a,resourceLoadDuration:f-c,elementRenderDelay:t.value-f,navigationEntry:o,lcpEntry:i},i.url&&(n.url=i.url),s&&(n.lcpResourceEntry=s)}}return Object.assign(t,{attribution:n})})(n);t(o)}),n)},U=[800,1800],V=t=>{document.prerendering?T((()=>V(t))):\"complete\"!==document.readyState?addEventListener(\"load\",(()=>V(t)),!0):setTimeout(t)},$=(t,n={})=>{((t,n={})=>{let o=h(\"TTFB\"),i=u(t,o,U,n.reportAllChanges);V((()=>{const r=e();r&&(o.value=Math.max(r.responseStart-l(),0),o.entries=[r],i(!0),f((()=>{o=h(\"TTFB\",0),i=u(t,o,U,n.reportAllChanges),i(!0)})))}))})((e=>{const n=(t=>{let e={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(t.entries.length){const n=t.entries[0],o=n.activationStart||0,i=Math.max((n.workerStart||n.fetchStart)-o,0),r=Math.max(n.domainLookupStart-o,0),s=Math.max(n.connectStart-o,0),a=Math.max(n.connectEnd-o,0);e={waitingDuration:i,cacheDuration:r-i,dnsDuration:s-r,connectionDuration:a-s,requestDuration:t.value-a,navigationEntry:n}}return Object.assign(t,{attribution:e})})(e);t(n)}),n)};export{L as CLSThresholds,E as FCPThresholds,q as INPThresholds,H as LCPThresholds,U as TTFBThresholds,S as onCLS,w as onFCP,x as onINP,R as onLCP,$ as onTTFB};\n", "/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes } from '@opentelemetry/api';\nimport type { LogRecord } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n CLSMetricWithAttribution,\n INPMetricWithAttribution,\n MetricWithAttribution,\n} from 'web-vitals/attribution';\nimport { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';\nimport {\n ATTR_WEB_VITAL_DELTA,\n ATTR_WEB_VITAL_ID,\n ATTR_WEB_VITAL_NAME,\n ATTR_WEB_VITAL_NAVIGATION_TYPE,\n ATTR_WEB_VITAL_RATING,\n ATTR_WEB_VITAL_VALUE,\n WEB_VITAL_EVENT_NAME,\n} from './semconv.ts';\nimport type { WebVitalsInstrumentationConfig } from './types.ts';\n\n/**\n * Instrumentation for Core Web Vitals using the `web-vitals` library.\n * https://github.com/GoogleChrome/web-vitals\n *\n * Note: The `web-vitals` library does not support removing listeners once\n * registered. Calling `disable()` will stop emitting logs, but the underlying\n * listeners remain active. Calling `enable()` again will resume emission.\n */\nexport class WebVitalsInstrumentation extends InstrumentationBase<WebVitalsInstrumentationConfig> {\n // Using `declare` is required here: InstrumentationBase calls enable() during\n // construction, and standard field initialization would reset this flag after\n // super() returns, breaking the duplicate-registration guard.\n private declare _isEnabled: boolean;\n private declare _listenersRegistered: boolean;\n private _applyCustomLogRecordData?: (logRecord: LogRecord) => void;\n private _includeRawAttribution: boolean;\n\n constructor(config: WebVitalsInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-web-vitals', '0.1.0', config);\n this._applyCustomLogRecordData = config.applyCustomLogRecordData;\n this._includeRawAttribution = config.includeRawAttribution ?? false;\n }\n\n protected override init() {\n return [];\n }\n\n /**\n * Enables the instrumentation and registers web-vitals listeners.\n * Listeners are registered only once. If disabled, subsequent calls resume emission.\n */\n override enable(): void {\n if (typeof PerformanceObserver === 'undefined') {\n this._diag.debug(\n 'PerformanceObserver not supported, web vitals will not be collected',\n );\n return;\n }\n\n this._isEnabled = true;\n\n if (this._listenersRegistered) {\n this._diag.debug('Listeners already registered, resuming emission');\n return;\n }\n\n this._listenersRegistered = true;\n this._diag.debug(`Registering listeners`);\n // CLS is only supported in Chromium. See:\n // https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#browser-support\n onCLS((metric) => this._emitWebVital(metric));\n onINP((metric) => this._emitWebVital(metric));\n onLCP((metric) => this._emitWebVital(metric));\n onFCP((metric) => this._emitWebVital(metric));\n onTTFB((metric) => this._emitWebVital(metric));\n }\n\n /**\n * Disables the instrumentation, pausing log emission.\n * Listeners remain active due to web-vitals library limitations.\n */\n override disable(): void {\n this._isEnabled = false;\n this._diag.debug('Instrumentation disabled, pausing emission');\n }\n\n /**\n * Gets the timestamp for a metric based on attribution timing.\n * Returns undefined to let OTel use the current time for metrics without\n * specific timing information.\n */\n private _getTimestampForMetric(\n metric: MetricWithAttribution,\n ): number | undefined {\n if (metric.name === 'CLS') {\n const { attribution } = metric as CLSMetricWithAttribution;\n if (attribution.largestShiftTime !== undefined) {\n return attribution.largestShiftTime;\n }\n return undefined;\n }\n if (metric.name === 'INP') {\n const { attribution } = metric as INPMetricWithAttribution;\n return attribution.interactionTime;\n }\n // FCP, LCP, TTFB: metric.value is already DOMHighResTimeStamp of the event\n return metric.value;\n }\n\n private _emitWebVital(metric: MetricWithAttribution): void {\n if (!this._isEnabled) {\n return;\n }\n const attributes: Attributes = {\n [ATTR_WEB_VITAL_NAME]: metric.name.toLowerCase(),\n [ATTR_WEB_VITAL_VALUE]: metric.value,\n // `delta` equals `value` on the first emission; subsequent emissions report only the change\n [ATTR_WEB_VITAL_DELTA]: metric.delta,\n [ATTR_WEB_VITAL_RATING]: metric.rating,\n [ATTR_WEB_VITAL_ID]: metric.id,\n [ATTR_WEB_VITAL_NAVIGATION_TYPE]: metric.navigationType,\n };\n\n const timestamp = this._getTimestampForMetric(metric);\n\n const logRecord: LogRecord = {\n eventName: WEB_VITAL_EVENT_NAME,\n severityNumber: SeverityNumber.INFO,\n attributes,\n ...(this._includeRawAttribution\n ? { body: JSON.stringify(metric.attribution) }\n : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n };\n\n if (this._applyCustomLogRecordData) {\n safeExecuteInTheMiddle(\n () => this._applyCustomLogRecordData?.(logRecord),\n (error) => {\n if (error) {\n this._diag.error('applyCustomLogRecordData hook failed', error);\n }\n },\n true,\n );\n }\n\n this.logger.emit(logRecord);\n }\n}\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {DiagLogLevel} from '@opentelemetry/api';\n\nlet _logLevel = DiagLogLevel.INFO;\nconst logLevelMap = {\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 * TODO: luggite like?\n * @param {Object} config\n * @param {string} config.logLevel\n * @returns {import('@opentelemetry/api').DiagLogger}\n */\nexport function createLogger(config) {\n _logLevel = logLevelMap[config.logLevel.toUpperCase()];\n\n if (_logLevel == null) {\n console.warn(\n `Unknown log level \"${config.logLevel}\", expected one of ${Object.keys(logLevelMap)}, using default`\n );\n _logLevel = logLevelMap.INFO;\n }\n\n return {\n error: makeLogFunction(logLevelMap.ERROR, console.error.bind(console)),\n warn: makeLogFunction(logLevelMap.WARN, console.error.bind(console)),\n info: makeLogFunction(logLevelMap.INFO, console.log.bind(console)),\n debug: makeLogFunction(logLevelMap.DEBUG, console.log.bind(console)),\n verbose: makeLogFunction(\n logLevelMap.VERBOSE,\n console.trace.bind(console)\n ),\n };\n}\n\n/**\n * Build a log emitter function for level minLevel. I.e. this is the\n * creator of `log.info`, `log.error`, etc.\n *\n * @param {number} minLevel\n * @param {(...args: any[]) => void} emitFn\n * @returns {function(...any): void}\n */\nfunction makeLogFunction(minLevel, emitFn) {\n return function LOG(...args) {\n const shouldLog = _logLevel >= minLevel;\n if (args.length === 0) {\n // `log.<level>()`\n return shouldLog;\n }\n\n if (shouldLog) {\n emitFn(...args);\n }\n };\n}\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// This manager patches some async APIs to keep track of the context\n// on the most common cases for web applications like when user performs\n// an action and:\n// - a timer is set\n// - a fetch/XHR request is made\n// - a Promise is chained with `then`, `catch` or `finally`\n\nimport {ROOT_CONTEXT} from '@opentelemetry/api';\nimport {createLogger} from './logging.js';\n\n// use the diag one?\nconst logger = createLogger({logLevel: 'warn'});\n\n// Keep the state of the current context here so only\n// the manager has direct access.\nlet _currentContext = ROOT_CONTEXT;\nlet _managerEnabled = false;\n/** @type {import('@opentelemetry/api').ContextManager} */\nexport const AsyncApisContextManager = {\n active: function () {\n return _currentContext;\n },\n with: function (context, fn, thisArg, ...args) {\n const prevContext = _currentContext;\n _currentContext = context || ROOT_CONTEXT;\n try {\n return fn.call(thisArg, ...args);\n } finally {\n _currentContext = prevContext;\n }\n },\n // @ts-ignore -- upstream types expects a generic type as return\n bind: function (context, target) {\n if (typeof target === 'function') {\n return bindFn(target, this, context);\n }\n return target;\n },\n enable: function () {\n if (_managerEnabled) {\n return this;\n }\n const manager = this;\n wrap(window, 'setTimeout', (origSetTimeout) => {\n return function (...args) {\n // Coerce the delay argument to number like the original function does.\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#non-number_delay_values_are_silently_coerced_into_numbers\n const delay = Number(args[1]);\n // Only carry the context if the delay is low enough. `NaN` is the same as `undefined`\n // and schedules the callback immediately. The max value (50) is arbitrary.\n if (isNaN(delay) || delay <= 50) {\n args[0] = bindFn(args[0], manager, manager.active());\n }\n return origSetTimeout.apply(this, args);\n };\n });\n wrap(window, 'setImmediate', (origSetImmediate) => {\n return function (...args) {\n args[0] = bindFn(args[0], manager, manager.active());\n return origSetImmediate.apply(this, args);\n };\n });\n wrapXMLHttpRequest(manager);\n if (window.Promise) {\n wrapPromise(manager);\n }\n _currentContext = ROOT_CONTEXT;\n _managerEnabled = true;\n return manager;\n },\n disable: function () {\n if (_managerEnabled) {\n unwrap(window, 'setTimeout');\n unwrap(window, 'setImmediate');\n unwrapXMLHttpRequest();\n if (window.Promise) {\n unwrapPromise();\n }\n _currentContext = ROOT_CONTEXT;\n _managerEnabled = false;\n }\n return this;\n },\n};\n\n// -- helper functions\n\n/**\n * @param {Function} fn\n * @param {import('@opentelemetry/api').ContextManager} manager\n * @param {import('@opentelemetry/api').Context} context\n * @returns {Function}\n */\nfunction bindFn(fn, manager, context) {\n if (typeof fn !== 'function') {\n return fn;\n }\n const ctx = context || manager.active();\n function wrappedCtxFn(...args) {\n return manager.with(ctx, () => fn.apply(this, args));\n }\n Object.defineProperty(wrappedCtxFn, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: fn.length,\n });\n return wrappedCtxFn;\n}\n\n/**\n * Wraps the promise constructor so any new promises carry\n * the context in their sbsequent calls to `.then` and `.catch`\n * @param {import('@opentelemetry/api').ContextManager} manager\n */\nfunction wrapPromise(manager) {\n wrap(Promise.prototype, 'then', (origThen) => {\n return function (onResolved, onRejected) {\n return origThen.call(\n this,\n bindFn(onResolved, manager, manager.active()),\n bindFn(onRejected, manager, manager.active())\n );\n };\n });\n wrap(Promise.prototype, 'catch', (origCatch) => {\n return function (onRejected) {\n return origCatch.call(\n this,\n bindFn(onRejected, manager, manager.active())\n );\n };\n });\n wrap(Promise.prototype, 'finally', (origFinally) => {\n return function (onCompleted) {\n return origFinally.call(\n this,\n bindFn(onCompleted, manager, manager.active())\n );\n };\n });\n}\n\nfunction unwrapPromise() {\n unwrap(Promise.prototype, 'then');\n unwrap(Promise.prototype, 'catch');\n unwrap(Promise.prototype, 'finally');\n}\n\nconst xhrProps = ['onreadystatechange'];\nconst xhrProto = globalThis.XMLHttpRequest.prototype;\nconst xhrTargetProps = [\n 'onabort',\n 'onerror',\n 'onload',\n 'onloadend',\n 'onloadstart',\n 'onprogress',\n 'ontimeout',\n];\nconst xhrTargetProto = globalThis.XMLHttpRequestEventTarget.prototype;\n/**\n * We keep track of the event listeners on the same XHR instance that were\n * registered in a property named `__bound` so its easier to be cleared\n * and, therefore, garbage collected.\n * @param {import('@opentelemetry/api').ContextManager} manager\n */\nfunction wrapXMLHttpRequest(manager) {\n // Wrap events\n wrap(xhrProto, 'addEventListener', function (origAEL) {\n return function (...args) {\n const xhr = this;\n if (typeof args[1] === 'function') {\n xhr.__bound = xhr.__bound || new Map();\n const handler = args[1];\n const bound = xhr.__bound.get(handler);\n args[1] = bound || bindFn(handler, manager, manager.active());\n xhr.__bound.set(handler, args[1]);\n }\n return origAEL.apply(xhr, args);\n };\n });\n wrap(xhrProto, 'removeEventListener', function (origREL) {\n return function (...args) {\n const xhr = this;\n if (typeof args[1] === 'function') {\n const handler = args[1];\n const bound = xhr.__bound?.get(handler);\n if (bound) {\n args[1] = bound;\n // NOTE: this handler might be registered more than once\n // or for other event types so better to keep it in the map\n }\n }\n return origREL.apply(xhr, args);\n };\n });\n // Wrap on... properties of XMLHttpRequest.prototype\n for (const prop of xhrProps) {\n const descriptor = Object.getOwnPropertyDescriptor(xhrProto, prop);\n if (descriptor) {\n wrapDescriptor(descriptor, manager);\n Object.defineProperty(xhrProto, prop, descriptor);\n }\n }\n\n // Wrap onload, onerror, on... properties of XMLHttpRequestEventTarget.prototype\n for (const prop of xhrTargetProps) {\n const descriptor = Object.getOwnPropertyDescriptor(\n xhrTargetProto,\n prop\n );\n if (descriptor) {\n wrapDescriptor(descriptor, manager);\n Object.defineProperty(xhrTargetProto, prop, descriptor);\n }\n }\n}\n\nfunction unwrapXMLHttpRequest() {\n unwrap(xhrProto, 'addEventListener');\n unwrap(xhrProto, 'removeEventListener');\n // Unwrap onload, onerror, on... properties from:\n // - XMLHttpRequest.prototype\n // - XMLHttpRequestEventTarget.prototype\n for (const prop of xhrProps) {\n const descriptor = Object.getOwnPropertyDescriptor(xhrProto, prop);\n if (descriptor) {\n unwrap(descriptor, 'set');\n unwrap(descriptor, 'get');\n Object.defineProperty(xhrProto, prop, descriptor);\n }\n }\n for (const prop of xhrTargetProps) {\n const descriptor = Object.getOwnPropertyDescriptor(\n xhrTargetProto,\n prop\n );\n if (descriptor) {\n unwrap(descriptor, 'set');\n unwrap(descriptor, 'get');\n Object.defineProperty(xhrTargetProto, prop, descriptor);\n }\n }\n}\n\n// shimmer functions\nfunction wrap(nodule, name, wrapper) {\n if (!nodule || !nodule[name]) {\n logger.warn('no original function ' + String(name) + ' to wrap');\n return;\n }\n\n if (!wrapper) {\n logger.warn('no wrapper function');\n logger.warn(new Error().stack);\n return;\n }\n\n const original = nodule[name];\n\n if (typeof original !== 'function' || typeof wrapper !== 'function') {\n logger.warn('original object and wrapper must be functions');\n return;\n }\n\n const wrapped = wrapper(original, name);\n // Some frameworks check the `toString` to check if the function is native\n if (typeof original.toString === 'function') {\n wrapped.toString = original.toString.bind(original);\n }\n\n defineProperty(wrapped, '__original', original);\n defineProperty(wrapped, '__unwrap', () => {\n if (nodule[name] === wrapped) {\n defineProperty(nodule, name, original);\n }\n });\n defineProperty(wrapped, '__wrapped', true);\n defineProperty(nodule, name, wrapped);\n return wrapped;\n}\n\n// shimmer unwrap function\nfunction unwrap(nodule, name) {\n if (!nodule || !nodule[name]) {\n logger.warn('no function to unwrap.');\n logger.warn(new Error().stack);\n return;\n }\n\n const wrapped = nodule[name];\n if (!wrapped.__unwrap) {\n logger.warn(\n `no original to unwrap to -- has ${String(name)} already been unwrapped?`\n );\n } else {\n wrapped.__unwrap();\n return;\n }\n}\n\nfunction wrapDescriptor(descriptor, manager) {\n wrap(descriptor, 'set', function (origSet) {\n return function (value) {\n if (typeof value === 'function') {\n const origValue = value;\n value = bindFn(origValue, manager, manager.active());\n value.__original = origValue;\n }\n return origSet.call(this, value);\n };\n });\n wrap(descriptor, 'get', function (origGet) {\n return function () {\n const value = origGet.call(this);\n if (typeof value === 'function' && value.__original) {\n return value.__original;\n }\n return value;\n };\n });\n}\n\n/**\n * Sets a property on an object, preserving its enumerability.\n * This function assumes that the property is already writable.\n * @param {any} obj\n * @param {string | number | symbol} name\n * @param {unknown} value\n */\nfunction defineProperty(obj, name, value) {\n const enumerable =\n !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name);\n\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable,\n writable: true,\n value,\n });\n}\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Array of brand name and version separated by a space\n *\n * @example [\" Not A;Brand 99\", \"Chromium 99\", \"Chrome 99\"]\n *\n * @note This value is intended to be taken from the [UA client hints API](https://wicg.github.io/ua-client-hints/#interface) (`navigator.userAgentData.brands`).\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_BROWSER_BRANDS = 'browser.brands';\n\n/**\n * Preferred language of the user using the browser\n *\n * @example en\n * @example en-US\n * @example fr\n * @example fr-FR\n *\n * @note This value is intended to be taken from the Navigator API `navigator.language`.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_BROWSER_LANGUAGE = 'browser.language';\n\n/**\n * A boolean that is true if the browser is running on a mobile device\n *\n * @note This value is intended to be taken from the [UA client hints API](https://wicg.github.io/ua-client-hints/#interface) (`navigator.userAgentData.mobile`). If unavailable, this attribute **SHOULD** be left unset.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_BROWSER_MOBILE = 'browser.mobile';\n\n/**\n * The platform on which the browser is running\n *\n * @example Windows\n * @example macOS\n * @example Android\n *\n * @note This value is intended to be taken from the [UA client hints API](https://wicg.github.io/ua-client-hints/#interface) (`navigator.userAgentData.platform`). If unavailable, the legacy `navigator.platform` API **SHOULD NOT** be used instead and this attribute **SHOULD** be left unset in order for the values to be consistent.\n * The list of possible values is defined in the [W3C User-Agent Client Hints specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). Note that some (but not all) of these values can overlap with values in the [`os.type` and `os.name` attributes](./os.md). However, for consistency, the values in the `browser.platform` attribute should capture the exact value that the user agent provides.\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_BROWSER_PLATFORM = 'browser.platform';\n\n/**\n * This event describes the website performance metrics introduced by Google, See [web vitals](https://web.dev/vitals).\n *\n * @experimental This event is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const EVENT_BROWSER_WEB_VITAL = 'browser.web_vital';\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original';\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const EDOT_VERSION = '0.1.0';\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {resourceFromAttributes} from '@opentelemetry/resources';\nimport {SDK_INFO} from '@opentelemetry/core';\n\nimport {\n ATTR_BROWSER_BRANDS,\n ATTR_BROWSER_LANGUAGE,\n ATTR_BROWSER_MOBILE,\n ATTR_BROWSER_PLATFORM,\n ATTR_USER_AGENT_ORIGINAL,\n} from './semconv.js';\nimport {EDOT_VERSION} from './version.js';\n\n/**\n * @typedef {Object} UserAgentData\n * @property {{brand: string; version: string}[]} brands\n * @property {string} platform\n */\n\n/**\n * @template T\n * @typedef {T | Array<T | undefined | null>} MaybeArray<T>\n */\n/**\n * @typedef {MaybeArray<number> | MaybeArray<boolean> | MaybeArray<string>} AttributeValue\n */\n\n/**\n * @param {Record<string, AttributeValue>} attribs\n * @param {string | undefined} serviceName\n * @param {string | undefined} serviceVersion\n * @returns {import('@opentelemetry/resources').Resource}\n */\nexport function detectResource(attribs, serviceName, serviceVersion) {\n /** @type {MaybeArray<number>} */\n if (typeof serviceName === 'string' && serviceName) {\n attribs['service.name'] = serviceName;\n }\n if (typeof serviceVersion === 'string' && serviceVersion) {\n attribs['service.version'] = serviceVersion;\n }\n\n /** @type {Navigator & { userAgentData?: UserAgentData }} */\n const {userAgent, userAgentData} = navigator;\n const browserInfo = getBrowserInfo(userAgent);\n let platform;\n\n if (userAgentData) {\n platform = {name: userAgentData.platform, version: ''};\n attribs[ATTR_BROWSER_BRANDS] = userAgentData.brands.map(\n (i) => `${i.brand} ${i.version}`\n );\n } else {\n platform = getPlatformInfo(userAgent);\n }\n\n if (browserInfo) {\n attribs['browser.name'] = browserInfo.name;\n if (browserInfo.version) {\n attribs['browser.version'] = browserInfo.version;\n }\n }\n if (platform) {\n attribs[ATTR_BROWSER_PLATFORM] = platform.name;\n }\n\n attribs[ATTR_BROWSER_MOBILE] = navigator.userAgent.includes('Mobi');\n attribs[ATTR_BROWSER_LANGUAGE] = navigator.language;\n attribs[ATTR_USER_AGENT_ORIGINAL] = userAgent;\n attribs['telemetry.distro.name'] = 'elastic';\n attribs['telemetry.distro.version'] = EDOT_VERSION;\n\n // This might be usefull info\n // ['browser.touch_screen_enabled']: navigator.maxTouchPoints > 0,\n // ['network.effective_type']: navigator['networkInformation']?.effectiveType || 'unknown',\n // ['screen.width']: window.screen.width,\n // ['screen.height']: window.screen.height,\n // ['screen.size']: computeScreenSize(window.screen.width),\n\n return resourceFromAttributes({...attribs, ...SDK_INFO});\n}\n\n// -- helper functions\n// ref: https://mdn2.netlify.app/en-us/docs/web/http/browser_detection_using_the_user_agent/#which_part_of_the_user_agent_contains_the_information_you_are_looking_for\n\n/**\n * @param {string} userAgent\n * @returns {{name: string; version: string} | undefined}\n */\nexport function getPlatformInfo(userAgent) {\n /** @type {Array<[string,RegExp[]]>} */\n const platforms = [\n // {name: 'Firefox OS', test: /Firefox\\/([\\w\\.]+)?/i},\n ['Symbian', [/SymbianOS\\/([\\w\\.]+)/i]],\n ['Windows Phone', [/Windows Phone ([\\w\\.]+)/i]],\n ['Xbox', [/Xbox?/i]],\n ['Windows', [/Windows (\\d+)/i]],\n ['Windows RT', [/Windows NT ([\\w\\.]+).+ARM;/i]],\n ['Windows', [/Windows NT (\\d+\\.\\d+)/i]],\n ['Windows IoT', [/Windows IoT (\\d+\\.\\d+)/i]],\n ['iOS', [/iPhone OS (\\d+(_\\d+)*)/i, /iPad;.+CPU OS (\\d+(_\\d+)*)/i]],\n [\n 'macOS',\n [/Mac OS (\\d+(_\\d+)*)/i, /Mac OS X ([\\w\\.]+)/i, /Intel Mac OS X/],\n ],\n ['Ubuntu Touch', [/Ubuntu ([\\w\\.]+).+Mobile/i]],\n ['Android', [/Android ([\\w\\.]+)/i, /Android;/i]],\n ['Linux', [/Linux ([\\w_]+)/i, /Linux;/]],\n ];\n\n for (const p of platforms) {\n const [name, tests] = p;\n for (const t of tests) {\n const match = t.exec(userAgent);\n if (match) {\n let version;\n if (match[1]) {\n version = match[1].replaceAll('_', '.');\n }\n return {name, version};\n }\n }\n }\n}\n\n/**\n * @param {string} userAgent\n * @returns {{name: string; version: string | undefined} | undefined}\n */\nexport function getBrowserInfo(userAgent) {\n // note: only get the major version\n /** @type {Array<[string, RegExp[]]>} */\n const browsers = [\n // Branded or inapp browsers\n ['AliPay', [/AliPayClient\\/([\\w\\.]+)/i]],\n [\n 'Baidu',\n [\n /bd(?:browser|spark)\\/([\\w\\.]+)/i,\n /baidu(?:boxapp|hd)\\/([\\w\\.]+)/i,\n /BIDUBrowser\\/([\\w\\.]+)/i,\n ],\n ],\n ['Bing', [/Bing(?:Web|Sapphire)\\/([\\w\\.]+)/i]],\n ['Camino', [/Camino\\/([\\w\\.]+)/i]],\n ['Coc Coc', [/coc_coc_browser\\/([\\w\\.]+)/i]],\n ['Dragon', [/(?:Dragon|Comodo_Dragon)\\/([\\w\\.]+)/i]],\n ['DuckDuckGo', [/(?:Ddg|DuckDuckGo)\\/([\\w\\.]+)/i]],\n ['Electron', [/Electron\\/([\\w\\.]+)/i]],\n ['Facebook', [/;fbav\\/([\\w\\.]+);/i, /(?:fban\\/fbios|fb_iab\\/fb4a)/i]],\n ['GSA', [/GSA\\/([\\w\\.]+)/i]],\n ['Huawei Browser', [/HuaweiBrowser\\/([\\w\\.]+)/i]],\n ['Iron', [/(?:Iron|Iron Safari)\\/([\\w\\.]+)/i]],\n ['LG Browser', [/LG Browser\\/([\\w\\.]+)/i]],\n ['Lunascape', [/Lunascape\\/([\\w\\.]+)/i]],\n ['Maxthon', [/Maxthon\\/([\\w\\.]+)/i, /Mx(?:Browser|iOS)\\/([\\w\\.]+)/i]],\n ['MIUI Browser', [/MiuiBrowser\\/([\\w\\.]+)/i]],\n ['NokiaBrowser', [/NokiaBrowser\\/([\\w\\.]+)/i]],\n ['Oculus Browser', [/OculusBrowser\\/([\\w\\.]+)/i]],\n ['Pico Browser', [/PicoBrowser\\/([\\w\\.]+)/i]],\n ['Qwant', [/Qwant(?:Mobile|Browser|iOS)\\/([\\w\\.]+)/i]],\n ['Samsung Internet', [/SamsungBrowser\\/([\\w\\.]+)/i]],\n ['Silk', [/Silk\\/([\\w\\.]+)/i]],\n ['Smart Lenovo Browser', [/SLBrowser\\/([\\w\\.]+)/i]],\n ['Snapchat', [/Snapchat\\/([\\w\\.]+)/i]],\n ['Steam', [/Valve Steam/i]],\n ['TikTok', [/musical_ly.+app_version\\/([\\w\\.]+)/i]],\n ['Twitter', [/Twitter/i]],\n ['Vivaldi', [/Vivaldi\\/([\\w\\.]+)/i]],\n ['Yandex', [/Ya(?:SearchBrowser|Browser)\\/([\\w\\.]+)/i]],\n [\n 'WeChat',\n [\n /microm.+\\bqbcore\\/([\\w\\.]+)/i,\n /\\bqbcore\\/([\\w\\.]+).+microm/i,\n /micromessenger\\/([\\w\\.]+)/i,\n ],\n ],\n // Some wechat UAs contain qqbrowser so this should be last\n ['QQBrowser', [/M?QQbrowser\\/([\\w\\.]+)/i]],\n\n // The usual suspects\n ['Brave', [/Brave\\/([\\w\\.]+)/i]],\n ['Edge', [/(?:Edg|Edge|EdgA|EdgW|EdgiOS)\\/([\\w\\.]+)/i]],\n ['Opera', [/(?:OPR|OPT|OPiOS|Opera)\\/([\\w\\.]+)/i, /Coast\\/([\\w\\.]+)/i]],\n ['Chromium', [/Chromium\\/([\\w\\.]+)/i]],\n [\n 'Chrome Headless',\n [/HeadlessChrome\\/([\\w\\.]+)/i, /HeadlessChrome Safari\\/([\\w\\.]+)/i],\n ],\n ['Chrome', [/Chrome\\/([\\w\\.]+)/i, /Cr(?:iOS|Mo)\\/([\\w\\.]+)/i]],\n ['Android Browser', [/Android \\d.+Safari\\/([\\w\\.]+)/i]],\n ['Firefox', [/(?:Firefox|FxiOS)\\/([\\w\\.]+)/i]],\n ['Safari', [/Safari\\/([\\w\\.]+)/i]],\n ];\n\n for (const b of browsers) {\n const [name, tests] = b;\n for (const t of tests) {\n const match = t.exec(userAgent);\n if (match) {\n let version;\n if (match[1]) {\n version = match[1].replaceAll('_', '.');\n }\n return {name, version};\n }\n }\n }\n}\n\n// /**\n// * @param {number} screenWidth\n// * @returns {'small' | 'medium' | 'large' | 'unknown'}\n// */\n// function computeScreenSize (screenWidth) {\n// if (screenWidth <= 768) return 'small';\n// else if (screenWidth > 768 && screenWidth <= 1024) return 'medium';\n// else if (screenWidth > 1024) return 'large';\n\n// return 'unknown';\n// };\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {diag, DiagLogLevel, metrics} from '@opentelemetry/api';\nimport {logs} from '@opentelemetry/api-logs';\nimport {OTLPLogExporter} from '@opentelemetry/exporter-logs-otlp-http';\nimport {OTLPMetricExporter} from '@opentelemetry/exporter-metrics-otlp-http';\nimport {OTLPTraceExporter} from '@opentelemetry/exporter-trace-otlp-http';\nimport {BatchLogRecordProcessor, LoggerProvider} from '@opentelemetry/sdk-logs';\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n} from '@opentelemetry/sdk-metrics';\nimport {\n BatchSpanProcessor,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace-base';\nimport {WebTracerProvider} from '@opentelemetry/sdk-trace-web';\n\nimport {registerInstrumentations} from '@opentelemetry/instrumentation';\nimport {DocumentLoadInstrumentation} from '@opentelemetry/instrumentation-document-load';\nimport {FetchInstrumentation} from '@opentelemetry/instrumentation-fetch';\nimport {LongTaskInstrumentation} from '@opentelemetry/instrumentation-long-task';\nimport {UserInteractionInstrumentation} from '@opentelemetry/instrumentation-user-interaction';\nimport {XMLHttpRequestInstrumentation} from '@opentelemetry/instrumentation-xml-http-request';\nimport {ExceptionInstrumentation} from '@opentelemetry/instrumentation-web-exception';\nimport {WebVitalsInstrumentation} from '@opentelemetry/browser-instrumentation/experimental/web-vitals';\n\nimport {AsyncApisContextManager} from './context.js';\nimport {createLogger} from './logging.js';\nimport {detectResource} from './detector.js';\n\n/**\n * @typedef {{\n * \"@opentelemetry/instrumentation-document-load\": import('@opentelemetry/instrumentation-document-load').DocumentLoadInstrumentationConfig;\n * \"@opentelemetry/instrumentation-fetch\": import('@opentelemetry/instrumentation-fetch').FetchInstrumentationConfig;\n * \"@opentelemetry/instrumentation-long-task\": import('@opentelemetry/instrumentation-long-task').LongtaskInstrumentationConfig;\n * \"@opentelemetry/instrumentation-user-interaction\": import('@opentelemetry/instrumentation-user-interaction').UserInteractionInstrumentationConfig;\n * \"@opentelemetry/instrumentation-xml-http-request\": import('@opentelemetry/instrumentation-xml-http-request').XMLHttpRequestInstrumentationConfig;\n * \"@opentelemetry/instrumentation-web-exception\": import('@opentelemetry/instrumentation-web-exception').GlobalErrorsInstrumentationConfig;\n * \"@opentelemetry/instrumentation-web-vitals\": import('@opentelemetry/browser-instrumentation/experimental/web-vitals').WebVitalsInstrumentationConfig;\n * }} InstrumentationsConfigMap\n */\n\n/**\n * @typedef {Object} BrowserSdkConfiguration\n * @property {boolean} [disabled]\n * @property {string} [serviceName]\n * @property {string} [serviceVersion]\n * @property {string} [logLevel] // defaults to 'info'\n * @property {number} [sampleRate] // defaults to 1\n * @property {Record<string, import('./detector.js').AttributeValue>} [resourceAttributes]\n * @property {string} [otlpEndpoint] // defaults to 'http://localhost:4318'\n * @property {Record<string, string>} [exportHeaders] // defaults to {}\n *\n * // other options\n * @property {Partial<InstrumentationsConfigMap>} [instrumentations]\n */\n\n// To control multiple calls to `startBrowserSdk`\nlet sdkStarted = false;\n\n/** @type {BrowserSdkConfiguration} */\nconst defaultConfig = {\n logLevel: 'info',\n sampleRate: 1,\n serviceName: 'unknown_service:web',\n resourceAttributes: {},\n otlpEndpoint: 'http://localhost:4318',\n exportHeaders: {},\n};\n\n/**\n * @param {BrowserSdkConfiguration} cfg\n * @returns {{\n * forceFlush: () => Promise<void>\n * }}\n */\nexport function startBrowserSdk(cfg = {}) {\n if (sdkStarted || cfg.disabled) {\n return;\n }\n\n const logLevel = cfg.logLevel ?? defaultConfig.logLevel;\n diag.setLogger(createLogger({logLevel}), {logLevel: DiagLogLevel.ALL});\n diag.debug(`Browser SDK intialization`, cfg);\n\n const {serviceName, serviceVersion} = cfg;\n const config = {...defaultConfig, ...cfg};\n\n // Input validation\n /** @type {URL} */\n let endpointUrl;\n try {\n endpointUrl = new URL(config.otlpEndpoint);\n } catch (urlErr) {\n diag.error(\n `The value \"${config.otlpEndpoint}\" for \"otlpEndpoint\" configuration is not an URL. SDK won't start.`\n );\n return;\n }\n\n // Detect resource\n const resource = detectResource(\n config.resourceAttributes,\n serviceName,\n serviceVersion\n );\n\n // NOTE: export payloads can be seen in DevTools network tab in JSON format\n // so IMHO it would be redundant to use console exporters\n\n // traces signal configuration\n const tracesEndpoint = appendPath(endpointUrl, 'v1/traces').href;\n const spanProcessor = new BatchSpanProcessor(\n new OTLPTraceExporter({\n url: tracesEndpoint,\n headers: config.exportHeaders,\n })\n );\n const tracerProvider = new WebTracerProvider({\n resource,\n sampler: new TraceIdRatioBasedSampler(config.sampleRate),\n spanProcessors: [spanProcessor],\n });\n // TODO: WebTracerProvider comes with\n // - a composite propagator [W3C, Baggage]\n // - a context manager (Stack, which has issues with exporters)\n // Should we allow users to pass their own propagator, contextmanager?\n tracerProvider.register({\n contextManager: AsyncApisContextManager,\n });\n // ideally it shoud be\n // trace.setGlobalTracerProvider(tracerProvider);\n // but there is no way to set propagators and context manager\n\n // metrics signal configuration\n const metricsEndpoint = appendPath(endpointUrl, 'v1/metrics').href;\n const metricsReader = new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: metricsEndpoint,\n headers: config.exportHeaders,\n }),\n });\n const meterProvider = new MeterProvider({\n resource,\n readers: [metricsReader],\n });\n metrics.setGlobalMeterProvider(meterProvider);\n\n // logs signal configuration\n const logsEndpoint = appendPath(endpointUrl, 'v1/logs').href;\n const logsProcessor = new BatchLogRecordProcessor(\n new OTLPLogExporter({\n url: logsEndpoint,\n headers: config.exportHeaders,\n })\n );\n const loggerProvider = new LoggerProvider({\n resource,\n processors: [logsProcessor],\n });\n logs.setGlobalLoggerProvider(loggerProvider);\n\n // Resgister instrumentations. The `registerInstrumentations` enabled all of them\n // regardless of the configuration so EDOT only add the ones that are not disabled\n // by configuration\n /** @type {Record<keyof InstrumentationsConfigMap, (cfg: any) => any>} */\n const instrFactories = {\n '@opentelemetry/instrumentation-document-load': (cfg) =>\n new DocumentLoadInstrumentation(cfg),\n '@opentelemetry/instrumentation-fetch': (cfg) =>\n new FetchInstrumentation(cfg),\n '@opentelemetry/instrumentation-long-task': (cfg) =>\n new LongTaskInstrumentation(cfg),\n '@opentelemetry/instrumentation-user-interaction': (cfg) =>\n new UserInteractionInstrumentation(cfg),\n '@opentelemetry/instrumentation-xml-http-request': (cfg) =>\n new XMLHttpRequestInstrumentation(cfg),\n '@opentelemetry/instrumentation-web-exception': (cfg) =>\n new ExceptionInstrumentation(cfg),\n '@opentelemetry/instrumentation-web-vitals': (cfg) =>\n new WebVitalsInstrumentation(cfg),\n };\n\n const httpSemconvConfig = {semconvStabilityOptIn: 'http'};\n const instrumentations = config.instrumentations || {};\n const enabledInstrumentations = [];\n for (const key of Object.keys(instrFactories)) {\n let instrConfig = instrumentations[key];\n if (\n key === '@opentelemetry/instrumentation-fetch' ||\n key === '@opentelemetry/instrumentation-xml-http-request'\n ) {\n instrConfig = {...httpSemconvConfig, ...instrConfig};\n }\n\n const isDisabled = instrConfig?.enabled === false;\n if (!isDisabled) {\n enabledInstrumentations.push(instrFactories[key](instrConfig));\n }\n }\n registerInstrumentations({instrumentations: enabledInstrumentations});\n\n // Flag as started\n sdkStarted = true;\n\n return {\n forceFlush() {\n return Promise.all([\n tracerProvider.forceFlush(),\n meterProvider.forceFlush(),\n loggerProvider.forceFlush(),\n ]).then(() => {});\n },\n };\n}\n\n// -- helper functions\n\n/**\n * Returns a new URL with the path appended. Avoiding double slash\n * @param {URL} url\n * @param {string} path\n */\nfunction appendPath(url, path) {\n const result = new URL(url.href);\n result.pathname = (result.pathname + path).replace('//', '/');\n return result;\n}\n", "/*\n * Copyright Elasticsearch B.V. and contributors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {startBrowserSdk} from './sdk.js';\n\nglobalThis['startBrowserSdk'] = startBrowserSdk;\n"],
|
|
5
|
+
"mappings": "MA4BO,IAAMA,GACX,OAAO,YAAe,SAClB,WACA,OAAO,MAAS,SAChB,KACA,OAAO,QAAW,SAClB,OACA,OAAO,QAAW,SAClB,OACC,CAAA,ECpBA,IAAMC,GAAU,QCCvB,IAAMC,GAAK,gCAkBL,SAAUC,GACdC,EAAkB,CAElB,IAAMC,EAAmB,IAAI,IAAY,CAACD,CAAU,CAAC,EAC/CE,EAAmB,IAAI,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C,CAAG,EACnC,kDAAoDA,GAChD,IAAIsC,GAA+BtC,CAAG,EAC1C,kDAAoDA,GAChD,IAAIuC,GAA8BvC,CAAG,EACzC,+CAAiDA,GAC7C,IAAIwC,GAAyBxC,CAAG,EACpC,4CAA8CA,GAC1C,IAAIyC,GAAyBzC,CAAG,CACxC,EAEM0C,EAAoB,CAAC,sBAAuB,MAAM,EAClDC,EAAmBpC,EAAO,kBAAoB,CAAC,EAC/CqC,EAA0B,CAAC,EACjC,QAAWC,KAAO,OAAO,KAAKX,CAAc,EAAG,CAC3C,IAAIY,EAAcH,EAAiBE,CAAG,GAElCA,IAAQ,wCACRA,IAAQ,qDAERC,EAAc,CAAC,GAAGJ,EAAmB,GAAGI,CAAW,GAGpCA,GAAa,UAAY,IAExCF,EAAwB,KAAKV,EAAeW,CAAG,EAAEC,CAAW,CAAC,CAErE,CACA,OAAAC,GAAyB,CAAC,iBAAkBH,CAAuB,CAAC,EAGpE/C,GAAa,GAEN,CACH,YAAa,CACT,OAAO,QAAQ,IAAI,CACfmB,EAAe,WAAW,EAC1BQ,EAAc,WAAW,EACzBO,EAAe,WAAW,CAC9B,CAAC,EAAE,KAAK,IAAM,CAAC,CAAC,CACpB,CACJ,CACJ,CASA,SAASnB,GAAWoC,EAAKC,EAAM,CAC3B,IAAMC,EAAS,IAAI,IAAIF,EAAI,IAAI,EAC/B,OAAAE,EAAO,UAAYA,EAAO,SAAWD,GAAM,QAAQ,KAAM,GAAG,EACrDC,CACX,CChOA,WAAW,gBAAqBC",
|
|
6
|
+
"names": ["_globalThis", "VERSION", "re", "_makeCompatibilityCheck", "ownVersion", "acceptedVersions", "rejectedVersions", "myVersionMatch", "ownVersionParsed", "globalVersion", "_reject", "v", "_accept", "globalVersionMatch", "globalVersionParsed", "isCompatible", "VERSION", "major", "VERSION", "GLOBAL_OPENTELEMETRY_API_KEY", "_global", "_globalThis", "registerGlobal", "type", "instance", "diag", "allowOverride", "api", "_a", "err", "getGlobal", "globalVersion", "isCompatible", "_b", "unregisterGlobal", "DiagComponentLogger", "props", "args", "_i", "logProxy", "logProxy", "funcName", "namespace", "args", "logger", "getGlobal", "__spreadArray", "__read", "DiagLogLevel", "createLogLevelDiagLogger", "maxLevel", "logger", "DiagLogLevel", "_filterFunc", "funcName", "theLevel", "theFunc", "API_NAME", "DiagAPI", "_logProxy", "funcName", "args", "_i", "logger", "getGlobal", "__spreadArray", "__read", "self", "setLogger", "optionsOrLogLevel", "DiagLogLevel", "err", "_a", "oldLogger", "newLogger", "createLogLevelDiagLogger", "_b", "stack", "_c", "registerGlobal", "unregisterGlobal", "options", "DiagComponentLogger", "BaggageImpl", "entries", "key", "entry", "_a", "_b", "__read", "k", "v", "newBaggage", "keys", "_i", "keys_1", "__values", "keys_1_1", "baggageEntryMetadataSymbol", "diag", "DiagAPI", "createBaggage", "entries", "BaggageImpl", "baggageEntryMetadataFromString", "str", "baggageEntryMetadataSymbol", "createContextKey", "description", "BaseContext", "parentContext", "self", "key", "value", "context", "ROOT_CONTEXT", "NoopMeter", "_name", "_options", "NOOP_GAUGE_METRIC", "NOOP_HISTOGRAM_METRIC", "NOOP_COUNTER_METRIC", "NOOP_UP_DOWN_COUNTER_METRIC", "NOOP_OBSERVABLE_GAUGE_METRIC", "NOOP_OBSERVABLE_COUNTER_METRIC", "NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC", "_callback", "_observables", "NoopMetric", "NoopCounterMetric", "_super", "__extends", "_value", "_attributes", "NoopMetric", "NoopUpDownCounterMetric", "_super", "__extends", "_value", "_attributes", "NoopMetric", "NoopGaugeMetric", "_super", "__extends", "_value", "_attributes", "NoopMetric", "NoopHistogramMetric", "_super", "__extends", "_value", "_attributes", "NoopMetric", "NoopObservableMetric", "_callback", "NoopObservableCounterMetric", "_super", "__extends", "NoopObservableMetric", "NoopObservableGaugeMetric", "_super", "__extends", "NoopObservableMetric", "NoopObservableUpDownCounterMetric", "_super", "__extends", "NoopObservableMetric", "NOOP_METER", "NoopMeter", "NOOP_COUNTER_METRIC", "NoopCounterMetric", "NOOP_GAUGE_METRIC", "NoopGaugeMetric", "NOOP_HISTOGRAM_METRIC", "NoopHistogramMetric", "NOOP_UP_DOWN_COUNTER_METRIC", "NoopUpDownCounterMetric", "NOOP_OBSERVABLE_COUNTER_METRIC", "NoopObservableCounterMetric", "NOOP_OBSERVABLE_GAUGE_METRIC", "NoopObservableGaugeMetric", "NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC", "NoopObservableUpDownCounterMetric", "createNoopMeter", "ValueType", "defaultTextMapGetter", "carrier", "key", "defaultTextMapSetter", "value", "NoopContextManager", "ROOT_CONTEXT", "_context", "fn", "thisArg", "args", "_i", "__spreadArray", "__read", "target", "API_NAME", "NOOP_CONTEXT_MANAGER", "NoopContextManager", "ContextAPI", "contextManager", "registerGlobal", "DiagAPI", "context", "fn", "thisArg", "args", "_i", "_a", "__spreadArray", "__read", "target", "getGlobal", "unregisterGlobal", "TraceFlags", "INVALID_SPANID", "INVALID_TRACEID", "INVALID_SPAN_CONTEXT", "TraceFlags", "NonRecordingSpan", "_spanContext", "INVALID_SPAN_CONTEXT", "_key", "_value", "_attributes", "_name", "_link", "_links", "_status", "_endTime", "_exception", "_time", "SPAN_KEY", "createContextKey", "getSpan", "context", "getActiveSpan", "ContextAPI", "setSpan", "span", "deleteSpan", "setSpanContext", "spanContext", "NonRecordingSpan", "getSpanContext", "_a", "VALID_TRACEID_REGEX", "VALID_SPANID_REGEX", "isValidTraceId", "traceId", "INVALID_TRACEID", "isValidSpanId", "spanId", "INVALID_SPANID", "isSpanContextValid", "spanContext", "wrapSpanContext", "NonRecordingSpan", "contextApi", "ContextAPI", "NoopTracer", "name", "options", "context", "root", "NonRecordingSpan", "parentFromContext", "getSpanContext", "isSpanContext", "isSpanContextValid", "arg2", "arg3", "arg4", "opts", "ctx", "fn", "parentContext", "span", "contextWithSpanSet", "setSpan", "isSpanContext", "spanContext", "NOOP_TRACER", "NoopTracer", "ProxyTracer", "_provider", "name", "version", "options", "context", "_name", "_options", "_context", "_fn", "tracer", "NoopTracerProvider", "_name", "_version", "_options", "NoopTracer", "NOOP_TRACER_PROVIDER", "NoopTracerProvider", "ProxyTracerProvider", "name", "version", "options", "_a", "ProxyTracer", "delegate", "SamplingDecision", "SpanKind", "SpanStatusCode", "context", "ContextAPI", "diag", "DiagAPI", "NoopMeterProvider", "_name", "_version", "_options", "NOOP_METER", "NOOP_METER_PROVIDER", "NoopMeterProvider", "API_NAME", "MetricsAPI", "provider", "registerGlobal", "DiagAPI", "getGlobal", "NOOP_METER_PROVIDER", "name", "version", "options", "unregisterGlobal", "metrics", "MetricsAPI", "NoopTextMapPropagator", "_context", "_carrier", "context", "BAGGAGE_KEY", "createContextKey", "getBaggage", "context", "getActiveBaggage", "ContextAPI", "setBaggage", "baggage", "deleteBaggage", "API_NAME", "NOOP_TEXT_MAP_PROPAGATOR", "NoopTextMapPropagator", "PropagationAPI", "createBaggage", "getBaggage", "getActiveBaggage", "setBaggage", "deleteBaggage", "propagator", "registerGlobal", "DiagAPI", "context", "carrier", "setter", "defaultTextMapSetter", "getter", "defaultTextMapGetter", "unregisterGlobal", "getGlobal", "propagation", "PropagationAPI", "API_NAME", "TraceAPI", "ProxyTracerProvider", "wrapSpanContext", "isSpanContextValid", "deleteSpan", "getSpan", "getActiveSpan", "getSpanContext", "setSpan", "setSpanContext", "provider", "success", "registerGlobal", "DiagAPI", "getGlobal", "name", "version", "unregisterGlobal", "trace", "TraceAPI", "SeverityNumber", "NoopLogger", "_logRecord", "NOOP_LOGGER", "GLOBAL_LOGS_API_KEY", "_global", "makeGetter", "requiredVersion", "instance", "fallback", "version", "API_BACKWARDS_COMPATIBILITY_VERSION", "NoopLoggerProvider", "_name", "_version", "_options", "NoopLogger", "NOOP_LOGGER_PROVIDER", "ProxyLogger", "provider", "name", "version", "options", "logRecord", "logger", "NOOP_LOGGER", "ProxyLoggerProvider", "name", "version", "options", "_a", "ProxyLogger", "NOOP_LOGGER_PROVIDER", "delegate", "LogsAPI", "_LogsAPI", "ProxyLoggerProvider", "provider", "_global", "GLOBAL_LOGS_API_KEY", "makeGetter", "API_BACKWARDS_COMPATIBILITY_VERSION", "NOOP_LOGGER_PROVIDER", "_b", "_a", "name", "version", "options", "logs", "LogsAPI", "OTLPExporterBase", "delegate", "items", "resultCallback", "OTLPExporterError", "message", "code", "data", "validateTimeoutMillis", "timeoutMillis", "wrapStaticHeadersInFunction", "headers", "mergeOtlpSharedConfigurationWithDefaults", "userProvidedConfiguration", "fallbackConfiguration", "defaultConfiguration", "getSharedConfigurationDefaults", "BoundedQueueExportPromiseHandler", "concurrencyLimit", "promise", "popPromise", "index", "createBoundedQueueExportPromiseHandler", "options", "SUPPRESS_TRACING_KEY", "createContextKey", "suppressTracing", "context", "isTracingSuppressed", "context", "SUPPRESS_TRACING_KEY", "BAGGAGE_HEADER", "serializeKeyPairs", "keyPairs", "hValue", "current", "value", "getKeyPairs", "baggage", "key", "entry", "parsePairKeyValue", "metadataSeparatorIndex", "keyPairPart", "separatorIndex", "rawKey", "rawValue", "metadata", "metadataString", "baggageEntryMetadataFromString", "W3CBaggagePropagator", "context", "carrier", "setter", "baggage", "propagation", "isTracingSuppressed", "keyPairs", "getKeyPairs", "pair", "headerValue", "serializeKeyPairs", "BAGGAGE_HEADER", "getter", "baggageString", "entry", "keyPair", "parsePairKeyValue", "baggageEntry", "sanitizeAttributes", "attributes", "out", "key", "isAttributeKey", "diag", "val", "isAttributeValue", "isHomogeneousAttributeValueArray", "isValidPrimitiveAttributeValueType", "arr", "type", "element", "elementType", "valType", "loggingErrorHandler", "ex", "diag", "stringifyException", "flattenException", "result", "current", "propertyName", "value", "delegateHandler", "loggingErrorHandler", "globalErrorHandler", "ex", "delegateHandler", "VERSION", "ATTR_ERROR_TYPE", "ATTR_EXCEPTION_MESSAGE", "ATTR_EXCEPTION_STACKTRACE", "ATTR_EXCEPTION_TYPE", "ATTR_HTTP_REQUEST_METHOD", "ATTR_HTTP_REQUEST_METHOD_ORIGINAL", "ATTR_HTTP_RESPONSE_STATUS_CODE", "ATTR_SERVER_ADDRESS", "ATTR_SERVER_PORT", "ATTR_SERVICE_NAME", "ATTR_TELEMETRY_SDK_LANGUAGE", "TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS", "ATTR_TELEMETRY_SDK_NAME", "ATTR_TELEMETRY_SDK_VERSION", "ATTR_URL_FULL", "ATTR_USER_AGENT_ORIGINAL", "ATTR_PROCESS_RUNTIME_NAME", "SDK_INFO", "ATTR_TELEMETRY_SDK_NAME", "ATTR_PROCESS_RUNTIME_NAME", "ATTR_TELEMETRY_SDK_LANGUAGE", "TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS", "ATTR_TELEMETRY_SDK_VERSION", "VERSION", "otperformance", "NANOSECOND_DIGITS", "NANOSECOND_DIGITS_IN_MILLIS", "MILLISECONDS_TO_NANOSECONDS", "SECOND_TO_NANOSECONDS", "millisToHrTime", "epochMillis", "epochSeconds", "seconds", "nanos", "hrTime", "performanceNow", "timeOrigin", "millisToHrTime", "otperformance", "now", "addHrTimes", "timeInputToHrTime", "time", "isTimeInputHrTime", "hrTimeDuration", "startTime", "endTime", "seconds", "nanos", "SECOND_TO_NANOSECONDS", "hrTimeToNanoseconds", "time", "SECOND_TO_NANOSECONDS", "hrTimeToMicroseconds", "time", "isTimeInputHrTime", "value", "isTimeInput", "addHrTimes", "time1", "time2", "out", "SECOND_TO_NANOSECONDS", "ExportResultCode", "CompositePropagator", "config", "p", "x", "y", "context", "carrier", "setter", "propagator", "err", "diag", "getter", "ctx", "VALID_KEY_CHAR_RANGE", "VALID_KEY", "VALID_VENDOR_KEY", "VALID_KEY_REGEX", "VALID_VALUE_BASE_REGEX", "INVALID_VALUE_COMMA_EQUAL_REGEX", "validateKey", "key", "validateValue", "value", "MAX_TRACE_STATE_ITEMS", "MAX_TRACE_STATE_LEN", "LIST_MEMBERS_SEPARATOR", "LIST_MEMBER_KEY_VALUE_SPLITTER", "TraceState", "_TraceState", "rawTraceState", "key", "value", "traceState", "agg", "part", "listMember", "validateKey", "validateValue", "TRACE_PARENT_HEADER", "TRACE_STATE_HEADER", "VERSION", "VERSION_PART", "TRACE_ID_PART", "PARENT_ID_PART", "FLAGS_PART", "TRACE_PARENT_REGEX", "parseTraceParent", "traceParent", "match", "W3CTraceContextPropagator", "context", "carrier", "setter", "spanContext", "trace", "isTracingSuppressed", "isSpanContextValid", "TraceFlags", "getter", "traceParentHeader", "traceStateHeader", "state", "TraceState", "objectTag", "nullTag", "undefinedTag", "funcProto", "funcToString", "objectCtorString", "getPrototypeOf", "objectProto", "hasOwnProperty", "symToStringTag", "nativeObjectToString", "isPlainObject", "value", "isObjectLike", "baseGetTag", "proto", "Ctor", "getRawTag", "objectToString", "isOwn", "tag", "unmasked", "result", "MAX_LEVEL", "merge", "args", "result", "objects", "mergeTwoObjects", "takeValue", "value", "isArray", "one", "two", "level", "isPrimitive", "isFunction", "j", "isObject", "keys", "i", "key", "shouldMerge", "twoValue", "obj1", "obj2", "wasObjectReferenced", "arr1", "arr2", "obj", "arr", "info", "isPlainObject", "TimeoutError", "_TimeoutError", "message", "callWithTimeout", "promise", "timeout", "timeoutHandle", "timeoutPromise", "_resolve", "reject", "result", "reason", "urlMatches", "url", "urlToMatch", "isUrlIgnored", "ignoredUrls", "ignoreUrl", "Deferred", "resolve", "reject", "val", "err", "BindOnceFuture", "Deferred", "callback", "that", "args", "val", "err", "_export", "exporter", "arg", "resolve", "context", "suppressTracing", "internal", "_export", "isPartialSuccessResponse", "response", "createLoggingPartialSuccessResponseHandler", "diag", "OTLPExportDelegate", "transport", "serializer", "responseHandler", "promiseQueue", "timeout", "diag", "internalRepresentation", "resultCallback", "ExportResultCode", "serializedRequest", "response", "e", "OTLPExporterError", "reason", "createOtlpExportDelegate", "components", "settings", "createLoggingPartialSuccessResponseHandler", "createOtlpNetworkExportDelegate", "options", "serializer", "transport", "createOtlpExportDelegate", "createBoundedQueueExportPromiseHandler", "createResource", "resource", "encoder", "result", "toAttributes", "schemaUrl", "createInstrumentationScope", "scope", "attributes", "key", "toKeyValue", "value", "toAnyValue", "t", "values", "i", "keys", "createExportLogsServiceRequest", "logRecords", "encoder", "logRecordsToResourceLogs", "createResourceMap", "resourceMap", "record", "resource", "name", "version", "schemaUrl", "ismMap", "ismKey", "records", "processedResource", "createResource", "scopeLogs", "createInstrumentationScope", "log", "toLogRecord", "toAnyValue", "toLogAttributes", "toLogAttributes", "attributes", "encoder", "key", "toKeyValue", "hrTimeToNanos", "hrTime", "NANOSECONDS", "encodeAsString", "hrTime", "hrTimeToNanos", "encodeTimestamp", "hrTimeToNanoseconds", "identity", "value", "JSON_ENCODER", "encodeTimestamp", "identity", "bytes", "chars", "i", "AggregationTemporality", "InstrumentType", "DataPointType", "hashAttributes", "attributes", "keys", "key", "instrumentationScopeId", "instrumentationScope", "TimeoutError", "_TimeoutError", "message", "callWithTimeout", "promise", "timeout", "timeoutHandle", "timeoutPromise", "_resolve", "reject", "result", "reason", "setEquals", "lhs", "rhs", "item", "binarySearchUB", "arr", "value", "lo", "hi", "ret", "mid", "equalsCaseInsensitive", "AggregatorKind", "DropAggregator", "AggregatorKind", "_previous", "_delta", "_current", "_descriptor", "_aggregationTemporality", "_accumulationByAttributes", "_endTime", "createNewEmptyCheckpoint", "boundaries", "counts", "HistogramAccumulation", "startTime", "recordMinMax", "current", "value", "idx", "binarySearchUB", "HistogramAggregator", "AggregatorKind", "previous", "delta", "previousValue", "deltaValue", "previousCounts", "deltaCounts", "mergedCounts", "min", "max", "currentValue", "currentCounts", "diffedCounts", "descriptor", "aggregationTemporality", "accumulationByAttributes", "endTime", "DataPointType", "attributes", "accumulation", "pointValue", "allowsNegativeValues", "InstrumentType", "Buckets", "_Buckets", "backing", "BucketsBacking", "indexBase", "indexStart", "indexEnd", "_", "i", "position", "bias", "bucketIndex", "increment", "decrement", "by", "size", "each", "inpos", "outpos", "pos", "mod", "dest", "src", "_BucketsBacking", "counts", "newSize", "oldPositiveLimit", "newPositiveLimit", "tmp", "from", "limit", "num", "MIN_VALUE", "getNormalBase2", "value", "dv", "getSignificand", "hiBits", "loBits", "ldexp", "frac", "exp", "nextGreaterSquare", "v", "MappingError", "ExponentMapping", "scale", "value", "MIN_VALUE", "exp", "getNormalBase2", "correction", "getSignificand", "index", "minIndex", "MappingError", "maxIndex", "ldexp", "shift", "LogarithmMapping", "scale", "ldexp", "value", "MIN_VALUE", "getSignificand", "getNormalBase2", "index", "maxIndex", "MappingError", "minIndex", "MIN_SCALE", "MAX_SCALE", "PREBUILT_MAPPINGS", "_", "i", "LogarithmMapping", "ExponentMapping", "getMapping", "scale", "MappingError", "HighLow", "_HighLow", "h1", "h2", "low", "high", "MAX_SCALE", "DEFAULT_MAX_SIZE", "MIN_MAX_SIZE", "ExponentialHistogramAccumulation", "_ExponentialHistogramAccumulation", "startTime", "maxSize", "recordMinMax", "sum", "count", "zeroCount", "min", "max", "positive", "Buckets", "negative", "mapping", "getMapping", "diag", "value", "increment", "previous", "minScale", "other", "buckets", "index", "rescalingNeeded", "change", "span", "bucketIndex", "needed", "size", "bias", "oldPositiveLimit", "newSize", "nextGreaterSquare", "newPositiveLimit", "newScale", "highLowPos", "highLowNeg", "currentScale", "shift", "ours", "theirs", "scale", "theirOffset", "theirChange", "i", "ExponentialHistogramAggregator", "AggregatorKind", "delta", "result", "current", "descriptor", "aggregationTemporality", "accumulationByAttributes", "endTime", "DataPointType", "attributes", "accumulation", "pointValue", "allowsNegativeValues", "InstrumentType", "LastValueAccumulation", "startTime", "current", "sampleTime", "value", "millisToHrTime", "LastValueAggregator", "AggregatorKind", "previous", "delta", "latestAccumulation", "hrTimeToMicroseconds", "descriptor", "aggregationTemporality", "accumulationByAttributes", "endTime", "DataPointType", "attributes", "accumulation", "SumAccumulation", "startTime", "monotonic", "current", "reset", "value", "SumAggregator", "AggregatorKind", "previous", "delta", "prevPv", "deltaPv", "currPv", "descriptor", "aggregationTemporality", "accumulationByAttributes", "endTime", "DataPointType", "attributes", "accumulation", "DropAggregation", "_DropAggregation", "DropAggregator", "_instrument", "SumAggregation", "_SumAggregation", "SumAggregator", "instrument", "InstrumentType", "LastValueAggregation", "_LastValueAggregation", "LastValueAggregator", "_instrument", "HistogramAggregation", "_HistogramAggregation", "HistogramAggregator", "_instrument", "ExplicitBucketHistogramAggregation", "boundaries", "recordMinMax", "a", "b", "minusInfinityIndex", "infinityIndex", "_instrument", "HistogramAggregator", "ExponentialHistogramAggregation", "maxSize", "ExponentialHistogramAggregator", "DefaultAggregation", "instrument", "InstrumentType", "SUM_AGGREGATION", "LAST_VALUE_AGGREGATION", "HISTOGRAM_AGGREGATION", "diag", "DROP_AGGREGATION", "DropAggregation", "SumAggregation", "LastValueAggregation", "HistogramAggregation", "EXPONENTIAL_HISTOGRAM_AGGREGATION", "DEFAULT_AGGREGATION", "AggregationType", "toAggregation", "option", "DEFAULT_AGGREGATION", "DROP_AGGREGATION", "SUM_AGGREGATION", "LAST_VALUE_AGGREGATION", "expOption", "ExponentialHistogramAggregation", "HISTOGRAM_AGGREGATION", "ExplicitBucketHistogramAggregation", "DEFAULT_AGGREGATION_SELECTOR", "_instrumentType", "AggregationType", "DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR", "AggregationTemporality", "MetricReader", "options", "DEFAULT_AGGREGATION_SELECTOR", "DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR", "metricProducer", "instrumentType", "sdkCollectionResults", "additionalCollectionResults", "producer", "errors", "result", "resource", "scopeMetrics", "diag", "callWithTimeout", "PeriodicExportingMetricReader", "MetricReader", "options", "exporter", "exportIntervalMillis", "metricProducers", "exportTimeoutMillis", "diag", "callWithTimeout", "err", "TimeoutError", "globalErrorHandler", "resourceMetrics", "errors", "e", "result", "internal", "ExportResultCode", "serviceName", "defaultServiceName", "argv0", "isPromiseLike", "val", "ResourceImpl", "_ResourceImpl", "attributes", "options", "res", "guardedRawAttributes", "_", "val", "isPromiseLike", "resource", "k", "v", "validateSchemaUrl", "i", "diag", "attrs", "mergedSchemaUrl", "mergeSchemaUrl", "mergedOptions", "resourceFromAttributes", "defaultResource", "resourceFromAttributes", "ATTR_SERVICE_NAME", "defaultServiceName", "ATTR_TELEMETRY_SDK_LANGUAGE", "SDK_INFO", "ATTR_TELEMETRY_SDK_NAME", "ATTR_TELEMETRY_SDK_VERSION", "guardedRawAttributes", "attributes", "k", "v", "isPromiseLike", "err", "diag", "validateSchemaUrl", "schemaUrl", "mergeSchemaUrl", "old", "updating", "oldSchemaUrl", "updatingSchemaUrl", "isOldEmpty", "isUpdatingEmpty", "ViewRegistry", "view", "instrument", "meter", "registeredView", "selector", "createInstrumentDescriptor", "name", "type", "options", "isValidName", "diag", "ValueType", "createInstrumentDescriptorWithView", "view", "instrument", "isDescriptorCompatibleWith", "descriptor", "otherDescriptor", "equalsCaseInsensitive", "NAME_REGEXP", "SyncInstrument", "writableMetricStorage", "descriptor", "value", "attributes", "context", "diag", "ValueType", "millisToHrTime", "UpDownCounterInstrument", "ctx", "CounterInstrument", "GaugeInstrument", "HistogramInstrument", "ObservableInstrument", "metricStorages", "observableRegistry", "callback", "ObservableCounterInstrument", "ObservableGaugeInstrument", "ObservableUpDownCounterInstrument", "isObservableInstrument", "it", "Meter", "meterSharedState", "name", "options", "descriptor", "createInstrumentDescriptor", "InstrumentType", "storage", "GaugeInstrument", "HistogramInstrument", "CounterInstrument", "UpDownCounterInstrument", "storages", "ObservableGaugeInstrument", "ObservableCounterInstrument", "ObservableUpDownCounterInstrument", "callback", "observables", "MetricStorage", "instrumentDescriptor", "description", "createInstrumentDescriptor", "HashMap", "hash", "key", "hashCode", "defaultFactory", "val", "value", "keyIterator", "next", "valueIterator", "AttributeHashMap", "hashAttributes", "DeltaMetricProcessor", "AttributeHashMap", "aggregator", "aggregationCardinalityLimit", "hashAttributes", "value", "attributes", "_context", "collectionTime", "accumulation", "measurements", "hashCode", "delta", "previous", "active", "unreportedDelta", "TemporalMetricProcessor", "_TemporalMetricProcessor", "aggregator", "collectorHandles", "handle", "collector", "instrumentDescriptor", "currentAccumulations", "collectionTime", "unreportedAccumulations", "result", "aggregationTemporality", "last", "lastCollectionTime", "AggregationTemporality", "accumulationRecords", "AttributesMapToAccumulationRecords", "currentAccumulation", "registeredCollectors", "stash", "AttributeHashMap", "unreportedList", "it", "current", "iterator", "next", "key", "record", "hash", "lastAccumulation", "accumulation", "map", "AsyncMetricStorage", "MetricStorage", "_instrumentDescriptor", "aggregator", "attributesProcessor", "collectorHandles", "aggregationCardinalityLimit", "DeltaMetricProcessor", "TemporalMetricProcessor", "measurements", "observationTime", "processed", "AttributeHashMap", "attributes", "value", "collector", "collectionTime", "accumulations", "getIncompatibilityDetails", "existing", "otherDescriptor", "incompatibility", "getValueTypeConflictResolutionRecipe", "getUnitConflictResolutionRecipe", "getTypeConflictResolutionRecipe", "selector", "selectorString", "getDescriptionResolutionRecipe", "getConflictResolutionRecipe", "MetricStorageRegistry", "_MetricStorageRegistry", "collector", "storages", "metricStorages", "perCollectorStorages", "storage", "storageMap", "expectedDescriptor", "descriptor", "existingStorages", "compatibleStorage", "existingStorage", "existingDescriptor", "isDescriptorCompatibleWith", "diag", "getIncompatibilityDetails", "getConflictResolutionRecipe", "MultiMetricStorage", "backingStorages", "value", "attributes", "context", "recordTime", "it", "ObservableResultImpl", "AttributeHashMap", "instrumentName", "valueType", "value", "attributes", "diag", "ValueType", "BatchObservableResultImpl", "metric", "isObservableInstrument", "map", "ObservableRegistry", "callback", "instrument", "idx", "instruments", "observableInstruments", "isObservableInstrument", "diag", "collectionTime", "timeoutMillis", "callbackFutures", "batchCallbackFutures", "result", "observationTime", "observableResult", "ObservableResultImpl", "callPromise", "callWithTimeout", "metricStorage", "BatchObservableResultImpl", "buffer", "record", "setEquals", "SyncMetricStorage", "MetricStorage", "instrumentDescriptor", "aggregator", "attributesProcessor", "collectorHandles", "aggregationCardinalityLimit", "DeltaMetricProcessor", "TemporalMetricProcessor", "value", "attributes", "context", "recordTime", "collector", "collectionTime", "accumulations", "NoopAttributesProcessor", "incoming", "_context", "MultiAttributesProcessor", "processors", "context", "filteredAttributes", "processor", "createNoopAttributesProcessor", "NOOP", "createMultiAttributesProcessor", "processors", "MultiAttributesProcessor", "NOOP", "NoopAttributesProcessor", "MeterSharedState", "MetricStorageRegistry", "ObservableRegistry", "meterProviderSharedState", "instrumentationScope", "Meter", "descriptor", "storages", "SyncMetricStorage", "MultiMetricStorage", "AsyncMetricStorage", "collector", "collectionTime", "options", "errors", "metricDataList", "metricStorage", "metricData", "MetricStorageType", "view", "viewDescriptor", "createInstrumentDescriptorWithView", "compatibleStorage", "aggregator", "viewStorage", "collectorStorages", "aggregation", "cardinalityLimit", "storage", "createNoopAttributesProcessor", "MeterProviderSharedState", "ViewRegistry", "resource", "instrumentationScope", "id", "instrumentationScopeId", "meterSharedState", "MeterSharedState", "instrumentType", "result", "collector", "toAggregation", "MetricCollector", "sharedState", "metricReader", "options", "collectionTime", "millisToHrTime", "scopeMetrics", "errors", "meterCollectionPromises", "meterSharedState", "current", "instrumentType", "ESCAPE", "PatternPredicate", "_PatternPredicate", "pattern", "str", "ExactPredicate", "InstrumentSelector", "criteria", "PatternPredicate", "ExactPredicate", "MeterSelector", "criteria", "ExactPredicate", "isSelectorNotProvided", "options", "validateViewOptions", "viewOptions", "PatternPredicate", "View", "createMultiAttributesProcessor", "createNoopAttributesProcessor", "toAggregation", "AggregationType", "InstrumentSelector", "MeterSelector", "MeterProvider", "options", "MeterProviderSharedState", "defaultResource", "viewOption", "View", "metricReader", "collector", "MetricCollector", "name", "version", "diag", "createNoopMeter", "EAggregationTemporality", "toResourceMetrics", "resourceMetrics", "encoder", "processedResource", "createResource", "toScopeMetrics", "scopeMetrics", "metrics", "createInstrumentationScope", "metricData", "toMetric", "out", "aggregationTemporality", "toAggregationTemporality", "DataPointType", "toSingularDataPoints", "toHistogramDataPoints", "toExponentialHistogramDataPoints", "toSingularDataPoint", "dataPoint", "valueType", "toAttributes", "ValueType", "histogram", "temporality", "AggregationTemporality", "EAggregationTemporality", "createExportMetricsServiceRequest", "SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK", "SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK", "buildSpanFlagsFrom", "traceFlags", "isRemote", "flags", "sdkSpanToOtlpSpan", "span", "encoder", "ctx", "status", "parentSpanId", "toAttributes", "event", "toOtlpSpanEvent", "link", "toOtlpLink", "timedEvent", "createExportTraceServiceRequest", "spans", "spanRecordsToResourceSpans", "createResourceMap", "readableSpans", "resourceMap", "record", "ilsMap", "instrumentationScopeKey", "records", "out", "entryIterator", "entry", "resource", "ilmMap", "scopeResourceSpans", "ilmIterator", "ilmEntry", "scopeSpans", "readableSpan", "createInstrumentationScope", "processedResource", "createResource", "transformedSpans", "JsonLogsSerializer", "arg", "request", "createExportLogsServiceRequest", "JSON_ENCODER", "decoder", "JsonMetricsSerializer", "arg", "request", "createExportMetricsServiceRequest", "JSON_ENCODER", "decoder", "JsonTraceSerializer", "arg", "request", "createExportTraceServiceRequest", "JSON_ENCODER", "decoder", "MAX_ATTEMPTS", "INITIAL_BACKOFF", "MAX_BACKOFF", "BACKOFF_MULTIPLIER", "JITTER", "getJitter", "RetryingTransport", "transport", "data", "timeoutMillis", "inMillis", "resolve", "reject", "attempts", "nextBackoff", "deadline", "result", "backoff", "retryInMillis", "remainingTimeoutMillis", "diag", "createRetryingTransport", "options", "isExportHTTPErrorRetryable", "statusCode", "parseRetryAfterToMills", "retryAfter", "seconds", "delay", "MAX_KEEPALIVE_BODY_SIZE", "MAX_KEEPALIVE_REQUESTS", "pendingBodySize", "pendingKeepaliveCount", "FetchTransport", "parameters", "data", "timeoutMillis", "abortController", "timeout", "fetchApi", "requestSize", "wouldExceedSize", "wouldExceedCount", "useKeepalive", "reason", "diag", "url", "response", "isExportHTTPErrorRetryable", "retryAfter", "parseRetryAfterToMills", "error", "isFetchNetworkErrorRetryable", "createFetchTransport", "createOtlpFetchExportDelegate", "options", "serializer", "createOtlpNetworkExportDelegate", "createRetryingTransport", "createFetchTransport", "validateAndNormalizeHeaders", "partialHeaders", "headers", "key", "value", "diag", "mergeHeaders", "userProvidedHeaders", "fallbackHeaders", "defaultHeaders", "requiredHeaders", "headers", "validateAndNormalizeHeaders", "validateUserProvidedUrl", "url", "base", "mergeOtlpHttpConfigurationWithDefaults", "userProvidedConfiguration", "fallbackConfiguration", "defaultConfiguration", "mergeOtlpSharedConfigurationWithDefaults", "getHttpConfigurationDefaults", "signalResourcePath", "getSharedConfigurationDefaults", "convertLegacyHeaders", "config", "wrapStaticHeadersInFunction", "convertLegacyBrowserHttpOptions", "config", "signalResourcePath", "requiredHeaders", "mergeOtlpHttpConfigurationWithDefaults", "convertLegacyHeaders", "getHttpConfigurationDefaults", "createLegacyOtlpBrowserExportDelegate", "config", "serializer", "signalResourcePath", "requiredHeaders", "options", "convertLegacyBrowserHttpOptions", "createOtlpFetchExportDelegate", "OTLPLogExporter", "OTLPExporterBase", "config", "createLegacyOtlpBrowserExportDelegate", "JsonLogsSerializer", "AggregationTemporalityPreference", "CumulativeTemporalitySelector", "AggregationTemporality", "DeltaTemporalitySelector", "instrumentType", "InstrumentType", "LowMemoryTemporalitySelector", "chooseTemporalitySelectorFromEnvironment", "configuredTemporality", "diag", "chooseTemporalitySelector", "temporalityPreference", "AggregationTemporalityPreference", "DEFAULT_AGGREGATION", "AggregationType", "chooseAggregationSelector", "config", "OTLPMetricExporterBase", "OTLPExporterBase", "delegate", "OTLPMetricExporter", "OTLPMetricExporterBase", "config", "createLegacyOtlpBrowserExportDelegate", "JsonMetricsSerializer", "OTLPTraceExporter", "OTLPExporterBase", "config", "createLegacyOtlpBrowserExportDelegate", "JsonTraceSerializer", "isLogAttributeValue", "val", "isLogAttributeValueInternal", "visited", "item", "obj", "LogRecordImpl", "severityText", "severityNumber", "body", "eventName", "_sharedState", "instrumentationScope", "logRecord", "timestamp", "observedTimestamp", "attributes", "exception", "context", "now", "timeInputToHrTime", "spanContext", "trace", "isSpanContextValid", "key", "value", "diag", "isLogAttributeValue", "k", "v", "limit", "val", "truncatedObj", "hasMinimumAttributes", "ATTR_EXCEPTION_MESSAGE", "exceptionObj", "ATTR_EXCEPTION_TYPE", "ATTR_EXCEPTION_STACKTRACE", "Logger", "instrumentationScope", "sharedState", "logRecord", "loggerConfig", "currentContext", "context", "recordSeverity", "SeverityNumber", "spanContext", "trace", "isSpanContextValid", "TraceFlags", "logRecordInstance", "LogRecordImpl", "NoopLogRecordProcessor", "_logRecord", "_context", "MultiLogRecordProcessor", "processors", "forceFlushTimeoutMillis", "timeout", "processor", "callWithTimeout", "logRecord", "context", "getInstrumentationScopeKey", "scope", "DEFAULT_LOGGER_CONFIG", "SeverityNumber", "DEFAULT_LOGGER_CONFIGURATOR", "LoggerProviderSharedState", "resource", "forceFlushTimeoutMillis", "logRecordLimits", "processors", "loggerConfigurator", "MultiLogRecordProcessor", "NoopLogRecordProcessor", "instrumentationScope", "key", "getInstrumentationScopeKey", "config", "DEFAULT_LOGGER_NAME", "LoggerProvider", "config", "mergedConfig", "defaultResource", "DEFAULT_LOGGER_CONFIGURATOR", "LoggerProviderSharedState", "BindOnceFuture", "name", "version", "options", "diag", "NOOP_LOGGER", "loggerName", "key", "Logger", "BatchLogRecordProcessorBase", "exporter", "config", "BindOnceFuture", "diag", "logRecord", "resolve", "reject", "promises", "batchCount", "callWithTimeout", "flush", "e", "globalErrorHandler", "logRecords", "doExport", "internal", "result", "ExportResultCode", "pendingResources", "i", "resource", "BatchLogRecordProcessor", "BatchLogRecordProcessorBase", "exporter", "config", "ExceptionEventName", "SpanImpl", "SpanStatusCode", "opts", "now", "otperformance", "key", "value", "diag", "isAttributeValue", "attributeCountLimit", "isNewKey", "attributes", "k", "v", "name", "attributesOrStartTime", "timeStamp", "eventCountLimit", "isTimeInput", "sanitizeAttributes", "link", "links", "status", "endTime", "hrTimeDuration", "inp", "hrTime", "millisToHrTime", "isTimeInputHrTime", "msDuration", "addHrTimes", "exception", "time", "ATTR_EXCEPTION_MESSAGE", "ATTR_EXCEPTION_TYPE", "ATTR_EXCEPTION_STACKTRACE", "ExceptionEventName", "error", "limit", "val", "SamplingDecision", "AlwaysOffSampler", "SamplingDecision", "AlwaysOnSampler", "SamplingDecision", "ParentBasedSampler", "config", "globalErrorHandler", "AlwaysOnSampler", "AlwaysOffSampler", "context", "traceId", "spanName", "spanKind", "attributes", "links", "parentContext", "trace", "isSpanContextValid", "TraceFlags", "TraceIdRatioBasedSampler", "ratio", "context", "traceId", "isValidTraceId", "SamplingDecision", "accumulation", "i", "pos", "part", "TracesSamplerValues", "DEFAULT_RATIO", "loadDefaultConfig", "buildSamplerFromEnv", "sampler", "AlwaysOnSampler", "AlwaysOffSampler", "ParentBasedSampler", "TraceIdRatioBasedSampler", "getSamplerProbabilityFromEnv", "diag", "probability", "DEFAULT_ATTRIBUTE_COUNT_LIMIT", "DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT", "mergeConfig", "userConfig", "perInstanceDefaults", "buildSamplerFromEnv", "DEFAULT_CONFIG", "loadDefaultConfig", "target", "reconfigureLimits", "spanLimits", "BatchSpanProcessorBase", "exporter", "config", "BindOnceFuture", "diag", "_span", "_parentContext", "span", "TraceFlags", "resolve", "reject", "promises", "count", "j", "timer", "context", "suppressTracing", "spans", "doExport", "result", "ExportResultCode", "pendingResources", "i", "len", "err", "globalErrorHandler", "flush", "e", "BatchSpanProcessor", "BatchSpanProcessorBase", "_exporter", "config", "error", "globalErrorHandler", "TRACE_BUFFER", "SPAN_BUFFER", "HEX", "_", "i", "randomFill", "buf", "toHex", "hex", "RandomIdGenerator", "ATTR_OTEL_SPAN_PARENT_ORIGIN", "ATTR_OTEL_SPAN_SAMPLING_RESULT", "METRIC_OTEL_SDK_SPAN_LIVE", "METRIC_OTEL_SDK_SPAN_STARTED", "TracerMetrics", "meter", "METRIC_OTEL_SDK_SPAN_STARTED", "METRIC_OTEL_SDK_SPAN_LIVE", "parentSpanCtx", "samplingDecision", "samplingDecisionStr", "samplingDecisionToString", "ATTR_OTEL_SPAN_PARENT_ORIGIN", "parentOrigin", "ATTR_OTEL_SPAN_SAMPLING_RESULT", "SamplingDecision", "liveSpanAttributes", "parentSpanContext", "decision", "VERSION", "Tracer", "instrumentationScope", "config", "resource", "spanProcessor", "localConfig", "mergeConfig", "RandomIdGenerator", "meter", "VERSION", "createNoopMeter", "TracerMetrics", "name", "options", "context", "trace", "parentSpan", "isTracingSuppressed", "diag", "INVALID_SPAN_CONTEXT", "parentSpanContext", "spanId", "validParentSpanContext", "traceId", "traceState", "spanKind", "SpanKind", "links", "link", "sanitizeAttributes", "attributes", "samplingResult", "recordEndMetrics", "traceFlags", "SamplingDecision", "TraceFlags", "spanContext", "initAttributes", "SpanImpl", "arg2", "arg3", "arg4", "opts", "ctx", "fn", "parentContext", "span", "contextWithSpanSet", "MultiSpanProcessor", "spanProcessors", "promises", "spanProcessor", "resolve", "error", "globalErrorHandler", "span", "context", "reject", "ForceFlushState", "BasicTracerProvider", "config", "mergedConfig", "merge", "loadDefaultConfig", "reconfigureLimits", "defaultResource", "spanProcessors", "MultiSpanProcessor", "name", "version", "options", "key", "Tracer", "timeout", "promises", "spanProcessor", "resolve", "state", "timeoutInterval", "error", "reject", "results", "errors", "result", "StackContextManager", "ROOT_CONTEXT", "context", "target", "manager", "contextWrapper", "args", "fn", "thisArg", "previousContext", "setupContextManager", "contextManager", "defaultContextManager", "StackContextManager", "context", "setupPropagator", "propagator", "propagation", "CompositePropagator", "W3CTraceContextPropagator", "W3CBaggagePropagator", "WebTracerProvider", "BasicTracerProvider", "config", "trace", "PerformanceTimingNames", "ATTR_HTTP_RESPONSE_CONTENT_LENGTH", "ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED", "urlNormalizingAnchor", "getUrlNormalizingAnchor", "hasKey", "obj", "key", "addSpanNetworkEvent", "span", "performanceName", "entries", "ignoreZeros", "addSpanNetworkEvents", "resource", "ignoreNetworkEvents", "skipOldSemconvContentLengthAttrs", "PerformanceTimingNames", "encodedLength", "ATTR_HTTP_RESPONSE_CONTENT_LENGTH", "decodedLength", "ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED", "sortResources", "filteredResources", "a", "b", "valueA", "valueB", "getOrigin", "getResource", "spanUrl", "startTimeHR", "endTimeHR", "resources", "ignoredResources", "initiatorType", "parsedSpanUrl", "parseUrl", "filterResourcesForSpan", "sorted", "corsPreFlightRequest", "mainRequest", "findMainRequest", "responseEnd", "corsPreFlightRequestEndTime", "spanEndTimeHR", "spanEndTime", "hrTimeToNanoseconds", "minTime", "timeInputToHrTime", "bestGap", "length", "i", "resourceStartTime", "resourceEndTime", "currentGap", "startTime", "endTime", "url", "element", "getElementXPath", "target", "optimised", "targetValue", "getNodeValue", "xpath", "getNodeIndex", "allowedTypes", "elements", "element", "localName", "nodeType", "index", "nodeValue", "id", "shouldPropagateTraceHeaders", "spanUrl", "propagateTraceHeaderCorsUrls", "propagateTraceHeaderUrls", "parseUrl", "getOrigin", "propagateTraceHeaderUrl", "urlMatches", "enableInstrumentations", "instrumentations", "tracerProvider", "meterProvider", "loggerProvider", "i", "j", "instrumentation", "disableInstrumentations", "registerInstrumentations", "options", "tracerProvider", "trace", "meterProvider", "metrics", "loggerProvider", "logs", "instrumentations", "enableInstrumentations", "disableInstrumentations", "logger", "defineProperty", "obj", "name", "value", "enumerable", "wrap", "nodule", "wrapper", "original", "wrapped", "massWrap", "nodules", "names", "unwrap", "massUnwrap", "shimmer", "options", "InstrumentationAbstract", "instrumentationName", "instrumentationVersion", "config", "diag", "trace", "metrics", "logs", "wrap", "unwrap", "massWrap", "massUnwrap", "meterProvider", "loggerProvider", "initResult", "tracerProvider", "hookHandler", "triggerName", "span", "info", "e", "InstrumentationBase", "InstrumentationAbstract", "instrumentationName", "instrumentationVersion", "config", "safeExecuteInTheMiddle", "execute", "onFinish", "preventThrowingError", "error", "result", "e", "isWrapped", "func", "SemconvStability", "semconvStabilityFromStr", "namespace", "str", "semconvStability", "entries", "v", "s", "entry", "AttributeNames", "PACKAGE_VERSION", "PACKAGE_NAME", "ATTR_HTTP_URL", "ATTR_HTTP_USER_AGENT", "EventNames", "getPerformanceNavigationEntries", "entries", "performanceNavigationTiming", "otperformance", "PerformanceTimingNames", "key", "hasKey", "value", "performanceTiming", "performancePaintNames", "EventNames", "addSpanPerformancePaintEvents", "span", "performancePaintTiming", "name", "startTime", "DocumentLoadInstrumentation", "InstrumentationBase", "config", "PACKAGE_NAME", "PACKAGE_VERSION", "semconvStabilityFromStr", "rootSpan", "resources", "otperformance", "resource", "metaElement", "e", "TRACE_PARENT_HEADER", "entries", "getPerformanceNavigationEntries", "traceparent", "context", "propagation", "ROOT_CONTEXT", "AttributeNames", "PerformanceTimingNames", "trace", "fetchSpan", "SemconvStability", "ATTR_HTTP_URL", "ATTR_URL_FULL", "skipOldSemconvContentLengthAttrs", "addSpanNetworkEvents", "ATTR_HTTP_USER_AGENT", "ATTR_USER_AGENT_ORIGINAL", "addSpanNetworkEvent", "addSpanPerformancePaintEvents", "span", "performanceName", "hasKey", "parentSpan", "spanName", "applyCustomAttributesOnSpan", "safeExecuteInTheMiddle", "error", "AttributeNames", "ATTR_HTTP_HOST", "ATTR_HTTP_METHOD", "ATTR_HTTP_REQUEST_BODY_SIZE", "ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED", "ATTR_HTTP_SCHEME", "ATTR_HTTP_STATUS_CODE", "ATTR_HTTP_URL", "ATTR_HTTP_USER_AGENT", "DIAG_LOGGER", "diag", "getFetchBodyLength", "args", "requestInit", "body", "length", "_getBodyNonDestructively", "getXHRBodyLength", "info", "t", "getByteLength", "resolveLength", "lengthPromise", "resolve", "transform", "chunk", "controller", "bytearray", "isDocument", "value", "getFormDataSize", "TEXT_ENCODER", "s", "formData", "size", "key", "normalizeHttpRequestMethod", "method", "knownMethods", "getKnownMethods", "methUpper", "DEFAULT_KNOWN_METHODS", "cfgMethods", "m", "HTTP_PORT_FROM_PROTOCOL", "serverPortFromUrl", "url", "serverPort", "VERSION", "OBSERVER_WAIT_TIME_MS", "hasBrowserPerformanceAPI", "FetchInstrumentation", "InstrumentationBase", "VERSION", "config", "semconvStabilityFromStr", "span", "corsPreFlightRequest", "childSpan", "PerformanceTimingNames", "trace", "context", "skipOldSemconvContentLengthAttrs", "SemconvStability", "addSpanNetworkEvents", "response", "parsedUrl", "parseUrl", "ATTR_HTTP_STATUS_CODE", "AttributeNames", "ATTR_HTTP_HOST", "ATTR_HTTP_SCHEME", "ATTR_HTTP_USER_AGENT", "ATTR_HTTP_RESPONSE_STATUS_CODE", "ATTR_SERVER_ADDRESS", "serverPort", "serverPortFromUrl", "ATTR_SERVER_PORT", "options", "spanUrl", "shouldPropagateTraceHeaders", "headers", "propagation", "h", "k", "v", "url", "isUrlIgnored", "name", "attributes", "method", "ATTR_HTTP_METHOD", "ATTR_HTTP_URL", "origMethod", "normMethod", "normalizeHttpRequestMethod", "ATTR_HTTP_REQUEST_METHOD", "ATTR_HTTP_REQUEST_METHOD_ORIGINAL", "ATTR_URL_FULL", "SpanKind", "resourcesObserver", "endTime", "resources", "resource", "getResource", "mainRequest", "spanData", "millisToHrTime", "performanceEndTime", "hrTime", "SpanStatusCode", "ATTR_ERROR_TYPE", "original", "plugin", "readOnlyProps", "createResponseProxy", "target", "originalResponse", "t", "prop", "_receiver", "value", "args", "self", "createdSpan", "getFetchBodyLength", "bodyLength", "ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED", "ATTR_HTTP_REQUEST_BODY_SIZE", "error", "endSpanOnError", "endSpanOnSuccess", "withCancelPropagation", "body", "readerClone", "reader", "controller", "done", "err", "_", "reason", "onSuccess", "resolve", "proxiedResponse", "wrappedBody", "newResponse", "read", "onError", "reject", "request", "result", "applyCustomAttributesOnSpan", "safeExecuteInTheMiddle", "requestHook", "startTime", "entries", "observer", "list", "entry", "isWrapped", "PACKAGE_VERSION", "PACKAGE_NAME", "LONGTASK_PERFORMANCE_TYPE", "LongTaskInstrumentation", "InstrumentationBase", "PACKAGE_VERSION", "config", "PACKAGE_NAME", "entry", "span", "hrTime", "observerCallback", "err", "diag", "attribution", "index", "prefix", "list", "AttributeNames", "PACKAGE_VERSION", "PACKAGE_NAME", "ZONE_CONTEXT_KEY", "EVENT_NAVIGATION_NAME", "DEFAULT_EVENT_NAMES", "defaultShouldPreventSpanCreation", "UserInteractionInstrumentation", "InstrumentationBase", "PACKAGE_VERSION", "config", "PACKAGE_NAME", "task", "span", "spanData", "hrTime", "eventName", "element", "parentSpan", "xpath", "getElementXPath", "AttributeNames", "trace", "context", "e", "zone", "on", "type", "listener", "wrappedListener", "listener2Type", "element2patched", "patched", "target", "args", "plugin", "original", "useCapture", "once", "patchedListener", "event", "result", "url", "urlAfter", "isWrapped", "currentZone", "currentSpan", "applyThis", "applyArgs", "activeZone", "endTime", "ZoneWithPrototype", "ATTR_HTTP_HOST", "ATTR_HTTP_METHOD", "ATTR_HTTP_REQUEST_BODY_SIZE", "ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED", "ATTR_HTTP_SCHEME", "ATTR_HTTP_STATUS_CODE", "ATTR_HTTP_URL", "ATTR_HTTP_USER_AGENT", "EventNames", "DIAG_LOGGER", "diag", "isDocument", "value", "getXHRBodyLength", "body", "getByteLength", "getFormDataSize", "TEXT_ENCODER", "s", "formData", "size", "key", "normalizeHttpRequestMethod", "method", "knownMethods", "getKnownMethods", "methUpper", "DEFAULT_KNOWN_METHODS", "cfgMethods", "m", "HTTP_PORT_FROM_PROTOCOL", "serverPortFromUrl", "url", "serverPort", "VERSION", "AttributeNames", "OBSERVER_WAIT_TIME_MS", "XMLHttpRequestInstrumentation", "InstrumentationBase", "VERSION", "config", "semconvStabilityFromStr", "xhr", "spanUrl", "url", "parseUrl", "shouldPropagateTraceHeaders", "headers", "propagation", "context", "key", "span", "corsPreFlightRequest", "trace", "childSpan", "PerformanceTimingNames", "skipOldSemconvContentLengthAttrs", "SemconvStability", "addSpanNetworkEvents", "xhrMem", "ATTR_HTTP_STATUS_CODE", "AttributeNames", "parsedUrl", "ATTR_HTTP_HOST", "ATTR_HTTP_SCHEME", "ATTR_HTTP_USER_AGENT", "ATTR_HTTP_RESPONSE_STATUS_CODE", "applyCustomAttributesOnSpan", "safeExecuteInTheMiddle", "error", "list", "entries", "entry", "otperformance", "startTime", "endTime", "resources", "resource", "getResource", "mainRequest", "callbackToRemoveEvents", "method", "isUrlIgnored", "name", "attributes", "ATTR_HTTP_METHOD", "ATTR_HTTP_URL", "origMethod", "normMethod", "normalizeHttpRequestMethod", "ATTR_HTTP_REQUEST_METHOD", "ATTR_HTTP_REQUEST_METHOD_ORIGINAL", "ATTR_URL_FULL", "ATTR_SERVER_ADDRESS", "serverPort", "serverPortFromUrl", "ATTR_SERVER_PORT", "currentSpan", "SpanKind", "EventNames", "original", "plugin", "args", "endSpanTimeout", "eventName", "performanceEndTime", "sendStartTime", "endSpan", "isError", "errorType", "SpanStatusCode", "ATTR_ERROR_TYPE", "hrTime", "onError", "onAbort", "onTimeout", "onLoad", "unregister", "body", "bodyLength", "getXHRBodyLength", "ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED", "ATTR_HTTP_REQUEST_BODY_SIZE", "isWrapped", "PACKAGE_VERSION", "PACKAGE_NAME", "ExceptionInstrumentation", "InstrumentationBase", "config", "PACKAGE_NAME", "PACKAGE_VERSION", "event", "EXCEPTION_EVENT_NAME", "error", "logger", "logs", "customAttributes", "errorAttributes", "ATTR_EXCEPTION_MESSAGE", "ATTR_EXCEPTION_TYPE", "ATTR_EXCEPTION_STACKTRACE", "errorLog", "SeverityNumber", "hrTime", "WEB_VITAL_EVENT_NAME", "ATTR_WEB_VITAL_NAME", "ATTR_WEB_VITAL_VALUE", "ATTR_WEB_VITAL_RATING", "ATTR_WEB_VITAL_DELTA", "ATTR_WEB_VITAL_ID", "ATTR_WEB_VITAL_NAVIGATION_TYPE", "t", "e", "n", "o", "i", "r", "s", "a", "c", "f", "u", "d", "l", "h", "m", "p", "g", "y", "v", "b", "M", "T", "E", "D", "L", "P", "S", "w", "_", "F", "k", "B", "C", "O", "j", "I", "A", "W", "q", "x", "N", "H", "R", "U", "V", "$", "WebVitalsInstrumentation", "InstrumentationBase", "config", "S", "metric", "x", "R", "w", "$", "attribution", "attributes", "ATTR_WEB_VITAL_NAME", "ATTR_WEB_VITAL_VALUE", "ATTR_WEB_VITAL_DELTA", "ATTR_WEB_VITAL_RATING", "ATTR_WEB_VITAL_ID", "ATTR_WEB_VITAL_NAVIGATION_TYPE", "timestamp", "logRecord", "WEB_VITAL_EVENT_NAME", "SeverityNumber", "safeExecuteInTheMiddle", "error", "_logLevel", "DiagLogLevel", "logLevelMap", "createLogger", "config", "makeLogFunction", "minLevel", "emitFn", "args", "shouldLog", "logger", "createLogger", "_currentContext", "ROOT_CONTEXT", "_managerEnabled", "AsyncApisContextManager", "context", "fn", "thisArg", "args", "prevContext", "target", "bindFn", "manager", "wrap", "origSetTimeout", "delay", "origSetImmediate", "wrapXMLHttpRequest", "wrapPromise", "unwrap", "unwrapXMLHttpRequest", "unwrapPromise", "ctx", "wrappedCtxFn", "origThen", "onResolved", "onRejected", "origCatch", "origFinally", "onCompleted", "xhrProps", "xhrProto", "xhrTargetProps", "xhrTargetProto", "origAEL", "xhr", "handler", "bound", "origREL", "prop", "descriptor", "wrapDescriptor", "nodule", "name", "wrapper", "original", "wrapped", "defineProperty", "origSet", "value", "origValue", "origGet", "obj", "enumerable", "ATTR_BROWSER_BRANDS", "ATTR_BROWSER_LANGUAGE", "ATTR_BROWSER_MOBILE", "ATTR_BROWSER_PLATFORM", "ATTR_USER_AGENT_ORIGINAL", "EDOT_VERSION", "detectResource", "attribs", "serviceName", "serviceVersion", "userAgent", "userAgentData", "browserInfo", "getBrowserInfo", "platform", "ATTR_BROWSER_BRANDS", "i", "getPlatformInfo", "ATTR_BROWSER_PLATFORM", "ATTR_BROWSER_MOBILE", "ATTR_BROWSER_LANGUAGE", "ATTR_USER_AGENT_ORIGINAL", "EDOT_VERSION", "resourceFromAttributes", "SDK_INFO", "platforms", "p", "name", "tests", "t", "match", "version", "browsers", "b", "sdkStarted", "defaultConfig", "startBrowserSdk", "cfg", "logLevel", "diag", "createLogger", "DiagLogLevel", "serviceName", "serviceVersion", "config", "endpointUrl", "resource", "detectResource", "tracesEndpoint", "appendPath", "spanProcessor", "BatchSpanProcessor", "OTLPTraceExporter", "tracerProvider", "WebTracerProvider", "TraceIdRatioBasedSampler", "AsyncApisContextManager", "metricsEndpoint", "metricsReader", "PeriodicExportingMetricReader", "OTLPMetricExporter", "meterProvider", "MeterProvider", "metrics", "logsEndpoint", "logsProcessor", "BatchLogRecordProcessor", "OTLPLogExporter", "loggerProvider", "LoggerProvider", "logs", "instrFactories", "DocumentLoadInstrumentation", "FetchInstrumentation", "LongTaskInstrumentation", "UserInteractionInstrumentation", "XMLHttpRequestInstrumentation", "ExceptionInstrumentation", "WebVitalsInstrumentation", "httpSemconvConfig", "instrumentations", "enabledInstrumentations", "key", "instrConfig", "registerInstrumentations", "url", "path", "result", "startBrowserSdk"]
|
|
7
|
+
}
|