@use-tusk/drift-node-sdk 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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["OtSpanKind","PbSpanKind","fields: Record<string, Value>","globalLogger: Logger","payload: AnalyticsPayload","version","module","exports","path","fs","mockFiles: string[]","mockData: CleanSpanData[]","mockDataItem: CleanSpanData","relatedMocks: CleanSpanData[]","spanInfo: SpanInfo | null","attributes: Attributes","normalized: Record<string, any>","buffers: Buffer[]","merged: JsonSchema","schema: JsonSchema","sortedObj: any","CONTENT_TYPE_MAPPING: Record<string, DecodedType>","rawInputValue: HttpClientInputValue","callback: ((res: any) => void) | undefined","mockOptions: TdMockClientRequestOptions","isWrapped","testSpan: HttpSpanData","actions: TransformAction[]","checks: MatcherFunction[]","path","self","completeInputValue: any","responseChunks: (string | Buffer)[]","outputValue: HttpServerOutputValue","spanData: HttpSpanData","error","requestBodyChunks: Buffer[]","streamConsumptionMode: \"NOT_CONSUMING\" | \"READ\" | \"PIPE\"","updatedInputValue: HttpServerInputValue","requestBodyChunks: (string | Buffer)[]","chunk","updatedInputValue: HttpClientInputValue","outputValue: HttpClientOutputValue","headers: Record<string, string>","requestOptions: RequestOptions","inputValue: HttpClientInputValue","currentSpanInfo: SpanInfo | null","self","self","context","currentSpanInfo: SpanInfo | null","self","queryConfig: QueryConfig | null","inputValue: PgClientInputValue","config: QueryConfig","error","context","fieldTypeMap: Record<string, number>","self","error: any","inputValue: PostgresClientInputValue","error","outputValue: any","self","self","verifyConfig: VerifyQueryConfig | null","rawInputValue: JwtVerifyInputValue","inputValue: JwtVerifyInputValue","signConfig: SignQueryConfig | null","inputValue: JwtSignInputValue","config: VerifyQueryConfig","config: SignQueryConfig","error","context","error: any","self","self","inputValue: FetchInputValue","error","result: Record<string, string>","bodyBuffer: Buffer","chunks: Uint8Array[]","context","api_1","constants_1","api_1","suppress_tracing_1","constants_1","utils_1","context","api_1","api_1","api_1","env","os","SPAN_ID_BYTES","TRACE_ID_BYTES","RandomIdGenerator","getIdGenerator","SHARED_BUFFER","semantic_conventions_1","__createBinding","__exportStar","exports","__createBinding","__exportStar","exports","platform_1","api_1","context","api_1","suppress_tracing_1","context","context","api_1","AlwaysOffSampler","api_1","AlwaysOnSampler","api_1","AlwaysOffSampler_1","AlwaysOnSampler_1","ParentBasedSampler","context","api_1","TraceIdRatioBasedSampler","api_1","__createBinding","__exportStar","exports","fs","ExportResultCode","protoSpans: Span[]","request: ExportSpansRequest","path","OtSpanKind","outputData: any","outputSchema: JsonSchema","outputValueHash: string","metadata: MetadataObject | undefined","sdkMessage: SDKMessage","error: any","cleaned: any","context","api_1","AbstractAsyncHooksContextManager_1","context","api_1","context","__createBinding","__exportStar","exports","api_1","api_1","core_1","common_1","constants_1","context","api_1","core_1","constants_1","context","core_1","context","__createBinding","__exportStar","exports","api_1","core_1","semantic_conventions_1","Span","context","Sampler_1","Sampler_1","api_1","core_1","AlwaysOffSampler_1","AlwaysOnSampler_1","context","api_1","api_1","core_1","config_1","core_1","api_1","core_1","env","BatchSpanProcessor","__createBinding","__exportStar","exports","__createBinding","__exportStar","exports","core_1","utility_1","platform_1","context","execAsync_1","api_1","getMachineId","fs_1","api_1","getMachineId","path","execAsync_1","api_1","getMachineId","process","api_1","getMachineId","api_1","getMachineId","process","semantic_conventions_1","Resource_1","os_1","utils_1","semantic_conventions_1","Resource_1","utils_1","api_1","semantic_conventions_1","Resource_1","os","__createBinding","__exportStar","exports","__createBinding","__exportStar","exports","api_1","semantic_conventions_1","core_1","platform_1","_a","__1","api_1","core_1","semantic_conventions_1","Resource_1","env","api_1","__createBinding","__exportStar","exports","api_1","__createBinding","__exportStar","exports","core_1","context","api_1","core_1","version","core_1","core_1","api_1","core_1","_a","__createBinding","__exportStar","exports","context","__createBinding","__exportStar","exports","exports","BatchSpanProcessor","TuskDrift: TuskDriftPublicAPI"],"sources":["../src/instrumentation/core/baseClasses/TdInstrumentationAbstract.ts","../package.json","../src/version.ts","../src/core/utils/dataNormalizationUtils.ts","../src/core/utils/samplingUtils.ts","../src/core/utils/protobufUtils.ts","../src/core/utils/OriginalGlobalUtils.ts","../src/core/utils/configUtils.ts","../src/core/utils/logger.ts","../src/core/analytics/analyticsUtils.ts","../src/instrumentation/core/baseClasses/TdInstrumentationBase.ts","../src/instrumentation/core/baseClasses/TdInstrumentationNodeModule.ts","../src/core/types.ts","../src/core/MemoryStore.ts","../src/core/tracing/SpanUtils.ts","../src/instrumentation/libraries/http/utils/bodyDecompression.ts","../src/instrumentation/libraries/http/utils/binaryDataHandler.ts","../src/core/tracing/JsonSchemaHelper.ts","../src/instrumentation/libraries/http/utils/httpBodyEncoder.ts","../src/instrumentation/libraries/http/mocks/TdHttpMockSocket.ts","../src/instrumentation/core/trackers/EnvVarTracker.ts","../src/instrumentation/core/trackers/DateTracker.ts","../src/instrumentation/core/utils/mockResponseUtils.ts","../src/instrumentation/libraries/http/mocks/TdMockClientRequest.ts","../src/instrumentation/libraries/http/HttpReplayHooks.ts","../src/instrumentation/core/utils/modeUtils.ts","../src/instrumentation/core/utils/selfExclusion.ts","../src/instrumentation/core/utils/shimmerUtils.ts","../src/instrumentation/libraries/http/HttpTransformEngine.ts","../src/instrumentation/libraries/http/Instrumentation.ts","../src/instrumentation/libraries/env/Instrumentation.ts","../src/instrumentation/libraries/date/Instrumentation.ts","../src/instrumentation/core/baseClasses/TdInstrumentationNodeModuleFile.ts","../src/instrumentation/libraries/graphql/utils.ts","../src/instrumentation/libraries/graphql/Instrumentation.ts","../src/instrumentation/libraries/pg/mocks/TdPgClientMock.ts","../src/instrumentation/libraries/pg/Instrumentation.ts","../src/instrumentation/libraries/postgres/Instrumentation.ts","../src/instrumentation/libraries/tcp/Instrumentation.ts","../src/instrumentation/libraries/jsonwebtoken/Instrumentation.ts","../src/instrumentation/libraries/jwks-rsa/Instrumentation.ts","../src/instrumentation/libraries/fetch/Instrumentation.ts","../node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js","../node_modules/@opentelemetry/core/build/src/baggage/constants.js","../node_modules/@opentelemetry/core/build/src/baggage/utils.js","../node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js","../node_modules/@opentelemetry/core/build/src/common/anchored-clock.js","../node_modules/@opentelemetry/core/build/src/common/attributes.js","../node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js","../node_modules/@opentelemetry/core/build/src/common/global-error-handler.js","../node_modules/@opentelemetry/core/build/src/utils/sampling.js","../node_modules/@opentelemetry/core/build/src/platform/browser/globalThis.js","../node_modules/@opentelemetry/core/build/src/utils/environment.js","../node_modules/@opentelemetry/core/build/src/platform/node/environment.js","../node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js","../node_modules/@opentelemetry/core/build/src/platform/node/hex-to-base64.js","../node_modules/@opentelemetry/core/build/src/platform/node/RandomIdGenerator.js","../node_modules/@opentelemetry/core/build/src/platform/node/performance.js","../node_modules/@opentelemetry/core/build/src/version.js","../node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js","../node_modules/@opentelemetry/core/build/src/platform/node/timer-util.js","../node_modules/@opentelemetry/core/build/src/platform/node/index.js","../node_modules/@opentelemetry/core/build/src/platform/index.js","../node_modules/@opentelemetry/core/build/src/common/time.js","../node_modules/@opentelemetry/core/build/src/common/types.js","../node_modules/@opentelemetry/core/build/src/ExportResult.js","../node_modules/@opentelemetry/core/build/src/propagation/composite.js","../node_modules/@opentelemetry/core/build/src/internal/validators.js","../node_modules/@opentelemetry/core/build/src/trace/TraceState.js","../node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js","../node_modules/@opentelemetry/core/build/src/trace/IdGenerator.js","../node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js","../node_modules/@opentelemetry/core/build/src/trace/sampler/AlwaysOffSampler.js","../node_modules/@opentelemetry/core/build/src/trace/sampler/AlwaysOnSampler.js","../node_modules/@opentelemetry/core/build/src/trace/sampler/ParentBasedSampler.js","../node_modules/@opentelemetry/core/build/src/trace/sampler/TraceIdRatioBasedSampler.js","../node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js","../node_modules/@opentelemetry/core/build/src/utils/merge.js","../node_modules/@opentelemetry/core/build/src/utils/timeout.js","../node_modules/@opentelemetry/core/build/src/utils/url.js","../node_modules/@opentelemetry/core/build/src/utils/wrap.js","../node_modules/@opentelemetry/core/build/src/utils/promise.js","../node_modules/@opentelemetry/core/build/src/utils/callback.js","../node_modules/@opentelemetry/core/build/src/internal/exporter.js","../node_modules/@opentelemetry/core/build/src/index.js","../src/core/tracing/TdSpanExporter.ts","../src/core/ProtobufCommunicator.ts","../node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js","../node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js","../node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js","../node_modules/@opentelemetry/context-async-hooks/build/src/index.js","../node_modules/@opentelemetry/propagator-b3/build/src/common.js","../node_modules/@opentelemetry/propagator-b3/build/src/constants.js","../node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js","../node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js","../node_modules/@opentelemetry/propagator-b3/build/src/types.js","../node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js","../node_modules/@opentelemetry/propagator-b3/build/src/index.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/config.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js","../node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js","../node_modules/@opentelemetry/resources/build/src/platform/node/utils.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/execAsync.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId-darwin.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId-linux.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId-bsd.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId-win.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId-unsupported.js","../node_modules/@opentelemetry/resources/build/src/platform/node/machine-id/getMachineId.js","../node_modules/@opentelemetry/resources/build/src/platform/node/HostDetectorSync.js","../node_modules/@opentelemetry/resources/build/src/platform/node/HostDetector.js","../node_modules/@opentelemetry/resources/build/src/platform/node/OSDetectorSync.js","../node_modules/@opentelemetry/resources/build/src/platform/node/OSDetector.js","../node_modules/@opentelemetry/resources/build/src/platform/node/ProcessDetectorSync.js","../node_modules/@opentelemetry/resources/build/src/platform/node/ProcessDetector.js","../node_modules/@opentelemetry/resources/build/src/platform/node/index.js","../node_modules/@opentelemetry/resources/build/src/platform/index.js","../node_modules/@opentelemetry/resources/build/src/Resource.js","../node_modules/@opentelemetry/resources/build/src/IResource.js","../node_modules/@opentelemetry/resources/build/src/types.js","../node_modules/@opentelemetry/resources/build/src/config.js","../node_modules/@opentelemetry/resources/build/src/detectors/BrowserDetector.js","../node_modules/@opentelemetry/resources/build/src/detectors/EnvDetectorSync.js","../node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js","../node_modules/@opentelemetry/resources/build/src/detectors/BrowserDetectorSync.js","../node_modules/@opentelemetry/resources/build/src/detectors/index.js","../node_modules/@opentelemetry/resources/build/src/utils.js","../node_modules/@opentelemetry/resources/build/src/detect-resources.js","../node_modules/@opentelemetry/resources/build/src/index.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/ReadableSpan.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/export/SpanExporter.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/SpanProcessor.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/TimedEvent.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/types.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/IdGenerator.js","../node_modules/@opentelemetry/sdk-trace-base/build/src/index.js","../node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js","../node_modules/@opentelemetry/propagator-jaeger/build/src/index.js","../node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js","../node_modules/@opentelemetry/sdk-trace-node/build/src/index.js","../src/core/MockMatcher.ts","../src/core/TuskDriftInstrumentationModuleNames.ts","../src/core/TuskDrift.ts"],"sourcesContent":["export interface TdInstrumentationConfig {\n enabled?: boolean;\n [key: string]: any;\n}\n\nexport abstract class TdInstrumentationAbstract {\n protected _config: TdInstrumentationConfig;\n protected instrumentationName: string;\n\n constructor(instrumentationName: string, config: TdInstrumentationConfig = {}) {\n this.instrumentationName = instrumentationName;\n this._config = {\n enabled: false,\n ...config,\n };\n }\n\n getConfig(): TdInstrumentationConfig {\n return this._config;\n }\n\n setConfig(config: TdInstrumentationConfig = {}): void {\n this._config = { ...config };\n }\n\n get name(): string {\n return this.instrumentationName;\n }\n\n abstract enable(): void;\n abstract isEnabled(): boolean;\n}\n","{\n \"name\": \"@use-tusk/drift-node-sdk\",\n \"version\": \"0.1.0\",\n \"description\": \"Node.js SDK for Tusk Drift instrumentation and replay\",\n \"type\": \"module\",\n \"files\": [\n \"dist/**\"\n ],\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.cts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"build\": \"npm run typecheck && tsdown\",\n \"build:watch\": \"tsdown --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\",\n \"prepare\": \"npm run build\",\n \"lint\": \"eslint src/**/*.ts\",\n \"test\": \"jest\"\n },\n \"keywords\": [\n \"instrumentation\",\n \"replay\",\n \"nodejs\",\n \"typescript\",\n \"tusk\"\n ],\n \"author\": \"\",\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"@bufbuild/buf\": \"^1.57.0\",\n \"@types/google-protobuf\": \"^3.15.12\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/js-yaml\": \"^4.0.9\",\n \"@types/jsonpath\": \"^0.2.4\",\n \"@types/node\": \"^20.0.0\",\n \"@types/pg\": \"^8.15.5\",\n \"@typescript-eslint/eslint-plugin\": \"^6.0.0\",\n \"@typescript-eslint/parser\": \"^6.0.0\",\n \"eslint\": \"^8.0.0\",\n \"jest\": \"^29.0.0\",\n \"prettier\": \"^3.2.4\",\n \"ts-jest\": \"^29.4.2\",\n \"ts-node\": \"^10.9.2\",\n \"tsc-alias\": \"^1.8.16\",\n \"tsdown\": \"^0.15.0\",\n \"typescript\": \"^5.0.0\"\n },\n \"dependencies\": {\n \"@opentelemetry/api\": \"^1.7.0\",\n \"@opentelemetry/instrumentation\": \"^0.45.0\",\n \"@opentelemetry/instrumentation-http\": \"^0.45.0\",\n \"@opentelemetry/sdk-node\": \"^0.45.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.17.0\",\n \"@protobuf-ts/runtime\": \"^2.11.1\",\n \"@protobuf-ts/runtime-rpc\": \"^2.11.1\",\n \"@protobuf-ts/twirp-transport\": \"^2.11.1\",\n \"@types/semver\": \"^7.7.0\",\n \"@use-tusk/drift-schemas\": \"^0.1.10\",\n \"express\": \"^5.1.0\",\n \"google-protobuf\": \"^4.0.0\",\n \"install\": \"^0.13.0\",\n \"js-yaml\": \"^4.1.0\",\n \"jsonpath\": \"^1.1.1\",\n \"lru-cache\": \"^10.0.0\",\n \"npm\": \"^11.6.0\",\n \"patch-package\": \"^8.0.0\",\n \"pg\": \"^8.16.3\",\n \"postgres\": \"^3.4.7\",\n \"posthog-node\": \"^3.0.0\",\n \"protoc-gen-ts\": \"^0.8.7\",\n \"require-in-the-middle\": \"^7.0.0\",\n \"semver\": \"^7.7.2\"\n },\n \"engines\": {\n \"node\": \">=16.0.0\"\n }\n}\n","import { version } from \"../package.json\";\nexport const SDK_VERSION = version;\n// Developer should update this when there are breaking changes to the current CLI\nexport const MIN_CLI_VERSION = \"0.1.0\";\n","/**\n * Shared data normalization utilities to ensure consistent data processing\n * between recording (span export) and replay (mock request) modes.\n *\n * This utility addresses the issue where recording uses JSON.stringify() which omits\n * undefined values, while replay sends raw objects with undefined values that get\n * converted to explicit null fields in protobuf.\n */\n\n/**\n * Safe JSON stringify that handles circular references\n */\nfunction safeJsonStringify(obj: any): string {\n const seen = new WeakSet();\n return JSON.stringify(obj, (key, value) => {\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n return value;\n });\n}\n\n/**\n * Normalizes input data for consistent processing across recording and replay.\n * This ensures the same data structure is used in both modes by:\n * 1. Filtering out undefined values (like JSON.stringify does)\n * 2. Providing a consistent object structure for hashing\n * 3. Handling circular references safely\n */\nexport function normalizeInputData<T extends Record<string, any>>(inputData: T): T {\n // Use safe JSON.stringify round-trip to match recording behavior\n // This removes undefined values, normalizes the data structure, and handles circular references\n return JSON.parse(safeJsonStringify(inputData)) as T;\n}\n\n/**\n * Creates a normalized input value for span attributes during recording.\n * This should be used instead of direct JSON.stringify to ensure consistency.\n */\nexport function createSpanInputValue(inputData: Record<string, any>): string {\n const normalized = normalizeInputData(inputData);\n return safeJsonStringify(normalized);\n}\n\n/**\n * Creates a normalized input value for mock requests during replay.\n * This ensures the same normalization is applied as during recording.\n */\nexport function createMockInputValue<T extends Record<string, any>>(inputData: T): T {\n return normalizeInputData(inputData);\n}\n","export function shouldSample({\n samplingRate,\n isAppReady,\n}: {\n samplingRate: number;\n isAppReady: boolean;\n}): boolean {\n const random = Math.random();\n if (!isAppReady) {\n // We should still record if app is not ready\n return true;\n }\n return random < samplingRate;\n}\n","import { Value, Struct } from \"@use-tusk/drift-schemas/google/protobuf/struct\";\nimport { SpanKind as OtSpanKind } from \"@opentelemetry/api\";\nimport { SpanKind as PbSpanKind } from \"@use-tusk/drift-schemas/core/span\";\n\nexport const toStruct = (obj: any | undefined) => (obj ? objectToProtobufStruct(obj) : undefined);\n\n// Map OpenTelemetry SpanKind -> protobuf SpanKind\nexport const mapOtToPb = (k: OtSpanKind): PbSpanKind => {\n switch (k) {\n case OtSpanKind.INTERNAL:\n return PbSpanKind.INTERNAL;\n case OtSpanKind.SERVER:\n return PbSpanKind.SERVER;\n case OtSpanKind.CLIENT:\n return PbSpanKind.CLIENT;\n case OtSpanKind.PRODUCER:\n return PbSpanKind.PRODUCER;\n case OtSpanKind.CONSUMER:\n return PbSpanKind.CONSUMER;\n default:\n return PbSpanKind.UNSPECIFIED;\n }\n};\n\n/**\n * Converts a JavaScript object to protobuf Struct format\n */\nexport function objectToProtobufStruct(obj: any): Struct {\n const fields: Record<string, Value> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n fields[key] = valueToProtobufValue(value);\n }\n\n return Struct.create({ fields });\n}\n\n/**\n * Converts a JavaScript value to protobuf Value format\n */\nexport function valueToProtobufValue(value: any): Value {\n if (value === null || value === undefined) {\n return Value.create({ kind: { oneofKind: \"nullValue\", nullValue: 0 } });\n }\n\n if (typeof value === \"boolean\") {\n return Value.create({ kind: { oneofKind: \"boolValue\", boolValue: value } });\n }\n\n if (typeof value === \"number\") {\n return Value.create({ kind: { oneofKind: \"numberValue\", numberValue: value } });\n }\n\n if (typeof value === \"string\") {\n return Value.create({ kind: { oneofKind: \"stringValue\", stringValue: value } });\n }\n\n if (Array.isArray(value)) {\n const listValue = {\n values: value.map((item) => valueToProtobufValue(item)),\n };\n return Value.create({ kind: { oneofKind: \"listValue\", listValue } });\n }\n\n if (typeof value === \"object\" && value !== null) {\n const structValue = objectToProtobufStruct(value);\n return Value.create({ kind: { oneofKind: \"structValue\", structValue } });\n }\n\n // Fallback to string representation for other types\n return Value.create({ kind: { oneofKind: \"stringValue\", stringValue: String(value) } });\n}\n","/**\n * Utility to access original global functions before they are instrumented.\n * This should be imported early in the application lifecycle to capture\n * the original references before any instrumentation occurs.\n *\n * NOTE: this only works for global functions, not for module imports.\n */\n\nconst OriginalDate = globalThis.Date;\nconst OriginalProcessEnv = process.env;\n\nexport class OriginalGlobalUtils {\n /**\n * Get the original Date constructor, unaffected by instrumentation\n */\n static getOriginalDate(): Date {\n return new OriginalDate();\n }\n\n /**\n * Get a specific environment variable using the original process.env\n */\n static getOriginalProcessEnvVar(key: string): string | undefined {\n return OriginalProcessEnv[key];\n }\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport yaml from \"js-yaml\";\nimport { logger } from \"./logger\";\nimport { TransformConfigs } from \"src/instrumentation/libraries/http/HttpTransformEngine\";\n\nexport interface TuskConfig {\n service?: {\n id?: string;\n name?: string;\n port?: number;\n start?: {\n command?: string;\n };\n readiness_check?: {\n command?: string;\n timeout?: string;\n interval?: string;\n };\n };\n traces?: {\n dir?: string;\n };\n tusk_api?: {\n url?: string;\n };\n test_execution?: {\n concurrency?: number;\n timeout?: string;\n };\n comparison?: {\n ignore_fields?: string[];\n };\n recording?: {\n sampling_rate?: number;\n export_spans?: boolean;\n enable_env_var_recording?: boolean;\n enable_analytics?: boolean;\n exclude_paths?: string[];\n };\n transforms?: TransformConfigs;\n}\n\n/**\n * Find project root by traversing up from the current working directory\n * or from the SDK's installation location in node_modules\n */\nfunction findProjectRoot(): string | null {\n let currentDir = process.cwd();\n\n // If we're running from node_modules, traverse up to find the project root\n if (currentDir.includes(\"node_modules\")) {\n // Find the node_modules directory and go up one level\n const nodeModulesIndex = currentDir.indexOf(\"node_modules\");\n if (nodeModulesIndex !== -1) {\n currentDir = currentDir.substring(0, nodeModulesIndex);\n }\n }\n\n // Traverse up to find package.json (indicating project root)\n while (currentDir !== path.dirname(currentDir)) {\n const packageJsonPath = path.join(currentDir, \"package.json\");\n if (fs.existsSync(packageJsonPath)) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n\n return null;\n}\n\n/**\n * Load the Tusk config from .tusk/config.yaml in the customer's project\n * Returns the raw config object without strict typing to allow future extensions\n */\nexport function loadTuskConfig(): TuskConfig | null {\n try {\n const projectRoot = findProjectRoot();\n if (!projectRoot) {\n logger.error(\"Could not find project root. Config loading skipped.\");\n return null;\n }\n\n const configPath = path.join(projectRoot, \".tusk\", \"config.yaml\");\n\n if (!fs.existsSync(configPath)) {\n logger.error(`No config file found at ${configPath}`);\n return null;\n }\n\n logger.debug(`Loading config from ${configPath}`);\n\n const configContent = fs.readFileSync(configPath, \"utf8\");\n const config = yaml.load(configContent) as TuskConfig;\n\n logger.debug(`Successfully loaded config for service: ${config.service?.name || \"unknown\"}`);\n return config;\n } catch (error) {\n logger.error(\"Error loading config:\", error);\n return null;\n }\n}\n","import { OriginalGlobalUtils } from \"./\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\ninterface LoggerConfig {\n logLevel: LogLevel;\n prefix?: string;\n}\n\nclass Logger {\n private config: LoggerConfig;\n private readonly levels = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n };\n\n constructor(config: LoggerConfig) {\n this.config = config;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return this.levels[level] <= this.levels[this.config.logLevel];\n }\n\n private formatMessage(level: LogLevel, message: string): string {\n const currentData = OriginalGlobalUtils.getOriginalDate();\n const timestamp = currentData instanceof Date ? currentData.toISOString() : currentData;\n // const timestamp = new Date().toISOString();\n const prefix = this.config.prefix ? `[${this.config.prefix}] ` : \"[TuskDrift] \";\n return `${timestamp} ${prefix}${message}`;\n }\n\n error(message: string, ...args: any[]): void {\n if (this.shouldLog(\"error\")) {\n console.error(this.formatMessage(\"error\", message), ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.shouldLog(\"warn\")) {\n console.warn(this.formatMessage(\"warn\", message), ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.shouldLog(\"info\")) {\n console.log(this.formatMessage(\"info\", message), ...args);\n }\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.shouldLog(\"debug\")) {\n console.log(this.formatMessage(\"debug\", message), ...args);\n }\n }\n\n setLogLevel(level: LogLevel): void {\n this.config.logLevel = level;\n }\n\n getLogLevel(): LogLevel {\n return this.config.logLevel;\n }\n}\n\n// Global logger instance\nlet globalLogger: Logger;\n\nexport function createLogger(config: LoggerConfig): Logger {\n return new Logger(config);\n}\n\nexport function initializeGlobalLogger(config: LoggerConfig): void {\n globalLogger = createLogger(config);\n}\n\nexport function getLogger(): Logger {\n if (!globalLogger) {\n // Default to warn level if not initialized\n globalLogger = createLogger({ logLevel: \"warn\" });\n }\n return globalLogger;\n}\n\n/**\n * - LogLevel = \"silent\"\n * - No logs are emitted\n * - LogLevel = \"error\"\n * - Logs errors\n * - LogLevel = \"warn\"\n * - Logs warnings and errors\n * - LogLevel = \"info\"\n * - Logs info, warnings, and errors\n * - LogLevel = \"debug\"\n * - Logs debug, info, warnings, and errors\n */\nexport const logger = {\n error: (message: string, ...args: any[]) => getLogger().error(message, ...args),\n warn: (message: string, ...args: any[]) => getLogger().warn(message, ...args),\n info: (message: string, ...args: any[]) => getLogger().info(message, ...args),\n debug: (message: string, ...args: any[]) => getLogger().debug(message, ...args),\n setLogLevel: (level: LogLevel) => getLogger().setLogLevel(level),\n getLogLevel: () => getLogger().getLogLevel(),\n};\n","import { TuskDriftCore } from \"../TuskDrift\";\nimport { SDK_VERSION } from \"../../version\";\nimport { logger } from \"../utils/logger\";\n\ninterface AnalyticsPayload {\n distinctId: string;\n event: string;\n properties: Record<string, any>;\n}\n\nexport function sendAnalyticsPayload(payload: AnalyticsPayload): void {\n try {\n // Only send analytics in production and if explicitly enabled\n if (TuskDriftCore.getInstance().getConfig().recording?.enable_analytics) {\n // TODO: implement this\n }\n } catch (e) {\n logger.error(\"Error sending analytics event:\", e);\n }\n}\n\nexport function sendTdAnalytics(eventName: string, properties: Record<string, any> = {}): void {\n const serviceId = TuskDriftCore.getInstance().getConfig().service?.id || \"unknown-service\";\n\n const payload: AnalyticsPayload = {\n distinctId: `tusk-drift:${serviceId}`,\n event: `${eventName}`,\n properties: {\n serviceId,\n tdMode: TuskDriftCore.getInstance().getMode(),\n sdkVersion: SDK_VERSION,\n ...properties,\n },\n };\n\n sendAnalyticsPayload(payload);\n}\n\n/**\n * NOTE: analytics has not been implemented yet, so this function does nothing\n */\nexport function sendVersionMismatchAlert({\n moduleName,\n foundVersion,\n supportedVersions,\n}: {\n moduleName: string;\n foundVersion: string | undefined;\n supportedVersions: string[];\n}): void {\n try {\n sendTdAnalytics(\"version_mismatch\", {\n moduleName,\n foundVersion: foundVersion || \"unknown\",\n supportedVersions: supportedVersions.join(\", \"),\n });\n } catch (e) {\n logger.error(\"Error sending version mismatch alert:\", e);\n }\n}\n\n/**\n * NOTE: analytics has not been implemented yet, so this function does nothing\n */\nexport function sendUnpatchedDependencyAlert({\n method,\n spanId,\n traceId,\n stackTrace,\n}: {\n method: string;\n spanId: string;\n traceId: string;\n stackTrace?: string;\n}): void {\n try {\n sendTdAnalytics(\"unpatched_dependency\", {\n method,\n spanId,\n traceId,\n stackTrace: stackTrace ? stackTrace.split(\"\\n\").slice(0, 10).join(\"\\n\") : undefined, // Limit stack trace size\n });\n } catch (e) {\n logger.error(\"Error sending unpatched dependency alert:\", e);\n }\n}\n","import path from \"path\";\nimport { satisfies } from \"semver\";\nimport { TdInstrumentationAbstract, TdInstrumentationConfig } from \"./TdInstrumentationAbstract\";\nimport { TdInstrumentationNodeModule } from \"./TdInstrumentationNodeModule\";\nimport { Hook, HookOptions } from \"require-in-the-middle\";\nimport { sendVersionMismatchAlert } from \"../../../core/analytics\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport abstract class TdInstrumentationBase extends TdInstrumentationAbstract {\n protected _modules: TdInstrumentationNodeModule[] = [];\n protected _enabled = false;\n\n constructor(instrumentationName: string, config: TdInstrumentationConfig = {}) {\n super(instrumentationName, config);\n\n let modules = this.init();\n if (modules && !Array.isArray(modules)) {\n modules = [modules];\n }\n this._modules = modules || [];\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n\n abstract init(): TdInstrumentationNodeModule | TdInstrumentationNodeModule[] | void;\n\n /**\n * Check if the provided version matches any of the supported versions\n * @param supportedVersions - Array of version patterns (e.g. [\"^1.0.0\", \"2.x\"])\n * @param version - The actual version to check (e.g. \"1.2.3\")\n * @param includePrerelease - Whether to include prerelease versions\n * @returns true if version is supported, false otherwise\n */\n isSupported(supportedVersions: string[], version?: string, includePrerelease = false): boolean {\n if (typeof version === \"undefined\") {\n return supportedVersions.includes(\"*\");\n }\n if (version === \"any\") {\n return true;\n }\n return supportedVersions.some((supportedVersion) =>\n satisfies(version, supportedVersion, {\n includePrerelease,\n }),\n );\n }\n\n /**\n * Extract package version from package.json in the given base directory\n * @param baseDir - Base directory containing package.json\n * @returns Version string or undefined if not found\n */\n private _extractPackageVersion(baseDir?: string): string | undefined {\n if (!baseDir) {\n return undefined;\n }\n try {\n const packagePath = path.join(baseDir, \"package.json\");\n const { version } = require(packagePath);\n return typeof version === \"string\" ? version : undefined;\n } catch (error) {\n logger.warn(`Failed extracting version from ${baseDir}:`, error);\n }\n return undefined;\n }\n\n enable(): void {\n if (this._enabled) {\n return;\n }\n this._enabled = true;\n\n // Set up require-in-the-middle hooks for each module\n for (const module of this._modules) {\n // Also set up hook for future requires\n const onRequire = (exports: any, name: string, baseDir?: string) => {\n return this._onRequire(module, exports, name, baseDir);\n };\n\n const hookOptions: HookOptions = { internals: true };\n new Hook([module.name], hookOptions, onRequire);\n }\n }\n\n isEnabled(): boolean {\n return this._enabled;\n }\n\n private _onRequire(\n module: TdInstrumentationNodeModule,\n exports: any,\n name: string,\n baseDir?: string,\n ): any {\n // baseDir set by require-in-the-middle\n if (!baseDir) {\n if (typeof module.patch === \"function\") {\n module.moduleExports = exports;\n if (this._enabled) {\n logger.debug(`Patching module ${name} (no version info available)`);\n return module.patch(exports);\n }\n }\n return exports;\n }\n\n const version = this._extractPackageVersion(baseDir);\n module.moduleVersion = version;\n\n if (module.name === name) {\n if (\n this.isSupported(module.supportedVersions, version) &&\n typeof module.patch === \"function\"\n ) {\n module.moduleExports = exports;\n if (this._enabled) {\n logger.debug(\n `Patching main module ${name} v${version} for instrumentation ${this.instrumentationName}`,\n );\n return module.patch(exports, module.moduleVersion);\n }\n } else if (version) {\n // Check if ANY module for this package name supports this version before logging/alerting\n const isVersionSupportedByAnyModule = this._modules\n .filter((m) => m.name === name)\n .some((m) => this.isSupported(m.supportedVersions, version));\n\n if (!isVersionSupportedByAnyModule) {\n logger.error(\n `Version mismatch for module ${name}: found v${version}, supported versions: [${module.supportedVersions.join(\", \")}]. Please contact support@usetusk.ai to add support for this version.`,\n );\n sendVersionMismatchAlert({\n moduleName: name,\n foundVersion: version,\n supportedVersions: module.supportedVersions,\n });\n }\n } else {\n logger.error(\n `No version found for module ${name}, supported versions: [${module.supportedVersions.join(\", \")}]. Please contact support@usetusk.ai to add support for this version.`,\n );\n sendVersionMismatchAlert({\n moduleName: name,\n foundVersion: undefined,\n supportedVersions: module.supportedVersions,\n });\n }\n return exports;\n }\n\n // Handle file-level patching\n const files = module.files ?? [];\n const normalizedName = path.normalize(name);\n const supportedFileInstrumentations = files\n .filter((f) => f.name === normalizedName)\n .filter((f) => this.isSupported(f.supportedVersions, version, false));\n\n // Only log file version mismatch if NO module supports this file for this version\n if (\n supportedFileInstrumentations.length === 0 &&\n files.some((f) => f.name === normalizedName)\n ) {\n // Check if ANY module in this instrumentation has a file that supports this version\n const isFileSupportedByAnyModule = this._modules\n .flatMap((m) => m.files || [])\n .filter((f) => f.name === normalizedName)\n .some((f) => this.isSupported(f.supportedVersions, version, false));\n\n if (!isFileSupportedByAnyModule) {\n logger.error(\n `Version mismatch for file ${normalizedName}: found v${version}, no compatible file instrumentation found. Please contact support@usetusk.ai to add support for this version.`,\n );\n sendVersionMismatchAlert({\n moduleName: normalizedName,\n foundVersion: version,\n supportedVersions: files.flatMap((f) => f.supportedVersions),\n });\n }\n }\n\n return supportedFileInstrumentations.reduce((patchedExports, file) => {\n file.moduleExports = patchedExports;\n if (this._enabled) {\n logger.debug(\n `Patching file ${file.name} v${version} for instrumentation ${this.instrumentationName}`,\n );\n return file.patch(patchedExports, module.moduleVersion);\n }\n return patchedExports;\n }, exports);\n }\n}\n","import { TdInstrumentationNodeModuleFile, PatchFunction } from \"./TdInstrumentationNodeModuleFile\";\n\nexport class TdInstrumentationNodeModule {\n name: string;\n supportedVersions: string[];\n patch?: PatchFunction;\n files: TdInstrumentationNodeModuleFile[];\n moduleExports?: any;\n moduleVersion?: string;\n\n constructor({\n name,\n supportedVersions,\n patch,\n files,\n }: {\n name: string;\n supportedVersions: string[];\n patch?: PatchFunction;\n files?: TdInstrumentationNodeModuleFile[];\n }) {\n this.name = name;\n this.supportedVersions = supportedVersions;\n this.patch = patch;\n this.files = files ?? [];\n }\n}\n","import { createContextKey } from \"@opentelemetry/api\";\nimport { StatusCode, PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { SpanKind } from \"@opentelemetry/api\";\n\nexport const REPLAY_TRACE_ID_CONTEXT_KEY = createContextKey(\"td.replayTraceId\");\nexport const SPAN_KIND_CONTEXT_KEY = createContextKey(\"td.spanKind\");\nexport const IS_PRE_APP_START_CONTEXT_KEY = createContextKey(\"td.isPreAppStart\");\nexport const CALLING_LIBRARY_CONTEXT_KEY = createContextKey(\"td.callingLibrary\");\n\nexport enum TdSpanAttributes {\n /**\n * Presentational information:\n * - packageType: is the langauge agnostic type that will be used to classify the package\n * - name: is the visual name of the span (e.g. for http could be \"/api/users\", for graphql could be \"update UpdateUser\")\n *\n * - packageName: is the name of the package that is instrumented and can be specific to a language\n * - instrumentationName: is the name of the instrumentation class\n * - submoduleName: is the name of the submodule that is instrumented (e.g. \"GET\", \"query\", \"execute\", \"get\", etc.)\n *\n * Example 1: fetch package\n *\n * name: \"/api/users\"\n * packageType: HTTP\n * packageName: \"fetch\"\n * instrumentationName: \"FetchInstrumentation\"\n * submoduleName: \"GET\"\n *\n * Example 2: graphql package\n *\n * name: \"update UpdateUser\"\n * packageType: GRAPHQL\n * packageName: \"http\"\n * instrumentationName: \"HttpInstrumentation\"\n * submoduleName: \"execute\"\n */\n NAME = \"td.name\",\n PACKAGE_TYPE = \"td.packageType\",\n PACKAGE_NAME = \"td.packageName\",\n INSTRUMENTATION_NAME = \"td.instrumentationName\",\n SUBMODULE_NAME = \"td.submodule\",\n IS_PRE_APP_START = \"td.isPreAppStart\",\n\n INPUT_VALUE = \"td.inputValue\",\n OUTPUT_VALUE = \"td.outputValue\",\n INPUT_SCHEMA_MERGES = \"td.inputSchemaMerges\",\n OUTPUT_SCHEMA_MERGES = \"td.outputSchemaMerges\",\n METADATA = \"td.metadata\",\n TRANSFORM_METADATA = \"td.transformMetadata\",\n}\n\nexport type CleanSpanData = {\n traceId: string;\n spanId: string;\n parentSpanId: string;\n name: string;\n\n packageName: string;\n instrumentationName: string;\n submoduleName: string;\n\n packageType?: PackageType;\n\n // keep these as plain JSON for readability\n inputValue: any;\n outputValue: any;\n inputSchema: any;\n outputSchema: any;\n\n inputSchemaHash: string;\n outputSchemaHash: string;\n inputValueHash: string;\n outputValueHash: string;\n\n kind: SpanKind;\n\n status: {\n code: StatusCode;\n message: string;\n };\n\n isPreAppStart: boolean;\n\n timestamp: { seconds: number; nanos: number };\n duration: { seconds: number; nanos: number };\n\n isRootSpan: boolean;\n\n metadata?: MetadataObject;\n transformMetadata?: {\n transformed: boolean;\n actions: Array<{\n type: \"redact\" | \"mask\" | \"replace\" | \"drop\";\n field: string;\n reason: string;\n description?: string;\n }>;\n };\n // sdk-specific\n isUsed?: boolean;\n};\n\nexport type MockRequestData = {\n traceId: string;\n spanId: string;\n name: string;\n packageName: string;\n packageType?: PackageType;\n instrumentationName: string;\n submoduleName: string;\n inputValue: any;\n kind: SpanKind;\n};\n\nexport type MetadataObject = {\n ENV_VARS?: Record<string, any>;\n};\n\nexport type OneOf<T extends object> = {\n [K in keyof T]: Required<Pick<T, K>> & Partial<Record<Exclude<keyof T, K>, null>>;\n}[keyof T];\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { CleanSpanData } from \"./types\";\nimport { logger } from \"./utils/logger\";\n\nexport interface HttpReplayResult {\n statusCode: number;\n headers: Record<string, any>;\n body: any;\n bodyEncoding?: string;\n [key: string]: any;\n}\n\n/**\n * Memory store singleton that provides access to mocks stored in the filesystem\n * and manages replay mappings for HTTP requests\n */\nexport class MemoryStore {\n private static instance: MemoryStore;\n private baseDirectory: string = \"\";\n private initialized = false;\n\n /**\n * Maps trace id to its replayed mocks\n */\n private requestReplayMockMap: Map<string, CleanSpanData[]> = new Map();\n\n /**\n * Cache for loaded mock files to avoid repeated filesystem reads\n */\n private mockFileCache: Map<string, CleanSpanData[]> = new Map();\n\n private constructor() {\n // Private constructor for singleton pattern\n }\n\n static getInstance(): MemoryStore {\n if (!MemoryStore.instance) {\n MemoryStore.instance = new MemoryStore();\n }\n return MemoryStore.instance;\n }\n\n /**\n * Initialize the memory store with a base directory\n *\n * Creates a mapping between file path (jsonl file of all mocks for a trace) and the mock data (CleanSpanData[])\n */\n initialize(baseDirectory: string): void {\n if (this.initialized) {\n logger.debug(\"MemoryStore already initialized, skipping...\");\n return;\n }\n\n this.baseDirectory = path.resolve(baseDirectory);\n this.initialized = true;\n\n logger.debug(`MemoryStore initialized with base directory: ${this.baseDirectory}`);\n\n // Preload mocks if directory exists\n if (fs.existsSync(this.baseDirectory)) {\n this.preloadMocks();\n } else {\n logger.debug(`MemoryStore base directory does not exist: ${this.baseDirectory}`);\n }\n }\n\n /**\n * Preload all mock files from the base directory\n */\n private preloadMocks(): void {\n try {\n const files = this.getAllMockFiles();\n logger.debug(`MemoryStore found ${files.length} mock files to preload`);\n\n for (const filePath of files) {\n this.loadMockFile(filePath);\n }\n\n logger.debug(`MemoryStore preloaded ${this.mockFileCache.size} mock files`);\n } catch (error) {\n logger.error(\"MemoryStore error preloading mocks:\", error);\n }\n }\n\n /**\n * Get all mock files from the base directory recursively\n */\n private getAllMockFiles(): string[] {\n const mockFiles: string[] = [];\n\n const walkDir = (dirPath: string) => {\n try {\n const entries = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n walkDir(fullPath);\n } else if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n mockFiles.push(fullPath);\n }\n }\n } catch (error) {\n logger.error(`MemoryStore error reading directory ${dirPath}:`, error);\n }\n };\n\n walkDir(this.baseDirectory);\n return mockFiles;\n }\n\n /**\n * Load and parse a mock file (JSONL format)\n */\n private loadMockFile(filePath: string): CleanSpanData[] | null {\n try {\n // Check cache first\n if (this.mockFileCache.has(filePath)) {\n return this.mockFileCache.get(filePath)!;\n }\n\n const fileContent = fs.readFileSync(filePath, \"utf8\");\n const mockData: CleanSpanData[] = [];\n\n // Parse JSONL format - one JSON object per line\n const lines = fileContent.split(\"\\n\").filter((line) => line.trim());\n\n for (const line of lines) {\n try {\n const jsonObject = JSON.parse(line);\n\n const mockDataItem: CleanSpanData = {\n ...jsonObject,\n };\n\n mockData.push(mockDataItem);\n } catch (lineError) {\n logger.error(`MemoryStore error parsing line in ${filePath}:`, lineError);\n }\n }\n\n // Validate that we have valid mock data\n if (mockData.length === 0) {\n logger.error(`MemoryStore no valid mock data found in: ${filePath}`);\n return null;\n }\n\n // Cache the loaded data\n this.mockFileCache.set(filePath, mockData);\n\n return mockData;\n } catch (error) {\n logger.error(`MemoryStore error loading mock file ${filePath}:`, error);\n return null;\n }\n }\n\n /**\n * Create a replay mock mapping for a specific trace ID\n */\n createRequestReplayMockMap(traceId: string): void {\n if (!this.initialized) {\n logger.error(\"MemoryStore not initialized. Call initialize() first.\");\n return;\n }\n\n // Find all mocks related to this trace ID\n const relatedMocks: CleanSpanData[] = [];\n\n for (const [_, mocks] of this.mockFileCache.entries()) {\n const matchingMocks = mocks.filter((mock) => mock.traceId === traceId);\n relatedMocks.push(...matchingMocks);\n }\n\n if (relatedMocks.length > 0) {\n this.requestReplayMockMap.set(traceId, relatedMocks);\n } else {\n logger.debug(`MemoryStore no mocks found for trace ${traceId}`);\n }\n }\n\n /**\n * Get replay mocks for a specific trace ID\n */\n getRequestReplayMocks(traceId: string): CleanSpanData[] | undefined {\n return this.requestReplayMockMap.get(traceId);\n }\n\n markAllMocksAsUnused(traceId: string): void {\n const mocks = this.getRequestReplayMocks(traceId);\n if (!mocks) {\n logger.debug(`MemoryStore no mocks available for marking as unused: ${traceId}`);\n return;\n }\n\n mocks.forEach((mock) => {\n mock.isUsed = false;\n });\n }\n\n /**\n * Check if the memory store is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n}\n\n// Export singleton instance\nexport const memoryStore = MemoryStore.getInstance();\n","import {\n trace,\n context,\n Span,\n SpanStatusCode,\n SpanKind,\n Context,\n Attributes,\n SpanStatus,\n} from \"@opentelemetry/api\";\nimport {\n IS_PRE_APP_START_CONTEXT_KEY,\n MetadataObject,\n REPLAY_TRACE_ID_CONTEXT_KEY,\n SPAN_KIND_CONTEXT_KEY,\n TdSpanAttributes,\n} from \"../types\";\nimport { memoryStore } from \"../MemoryStore\";\nimport { TuskDriftCore, TuskDriftMode } from \"../TuskDrift\";\nimport { createSpanInputValue } from \"../utils/dataNormalizationUtils\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { SchemaMerges } from \"./JsonSchemaHelper\";\nimport { logger } from \"../utils/logger\";\n\nexport interface SpanInfo {\n traceId: string;\n spanId: string;\n span: Span;\n context: Context;\n isPreAppStart: boolean;\n}\n\nexport interface CreateSpanOptions {\n name: string;\n kind: SpanKind;\n attributes?: Attributes;\n parentContext?: Context;\n isPreAppStart: boolean;\n}\n\nexport interface SpanExecutorOptions {\n name: string;\n kind: SpanKind;\n packageType?: PackageType;\n packageName: string;\n instrumentationName: string;\n submodule: string;\n inputValue: Record<string, any>;\n isPreAppStart: boolean;\n inputSchemaMerges?: SchemaMerges;\n metadata?: MetadataObject;\n}\n\nexport interface AddSpanAttributesOptions {\n name?: string;\n packageName?: string;\n instrumentationName?: string;\n packageType?: PackageType;\n submodule?: string;\n isPreAppStart?: boolean;\n inputValue?: Record<string, any>;\n outputValue?: Record<string, any>;\n inputSchemaMerges?: SchemaMerges;\n outputSchemaMerges?: SchemaMerges;\n metadata?: MetadataObject;\n transformMetadata?: {\n transformed: boolean;\n actions: Array<{\n type: \"redact\" | \"mask\" | \"replace\" | \"drop\";\n field: string;\n reason: string;\n description?: string;\n }>;\n };\n}\n\nexport class SpanUtils {\n /**\n * Creates a new span and returns span info including trace ID and span ID\n */\n static createSpan(options: CreateSpanOptions): SpanInfo | null {\n try {\n // Get tracer from the global trace API\n const tracer = TuskDriftCore.getInstance().getTracer();\n const parentContext = options.parentContext || context.active();\n\n // We can add a bunch of attributes to the span here, everything we want to store in tusk drift backend\n const span = tracer.startSpan(\n options.name,\n {\n kind: options.kind || SpanKind.CLIENT,\n attributes: options.attributes || {},\n },\n parentContext,\n );\n\n const spanContext = span.spanContext();\n\n const newContext = trace\n .setSpan(parentContext, span)\n // This will be used by TCP instrumentation to determine if we have unpatched dependencies\n .setValue(SPAN_KIND_CONTEXT_KEY, options.kind)\n .setValue(IS_PRE_APP_START_CONTEXT_KEY, options.isPreAppStart);\n\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n span,\n context: newContext,\n isPreAppStart: options.isPreAppStart,\n };\n } catch (error) {\n logger.error(\"SpanUtils error creating span:\", error);\n return null;\n }\n }\n\n /**\n * Executes a function within a span context\n */\n static withSpan<T>(spanInfo: SpanInfo, fn: () => T): T {\n return context.with(spanInfo.context, fn);\n }\n\n /**\n * Execute a function within a properly configured span\n *\n * If there is an error creating the span:\n * - In record mode, the original function will be called\n * - In replay mode, an error will be thrown\n *\n * @param mode The mode of the TuskDrift instance\n * @param originalFunctionCall The function to call if the span is not created\n * @param options Span configuration options\n * @param fn Function to execute within the span\n * @param contextTarget Optional target object to inject trace context into (for HTTP/fetch)\n * @returns The result of the function execution\n */\n static createAndExecuteSpan<T>(\n mode: TuskDriftMode,\n originalFunctionCall: () => T,\n options: SpanExecutorOptions,\n fn: (spanInfo: SpanInfo) => T,\n ): T {\n const {\n name,\n kind,\n packageName,\n instrumentationName,\n packageType,\n submodule,\n inputValue,\n inputSchemaMerges,\n isPreAppStart,\n metadata,\n } = options;\n\n let spanInfo: SpanInfo | null = null;\n\n try {\n // Create span with standard attributes\n spanInfo = SpanUtils.createSpan({\n name,\n kind,\n isPreAppStart: options.isPreAppStart,\n attributes: {\n [TdSpanAttributes.NAME]: name,\n [TdSpanAttributes.PACKAGE_NAME]: packageName,\n [TdSpanAttributes.SUBMODULE_NAME]: submodule,\n [TdSpanAttributes.INSTRUMENTATION_NAME]: instrumentationName,\n [TdSpanAttributes.PACKAGE_TYPE]: packageType,\n [TdSpanAttributes.INPUT_VALUE]: createSpanInputValue(inputValue),\n [TdSpanAttributes.IS_PRE_APP_START]: isPreAppStart,\n ...(inputSchemaMerges && {\n [TdSpanAttributes.INPUT_SCHEMA_MERGES]: JSON.stringify(inputSchemaMerges),\n }),\n ...(metadata && {\n [TdSpanAttributes.METADATA]: JSON.stringify(metadata),\n }),\n },\n });\n } catch (error) {\n logger.error(\"SpanExecutor error creating span:\", error);\n spanInfo = null;\n }\n\n if (!spanInfo) {\n if (mode === TuskDriftMode.REPLAY) {\n // Safe to throw error since we're in replay mode\n throw new Error(\"Error creating span in replay mode\");\n } else {\n // Call the original function, don't want SDK errors to propagate to the user\n return originalFunctionCall();\n }\n }\n\n // Execute function within span context\n return SpanUtils.withSpan(spanInfo, () => fn(spanInfo));\n }\n\n /**\n * Gets the current active span info\n */\n static getCurrentSpanInfo(): SpanInfo | null {\n try {\n const activeSpan = trace.getActiveSpan();\n if (!activeSpan) {\n return null;\n }\n\n const spanContext = activeSpan.spanContext();\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n span: activeSpan,\n context: context.active(),\n isPreAppStart: context.active().getValue(IS_PRE_APP_START_CONTEXT_KEY) as boolean,\n };\n } catch (error) {\n logger.error(\"SpanUtils error getting current span info:\", error);\n return null;\n }\n }\n\n /**\n * Adds attributes to a span\n */\n static addSpanAttributes(span: Span, addSpanAttributesOptions: AddSpanAttributesOptions): void {\n try {\n const attributes: Attributes = {\n ...(addSpanAttributesOptions.name && {\n [TdSpanAttributes.NAME]: addSpanAttributesOptions.name,\n }),\n ...(addSpanAttributesOptions.packageName && {\n [TdSpanAttributes.PACKAGE_NAME]: addSpanAttributesOptions.packageName,\n }),\n ...(addSpanAttributesOptions.instrumentationName && {\n [TdSpanAttributes.INSTRUMENTATION_NAME]: addSpanAttributesOptions.instrumentationName,\n }),\n ...(addSpanAttributesOptions.packageType && {\n [TdSpanAttributes.PACKAGE_TYPE]: addSpanAttributesOptions.packageType,\n }),\n ...(addSpanAttributesOptions.submodule && {\n [TdSpanAttributes.SUBMODULE_NAME]: addSpanAttributesOptions.submodule,\n }),\n ...(addSpanAttributesOptions.isPreAppStart && {\n [TdSpanAttributes.IS_PRE_APP_START]: addSpanAttributesOptions.isPreAppStart,\n }),\n ...(addSpanAttributesOptions.inputValue && {\n [TdSpanAttributes.INPUT_VALUE]: createSpanInputValue(addSpanAttributesOptions.inputValue),\n }),\n ...(addSpanAttributesOptions.outputValue && {\n [TdSpanAttributes.OUTPUT_VALUE]: JSON.stringify(addSpanAttributesOptions.outputValue),\n }),\n ...(addSpanAttributesOptions.inputSchemaMerges && {\n [TdSpanAttributes.INPUT_SCHEMA_MERGES]: JSON.stringify(\n addSpanAttributesOptions.inputSchemaMerges,\n ),\n }),\n ...(addSpanAttributesOptions.outputSchemaMerges && {\n [TdSpanAttributes.OUTPUT_SCHEMA_MERGES]: JSON.stringify(\n addSpanAttributesOptions.outputSchemaMerges,\n ),\n }),\n ...(addSpanAttributesOptions.metadata && {\n [TdSpanAttributes.METADATA]: JSON.stringify(addSpanAttributesOptions.metadata),\n }),\n ...(addSpanAttributesOptions.transformMetadata && {\n [TdSpanAttributes.TRANSFORM_METADATA]: JSON.stringify(\n addSpanAttributesOptions.transformMetadata,\n ),\n }),\n };\n span.setAttributes(attributes);\n } catch (error) {\n logger.error(\"SpanUtils error adding span attributes:\", error);\n }\n }\n\n static setStatus(span: Span, status: SpanStatus): void {\n try {\n span.setStatus(status);\n } catch (error) {\n logger.error(\"SpanUtils error setting span status:\", error);\n }\n }\n\n /**\n * Sets span status and ends the span\n *\n * Spans are only exported once span.end() is called\n */\n static endSpan(span: Span, status?: { code: SpanStatusCode; message?: string }): void {\n try {\n if (status) {\n span.setStatus(status);\n }\n span.end();\n } catch (error) {\n logger.error(\"SpanUtils error ending span:\", error);\n }\n }\n\n /**\n * Extracts trace ID from current context\n */\n static getCurrentTraceId(): string | null {\n try {\n const spanInfo = SpanUtils.getCurrentSpanInfo();\n return spanInfo?.traceId || null;\n } catch (error) {\n logger.error(\"SpanUtils error getting current trace id:\", error);\n return null;\n }\n }\n\n static setCurrentReplayTraceId(replayTraceId: string): Context | null {\n // Reset unused mocks for this trace\n try {\n memoryStore.markAllMocksAsUnused(replayTraceId);\n return context.active().setValue(REPLAY_TRACE_ID_CONTEXT_KEY, replayTraceId);\n } catch (error) {\n logger.error(\"SpanUtils error setting current replay trace id:\", error);\n return null;\n }\n }\n\n /**\n * Gets the current replay trace ID from the context\n */\n static getCurrentReplayTraceId(): string | null {\n try {\n const activeContext = context.active();\n return activeContext.getValue(REPLAY_TRACE_ID_CONTEXT_KEY) as string | null;\n } catch (error) {\n logger.error(\"SpanUtils error getting current replay trace id:\", error);\n return null;\n }\n }\n\n /**\n * Extracts span ID from current context\n */\n static getCurrentSpanId(): string | null {\n try {\n const spanInfo = SpanUtils.getCurrentSpanInfo();\n return spanInfo?.spanId || null;\n } catch (error) {\n logger.error(\"SpanUtils error getting current span id:\", error);\n return null;\n }\n }\n\n /**\n * Gets trace and span IDs as a combined string for logging\n */\n static getTraceInfo(): string {\n let traceId = null;\n let spanId = null;\n try {\n traceId = SpanUtils.getCurrentTraceId();\n spanId = SpanUtils.getCurrentSpanId();\n } catch (error) {\n logger.error(\"SpanUtils error getting trace info:\", error);\n return \"no-trace\";\n }\n\n if (traceId && spanId) {\n return `trace=${traceId} span=${spanId}`;\n }\n\n return \"no-trace\";\n }\n}\n","import * as zlib from \"zlib\";\nimport { logger } from \"../../../../core/utils/logger\";\n\n/**\n * Supported compression encodings and their corresponding zlib decompression functions\n */\nconst ENCODING_FUNCTION_MAP = {\n gzip: \"gunzip\",\n deflate: \"inflate\",\n br: \"brotliDecompress\",\n} as const;\n\ntype SupportedEncoding = keyof typeof ENCODING_FUNCTION_MAP;\n\n/**\n * Decompresses a buffer using the specified encoding\n *\n * @param buffer - The compressed buffer to decompress\n * @param encoding - The compression encoding (gzip, deflate, br)\n * @returns Promise<Buffer> - The decompressed buffer\n */\nexport async function decompressBuffer(buffer: Buffer, encoding: string): Promise<Buffer> {\n const normalizedEncoding = encoding.toLowerCase().trim() as SupportedEncoding;\n\n if (normalizedEncoding in ENCODING_FUNCTION_MAP) {\n return new Promise((resolve, reject) => {\n const zlibFunction = ENCODING_FUNCTION_MAP[normalizedEncoding];\n (zlib as any)[zlibFunction](buffer, (err: Error | null, decoded: Buffer) => {\n if (err) {\n reject(err);\n } else {\n resolve(decoded);\n }\n });\n });\n }\n\n logger.debug(`Unknown encoding: ${encoding} - skipping decoding.`);\n return Promise.resolve(buffer);\n}\n\n/**\n * Checks if a string represents a supported compression encoding\n *\n * @param encoding - The encoding string to check\n * @returns boolean - True if the encoding is supported\n */\nexport function isSupportedEncoding(encoding: string): boolean {\n const normalizedEncoding = encoding.toLowerCase().trim();\n return normalizedEncoding in ENCODING_FUNCTION_MAP;\n}\n\nexport function normalizeHeaders(headers: Record<string, any>): Record<string, any> {\n const normalized: Record<string, any> = {};\n for (const [name, value] of Object.entries(headers)) {\n normalized[name.toLowerCase()] = value;\n }\n return normalized;\n}\n","/**\n * Utility functions for handling binary data and encoding detection\n */\n\n/**\n * Checks if a buffer contains valid UTF-8 text\n * Uses TextDecoder with fatal flag\n *\n * @param buffer - The buffer to check\n * @returns boolean - True if the buffer contains valid UTF-8 text\n */\nexport function isUtf8(buffer: Buffer): boolean {\n if (buffer.length === 0) {\n return true;\n }\n\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n try {\n // If this succeeds, the buffer contains valid UTF-8\n decoder.decode(buffer);\n return true;\n } catch (error) {\n // If this fails, the buffer contains invalid UTF-8 (likely binary)\n return false;\n }\n}\n\n/**\n * Safely converts a buffer to string using appropriate encoding\n *\n * @param buffer - The buffer to convert\n * @returns object with content and encoding used\n */\nexport function bufferToString(buffer: Buffer): { content: string; encoding: \"utf8\" | \"base64\" } {\n if (isUtf8(buffer)) {\n return {\n content: buffer.toString(\"utf8\"),\n encoding: \"utf8\",\n };\n } else {\n return {\n content: buffer.toString(\"base64\"),\n encoding: \"base64\",\n };\n }\n}\n\n/**\n * Safely combines multiple chunks into a single buffer\n *\n * @param chunks - Array of chunks (can be strings or Buffers)\n * @returns Buffer - Combined buffer\n */\nexport function combineChunks(chunks: (string | Buffer)[]): Buffer {\n const buffers: Buffer[] = chunks.map((chunk) => {\n if (Buffer.isBuffer(chunk)) {\n return chunk;\n }\n return Buffer.from(chunk);\n });\n\n return Buffer.concat(buffers);\n}\n","import * as crypto from \"crypto\";\nimport { logger } from \"../utils/logger\";\n\nexport enum JsonSchemaType {\n NUMBER = \"NUMBER\",\n STRING = \"STRING\",\n BOOLEAN = \"BOOLEAN\",\n NULL = \"NULL\",\n UNDEFINED = \"UNDEFINED\",\n OBJECT = \"OBJECT\",\n ORDERED_LIST = \"ORDERED_LIST\",\n UNORDERED_LIST = \"UNORDERED_LIST\",\n FUNCTION = \"FUNCTION\",\n}\n\n// Standardized schema type mapping\nconst jsToJsonSchemaTypeMapping = {\n [\"long\"]: JsonSchemaType.NUMBER,\n [\"undefined\"]: JsonSchemaType.UNDEFINED,\n [\"string\"]: JsonSchemaType.STRING,\n [\"number\"]: JsonSchemaType.NUMBER,\n [\"Number\"]: JsonSchemaType.NUMBER,\n [\"boolean\"]: JsonSchemaType.BOOLEAN,\n [\"null\"]: JsonSchemaType.NULL,\n [\"bigint\"]: JsonSchemaType.NUMBER,\n [\"Error\"]: JsonSchemaType.OBJECT,\n [\"function\"]: JsonSchemaType.FUNCTION,\n [\"RegExp\"]: JsonSchemaType.OBJECT,\n [\"Set\"]: JsonSchemaType.UNORDERED_LIST,\n [\"symbol\"]: JsonSchemaType.STRING,\n [\"Date\"]: JsonSchemaType.STRING,\n [\"Int8Array\"]: JsonSchemaType.STRING,\n [\"Uint8Array\"]: JsonSchemaType.STRING,\n [\"Uint8ClampedArray\"]: JsonSchemaType.STRING,\n [\"Int16Array\"]: JsonSchemaType.STRING,\n [\"Uint16Array\"]: JsonSchemaType.STRING,\n [\"Int32Array\"]: JsonSchemaType.STRING,\n [\"Uint32Array\"]: JsonSchemaType.STRING,\n [\"Float32Array\"]: JsonSchemaType.STRING,\n [\"Float64Array\"]: JsonSchemaType.STRING,\n [\"DataView\"]: JsonSchemaType.STRING,\n [\"ArrayBuffer\"]: JsonSchemaType.STRING,\n [\"object\"]: JsonSchemaType.OBJECT,\n [\"Object\"]: JsonSchemaType.OBJECT,\n [\"Map\"]: JsonSchemaType.OBJECT,\n [\"Array\"]: JsonSchemaType.ORDERED_LIST,\n [\"Arguments\"]: JsonSchemaType.ORDERED_LIST,\n} as const;\n\nexport enum EncodingType {\n BASE64 = \"BASE64\",\n}\n\nexport enum DecodedType {\n JSON = \"JSON\",\n HTML = \"HTML\",\n CSS = \"CSS\",\n JAVASCRIPT = \"JAVASCRIPT\",\n XML = \"XML\",\n YAML = \"YAML\",\n MARKDOWN = \"MARKDOWN\",\n CSV = \"CSV\",\n SQL = \"SQL\",\n GRAPHQL = \"GRAPHQL\",\n PLAIN_TEXT = \"PLAIN_TEXT\",\n FORM_DATA = \"FORM_DATA\",\n MULTIPART_FORM = \"MULTIPART_FORM\",\n PDF = \"PDF\",\n AUDIO = \"AUDIO\",\n VIDEO = \"VIDEO\",\n GZIP = \"GZIP\",\n BINARY = \"BINARY\",\n JPEG = \"JPEG\",\n PNG = \"PNG\",\n GIF = \"GIF\",\n WEBP = \"WEBP\",\n SVG = \"SVG\",\n ZIP = \"ZIP\",\n}\n\nexport interface JsonSchema {\n type: JsonSchemaType;\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema | null;\n encoding?: EncodingType;\n decodedType?: DecodedType;\n matchImportance?: number; // Should be between 0 and 1, 0 being the lowest importance and 1 being the highest importance\n}\n\n// The following types can be merged with the generated schema to provide additional information\n// This is set in the instrumentation layer and merged with the generated schema\nexport interface SchemaMergeTypes {\n encoding?: EncodingType;\n decodedType?: DecodedType;\n matchImportance?: number; // Should be between 0 and 1, 0 being the lowest importance and 1 being the highest importance\n}\n\nexport type SchemaMerges = Record<string, SchemaMergeTypes>;\n\n/**\n * Utility class for JSON schema generation and hashing\n */\nexport class JsonSchemaHelper {\n /**\n * Determine the detailed type of a value using standardized mapping\n */\n static getDetailedType(value: any): JsonSchemaType {\n if (value === null) {\n return jsToJsonSchemaTypeMapping[\"null\"];\n }\n\n if (value === undefined) {\n return jsToJsonSchemaTypeMapping[\"undefined\"];\n }\n\n const primitiveType = typeof value;\n\n if (primitiveType === \"object\") {\n // More specific object type detection\n const objectType = Object.prototype.toString.call(value).slice(8, -1);\n\n if (objectType === \"Array\") {\n return jsToJsonSchemaTypeMapping[\"Array\"];\n }\n\n if (objectType === \"Date\") {\n return jsToJsonSchemaTypeMapping[\"Date\"];\n }\n\n if (objectType === \"RegExp\") {\n return jsToJsonSchemaTypeMapping[\"RegExp\"];\n }\n\n if (objectType === \"Error\") {\n return jsToJsonSchemaTypeMapping[\"Error\"];\n }\n\n if (objectType === \"Set\") {\n return jsToJsonSchemaTypeMapping[\"Set\"];\n }\n\n if (objectType === \"Map\") {\n return jsToJsonSchemaTypeMapping[\"Map\"];\n }\n\n // Typed arrays\n if (objectType === \"Int8Array\") return jsToJsonSchemaTypeMapping[\"Int8Array\"];\n if (objectType === \"Uint8Array\") return jsToJsonSchemaTypeMapping[\"Uint8Array\"];\n if (objectType === \"Uint8ClampedArray\") return jsToJsonSchemaTypeMapping[\"Uint8ClampedArray\"];\n if (objectType === \"Int16Array\") return jsToJsonSchemaTypeMapping[\"Int16Array\"];\n if (objectType === \"Uint16Array\") return jsToJsonSchemaTypeMapping[\"Uint16Array\"];\n if (objectType === \"Int32Array\") return jsToJsonSchemaTypeMapping[\"Int32Array\"];\n if (objectType === \"Uint32Array\") return jsToJsonSchemaTypeMapping[\"Uint32Array\"];\n if (objectType === \"Float32Array\") return jsToJsonSchemaTypeMapping[\"Float32Array\"];\n if (objectType === \"Float64Array\") return jsToJsonSchemaTypeMapping[\"Float64Array\"];\n if (objectType === \"DataView\") return jsToJsonSchemaTypeMapping[\"DataView\"];\n if (objectType === \"ArrayBuffer\") return jsToJsonSchemaTypeMapping[\"ArrayBuffer\"];\n\n if (objectType === \"Arguments\") {\n return jsToJsonSchemaTypeMapping[\"Arguments\"];\n }\n\n // Default to generic object\n return jsToJsonSchemaTypeMapping[\"object\"];\n }\n\n if (primitiveType === \"string\") {\n return jsToJsonSchemaTypeMapping[\"string\"];\n }\n\n if (primitiveType === \"number\") {\n return jsToJsonSchemaTypeMapping[\"number\"];\n }\n\n if (primitiveType === \"bigint\") {\n return jsToJsonSchemaTypeMapping[\"bigint\"];\n }\n\n if (primitiveType === \"boolean\") {\n return jsToJsonSchemaTypeMapping[\"boolean\"];\n }\n\n if (primitiveType === \"function\") {\n return jsToJsonSchemaTypeMapping[\"function\"];\n }\n\n if (primitiveType === \"symbol\") {\n return jsToJsonSchemaTypeMapping[\"symbol\"];\n }\n\n // Fallback for unknown types\n return jsToJsonSchemaTypeMapping[\"string\"];\n }\n\n /**\n * Merge schema override with generated schema\n * This allows partial overrides while preserving generated properties\n */\n private static mergeSchemaWithMerges(\n generatedSchema: JsonSchema,\n merges: SchemaMergeTypes,\n ): JsonSchema {\n const merged: JsonSchema = { ...generatedSchema };\n\n // Apply merges properties\n Object.keys(merges).forEach((key) => {\n (merged as any)[key] = (merges as any)[key];\n });\n\n return merged;\n }\n\n /**\n * Generate schema from data object using standardized types\n */\n static generateSchema(data: any, schemaMerges?: SchemaMerges): JsonSchema {\n if (data === null) {\n return { type: jsToJsonSchemaTypeMapping[\"null\"] };\n }\n\n if (data === undefined) {\n return { type: jsToJsonSchemaTypeMapping[\"undefined\"] };\n }\n\n const detailedType = JsonSchemaHelper.getDetailedType(data);\n\n if (detailedType === JsonSchemaType.ORDERED_LIST) {\n if (Array.isArray(data) && data.length === 0) {\n return { type: JsonSchemaType.ORDERED_LIST, items: null };\n }\n return {\n type: JsonSchemaType.ORDERED_LIST,\n items:\n Array.isArray(data) && data.length > 0 ? JsonSchemaHelper.generateSchema(data[0]) : null,\n };\n }\n\n if (detailedType === JsonSchemaType.UNORDERED_LIST) {\n // Handle Set objects\n if (data instanceof Set) {\n const firstItem = data.size > 0 ? data.values().next().value : null;\n return {\n type: JsonSchemaType.UNORDERED_LIST,\n items: firstItem !== null ? JsonSchemaHelper.generateSchema(firstItem) : null,\n };\n }\n return { type: JsonSchemaType.UNORDERED_LIST, items: null };\n }\n\n if (detailedType === JsonSchemaType.OBJECT) {\n const schema: JsonSchema = { type: JsonSchemaType.OBJECT, properties: {} };\n\n // Handle Map objects\n if (data instanceof Map) {\n data.forEach((value, key) => {\n if (schema.properties) {\n const keyString = String(key);\n const generatedSchema = JsonSchemaHelper.generateSchema(value);\n\n // Check for schema override for this key\n if (schemaMerges && schemaMerges[keyString]) {\n schema.properties[keyString] = JsonSchemaHelper.mergeSchemaWithMerges(\n generatedSchema,\n schemaMerges[keyString],\n );\n } else {\n schema.properties[keyString] = generatedSchema;\n }\n }\n });\n } else if (typeof data === \"object\") {\n Object.keys(data).forEach((key) => {\n if (schema.properties) {\n const generatedSchema = JsonSchemaHelper.generateSchema(data[key]);\n\n // Check for schema override for this key\n if (schemaMerges && schemaMerges[key]) {\n schema.properties[key] = JsonSchemaHelper.mergeSchemaWithMerges(\n generatedSchema,\n schemaMerges[key],\n );\n } else {\n schema.properties[key] = generatedSchema;\n }\n }\n });\n }\n\n return schema;\n }\n\n // For primitive types, return the standardized type\n return { type: detailedType };\n }\n\n /**\n * Generate deterministic hash for any data\n */\n static generateDeterministicHash(data: any): string {\n // Sort object keys to ensure deterministic hashing\n const sortedData = JsonSchemaHelper.sortObjectKeysRecursively(data);\n const jsonString = JSON.stringify(sortedData);\n return crypto.createHash(\"sha256\").update(jsonString).digest(\"hex\");\n }\n\n /**\n * Recursively sort object keys for deterministic hashing\n */\n static sortObjectKeysRecursively(obj: any): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => JsonSchemaHelper.sortObjectKeysRecursively(item));\n }\n\n if (typeof obj === \"object\") {\n const sortedObj: any = {};\n Object.keys(obj)\n .sort()\n .forEach((key) => {\n sortedObj[key] = JsonSchemaHelper.sortObjectKeysRecursively(obj[key]);\n });\n return sortedObj;\n }\n\n return obj;\n }\n\n /**\n * Decode data based on schema merges containing encoding and decodedType\n */\n private static decodeDataWithMerges(data: any, schemaMerges?: SchemaMerges): any {\n if (!schemaMerges) {\n return data;\n }\n\n const decodedData = { ...data };\n\n // Process each schema override that has encoding and decodedType\n for (const [key, schema] of Object.entries(schemaMerges)) {\n if (schema.encoding && schema.decodedType && data[key] !== undefined) {\n try {\n let decodedValue = data[key];\n\n // Decode based on encoding type\n if (schema.encoding === EncodingType.BASE64 && typeof decodedValue === \"string\") {\n const buffer = Buffer.from(decodedValue, \"base64\");\n decodedValue = buffer.toString(\"utf8\");\n }\n\n // Parse based on decoded type\n if (schema.decodedType === DecodedType.JSON && typeof decodedValue === \"string\") {\n decodedValue = JSON.parse(decodedValue);\n }\n\n decodedData[key] = decodedValue;\n } catch (error) {\n logger.warn(`[JsonSchemaHelper] Failed to decode ${key}:`, error);\n // Keep original value if decoding fails\n decodedData[key] = data[key];\n }\n }\n }\n\n return decodedData;\n }\n\n /**\n * Generate schema and hash for input/output data\n *\n * This method handles schema merges by decoding data (e.g., base64 -> JSON) and\n * generating schemas/hashes with schema merges applied.\n *\n * @param data - The original input data to process\n * @param schemaMerges - Optional schema merges could contain encoding, decodedType, and/or matchImportance info\n * @returns Object containing:\n * - schema: JsonSchema for the original data with merges applied\n * - decodedValueHash: Hash of the decoded data values (what the data looks like after decoding)\n * - decodedSchemaHash: Hash of the decoded data schema (structure of decoded data) with schema merges applied\n *\n *\n * E.g. if body is base64-encoded JSON, the schema will show\n *\n * \"body\": {\n * \"type\": \"OBJECT\",\n * \"properties\": {\n * \"location\": { \"type\": \"STRING\" },\n * \"current\": {\n * \"type\": \"OBJECT\",\n * \"properties\": {\n * \"temp_F\": { \"type\": \"STRING\" },\n * \"humidity\": { \"type\": \"STRING\" },\n * }\n * },\n * },\n * \"encoding\": \"BASE64\",\n * \"decodedType\": \"JSON\"\n * },\n *\n * Where the actual body is stored as a base64-encoded JSON string but the schema still demonstrates the structure of the JSON object.\n */\n static generateSchemaAndHash(\n data: any,\n schemaMerges?: SchemaMerges,\n ): {\n schema: JsonSchema;\n decodedValueHash: string;\n decodedSchemaHash: string;\n } {\n // Simulate the same JSON serialization/deserialization that happens during recording\n // This removes undefined values and normalizes the structure\n const normalizedData = JSON.parse(JSON.stringify(data));\n\n // Decode data based on schema merges (e.g., base64 -> JSON)\n const decodedData = JsonSchemaHelper.decodeDataWithMerges(normalizedData, schemaMerges);\n\n // Generate schema for the decoded data with the schema merges applied\n const schema = JsonSchemaHelper.generateSchema(decodedData, schemaMerges);\n\n // Generate hashes for decoded data\n const decodedValueHash = JsonSchemaHelper.generateDeterministicHash(decodedData);\n const decodedSchemaHash = JsonSchemaHelper.generateDeterministicHash(schema);\n\n return { schema, decodedValueHash, decodedSchemaHash };\n }\n\n /**\n * Get the standardized type mapping for reference\n */\n static getTypeMapping(): typeof jsToJsonSchemaTypeMapping {\n return jsToJsonSchemaTypeMapping;\n }\n}\n","import { decompressBuffer } from \"./bodyDecompression\";\nimport { DecodedType } from \"../../../../core/tracing/JsonSchemaHelper\";\nimport { logger } from \"../../../../core/utils/logger\";\n\nexport enum HttpBodyType {\n NONE = \"NONE\",\n JSON = \"JSON\",\n TEXT = \"TEXT\",\n RAW = \"RAW\",\n X_WWW_URL_FORM_URLENCODED = \"X_WWW_URL_FORM_URLENCODED\",\n MULTIPART = \"MULTIPART\",\n UNSPECIFIED = \"UNSPECIFIED\",\n}\n\n// Mapping from content-type to decoded type\nconst CONTENT_TYPE_MAPPING: Record<string, DecodedType> = {\n // JSON\n \"application/json\": DecodedType.JSON,\n\n // HTML\n \"text/html\": DecodedType.HTML,\n\n // CSS\n \"text/css\": DecodedType.CSS,\n\n // JavaScript\n \"text/javascript\": DecodedType.JAVASCRIPT,\n \"application/javascript\": DecodedType.JAVASCRIPT,\n \"application/x-javascript\": DecodedType.JAVASCRIPT,\n\n // XML\n \"text/xml\": DecodedType.XML,\n \"application/xml\": DecodedType.XML,\n\n // SVG (special case - XML-based but can be rendered)\n \"image/svg+xml\": DecodedType.SVG,\n\n // YAML\n \"application/yaml\": DecodedType.YAML,\n \"application/x-yaml\": DecodedType.YAML,\n \"text/yaml\": DecodedType.YAML,\n \"text/x-yaml\": DecodedType.YAML,\n\n // Plain text\n \"text/plain\": DecodedType.PLAIN_TEXT,\n\n // Markdown\n \"text/markdown\": DecodedType.MARKDOWN,\n \"text/x-markdown\": DecodedType.MARKDOWN,\n\n // CSV\n \"text/csv\": DecodedType.CSV,\n \"application/csv\": DecodedType.CSV,\n\n // SQL\n \"application/sql\": DecodedType.SQL,\n \"text/sql\": DecodedType.SQL,\n\n // GraphQL\n \"application/graphql\": DecodedType.GRAPHQL,\n\n // Form data\n \"application/x-www-form-urlencoded\": DecodedType.FORM_DATA,\n \"multipart/form-data\": DecodedType.MULTIPART_FORM,\n\n // PDF\n \"application/pdf\": DecodedType.PDF,\n\n // Specific image formats\n \"image/jpeg\": DecodedType.JPEG,\n \"image/jpg\": DecodedType.JPEG,\n \"image/png\": DecodedType.PNG,\n \"image/gif\": DecodedType.GIF,\n \"image/webp\": DecodedType.WEBP,\n \"image/bmp\": DecodedType.JPEG,\n \"image/tiff\": DecodedType.JPEG,\n \"image/ico\": DecodedType.PNG,\n\n // Audio (keep generic since audio formatting is similar)\n \"audio/mpeg\": DecodedType.AUDIO,\n \"audio/mp3\": DecodedType.AUDIO,\n \"audio/wav\": DecodedType.AUDIO,\n \"audio/ogg\": DecodedType.AUDIO,\n \"audio/webm\": DecodedType.AUDIO,\n\n // Video (keep generic since video formatting is similar)\n \"video/mp4\": DecodedType.VIDEO,\n \"video/webm\": DecodedType.VIDEO,\n \"video/ogg\": DecodedType.VIDEO,\n \"video/avi\": DecodedType.VIDEO,\n \"video/mov\": DecodedType.VIDEO,\n\n // Specific binary formats\n \"application/zip\": DecodedType.ZIP,\n \"application/gzip\": DecodedType.GZIP,\n \"application/x-gzip\": DecodedType.GZIP,\n\n // Generic binary\n \"application/octet-stream\": DecodedType.BINARY,\n \"application/tar\": DecodedType.BINARY,\n \"application/rar\": DecodedType.BINARY,\n \"application/7z\": DecodedType.BINARY,\n};\n\n/**\n * Async HTTP body encoder that base64 encodes the body buffer\n */\nexport async function httpBodyEncoder({\n bodyBuffer,\n contentEncoding,\n}: {\n bodyBuffer: Buffer;\n contentEncoding?: string;\n}): Promise<string> {\n // First check if we need to decompress the body\n let processedBuffer = bodyBuffer;\n\n if (contentEncoding) {\n try {\n processedBuffer = await decompressBuffer(bodyBuffer, contentEncoding);\n } catch (error) {\n logger.warn(`Failed to decompress body with encoding ${contentEncoding}:`, error);\n }\n }\n\n return processedBuffer.toString(\"base64\");\n}\n\n/**\n * Parses a Content-Type header and returns the corresponding decoded type enum\n * @param contentType - The Content-Type header value (e.g., \"application/json; charset=utf-8\")\n * @returns The corresponding DecodedType enum value\n */\nexport function getDecodedType(\n contentType: string | string[] | undefined,\n): DecodedType | undefined {\n // Handle array values (when same header appears multiple times)\n const contentTypeString =\n Array.isArray(contentType) && contentType.length > 0 ? contentType[0] : contentType;\n\n if (!contentTypeString || typeof contentTypeString !== \"string\") {\n logger.debug(`Invalid Content-Type header: ${contentType}`);\n return undefined;\n }\n\n // Convert to lowercase and extract the main media type (before semicolon)\n const mainType = contentTypeString.toLowerCase().split(\";\")[0].trim();\n return CONTENT_TYPE_MAPPING[mainType];\n}\n","import { EventEmitter } from \"events\";\nimport { OriginalGlobalUtils } from \"../../../../core/utils\";\n\nexport interface TdHttpMockSocketOptions {\n protocol?: \"http\" | \"https\";\n family?: number;\n port?: number;\n hostname?: string;\n host?: string;\n}\n\n/**\n * Mock socket implementation for Tusk Drift HTTP replay\n */\nexport class TdHttpMockSocket extends EventEmitter {\n public authorized?: boolean;\n public _hadError: boolean;\n public connecting: boolean;\n public writableLength: number;\n public bufferSize: number;\n public writable: boolean;\n public readable: boolean;\n public pending: boolean;\n public destroyed: boolean;\n public encrypted?: boolean;\n public timeout: number;\n public localAddress: string;\n public remoteFamily: string;\n public localPort: number;\n public remoteAddress: string;\n public remotePort: number;\n public readableEnded: boolean = false;\n public writableFinished: boolean = false;\n\n constructor(options: TdHttpMockSocketOptions = {}) {\n super();\n\n // Set SSL/TLS properties for HTTPS\n if (options.protocol === \"https\") {\n this.authorized = true;\n this.encrypted = true;\n }\n\n this.bufferSize = 0;\n this.writableLength = 0;\n this.writable = true;\n this.readable = true;\n this.pending = false;\n this.destroyed = false;\n this.connecting = true;\n this._hadError = false;\n this.timeout = 0;\n\n // Set up network addressing\n const ipv6 = options.family === 6;\n this.remoteFamily = ipv6 ? \"IPv6\" : \"IPv4\";\n this.remoteAddress = ipv6 ? \"::1\" : \"127.0.0.1\";\n this.localAddress = this.remoteAddress;\n\n // Set ports\n const port = options.port || (options.protocol === \"https\" ? 443 : 80);\n this.remotePort = Number.parseInt(String(port), 10);\n this.localPort = this.remotePort;\n }\n\n setNoDelay(): this {\n return this;\n }\n\n setKeepAlive(): this {\n return this;\n }\n\n resume(): this {\n return this;\n }\n\n ref(): this {\n return this;\n }\n\n unref(): this {\n return this;\n }\n\n write(): boolean {\n return false;\n }\n\n address(): { port: number; family: string; address: string } {\n return {\n port: this.remotePort,\n family: this.remoteFamily,\n address: this.remoteAddress,\n };\n }\n\n setTimeout(timeoutMs: number, callback?: () => void): this {\n this.timeout = timeoutMs;\n if (callback) {\n this.once(\"timeout\", callback);\n }\n return this;\n }\n\n /**\n * Artificial delay that will trip socket timeouts when appropriate.\n * Doesn't actually wait for time to pass.\n * Timeout events don't necessarily end the request.\n */\n applyDelay(delayMs: number): void {\n if (this.timeout && delayMs > this.timeout) {\n this.emit(\"timeout\");\n }\n }\n\n getPeerCertificate(): string {\n const originalDate = OriginalGlobalUtils.getOriginalDate();\n return Buffer.from((Math.random() * 1e4 + originalDate.getTime()).toString()).toString(\n \"base64\",\n );\n }\n\n /**\n * Denotes that no more I/O activity should happen on this socket.\n * Sets flags and emits 'close' and optional 'error' events.\n */\n destroy(err?: Error): this {\n if (this.destroyed) {\n return this;\n }\n\n this.destroyed = true;\n this.writable = false;\n this.readable = false;\n this.writableFinished = true;\n this.readableEnded = true;\n\n process.nextTick(() => {\n if (err) {\n this._hadError = true;\n this.emit(\"error\", err);\n }\n this.emit(\"close\");\n });\n\n return this;\n }\n}\n","export class EnvVarTracker {\n // This should be a mapping between trace id and env var\n private static envVars = new Map<string, Record<string, string | undefined>>();\n\n static setEnvVar({\n traceId,\n key,\n value,\n }: {\n traceId: string;\n key: string;\n value: string | undefined;\n }): void {\n this.envVars.set(traceId, {\n ...(this.envVars.get(traceId) || {}),\n [key]: value,\n });\n }\n\n static setEnvVars(traceId: string, envVars: Record<string, string | undefined>): void {\n this.envVars.set(traceId, envVars);\n }\n\n static getEnvVar(traceId: string, key: string): string | undefined {\n return this.envVars.get(traceId)?.[key];\n }\n\n static getEnvVars(traceId: string): Record<string, string | undefined> | undefined {\n return this.envVars.get(traceId);\n }\n\n static clearEnvVars(traceId: string): void {\n this.envVars.delete(traceId);\n }\n}\n","import { SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { logger } from \"../../../core/utils/logger\";\n\n/**\n * Global date tracker that maintains the latest mock response timestamp per trace.\n * This is used to provide consistent dates in replay mode.\n */\nexport class DateTracker {\n private static traceToLatestTimestamp = new Map<string, Date>();\n\n /**\n * Updates the latest timestamp for a given trace ID\n */\n static updateLatestTimestamp(traceId: string, timestamp: string | number): void {\n const date = new Date(timestamp);\n this.traceToLatestTimestamp.set(traceId, date);\n logger.debug(`Updated latest timestamp for trace ${traceId}: ${date.toISOString()}`);\n }\n\n /**\n * Gets the latest timestamp for the current trace\n */\n static getCurrentTraceLatestDate(): Date | null {\n const replayTraceId = SpanUtils.getCurrentReplayTraceId();\n if (!replayTraceId) {\n return null;\n }\n\n return this.traceToLatestTimestamp.get(replayTraceId) || null;\n }\n\n /**\n * Clears the timestamp for a given trace ID (useful for cleanup)\n */\n static clearTrace(traceId: string): void {\n this.traceToLatestTimestamp.delete(traceId);\n }\n\n /**\n * Clears all tracked timestamps (useful for testing)\n */\n static clearAll(): void {\n this.traceToLatestTimestamp.clear();\n }\n}\n","import { SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDriftCore } from \"../../../core/TuskDrift\";\nimport { DateTracker } from \"../trackers\";\nimport { JsonSchema, JsonSchemaHelper, SchemaMerges } from \"../../../core/tracing/JsonSchemaHelper\";\nimport { CleanSpanData, MockRequestData } from \"../../../core/types\";\nimport { StatusCode } from \"@use-tusk/drift-schemas/core/span\";\nimport { OriginalGlobalUtils, logger } from \"../../../core/utils\";\n\nexport interface MockRequest {\n service: string;\n operation: string;\n target: string;\n inputData?: any;\n inputSchema?: JsonSchema;\n}\n\nexport interface MockResponse {\n result: any;\n}\n\n// Add filler values for the clean span data fields we don't care about when fetching mocks\nfunction convertMockRequestDataToCleanSpanData(\n mockRequestData: MockRequestData,\n tuskDrift: TuskDriftCore,\n inputValueSchemaMerges?: SchemaMerges,\n): CleanSpanData {\n const {\n schema: inputSchema,\n decodedValueHash: inputValueHash,\n decodedSchemaHash: inputSchemaHash,\n } = JsonSchemaHelper.generateSchemaAndHash(mockRequestData.inputValue, inputValueSchemaMerges);\n\n // log date.now in a readable format\n const originalDate = OriginalGlobalUtils.getOriginalDate();\n\n return {\n ...mockRequestData,\n parentSpanId: \"\",\n inputValueHash,\n inputSchema,\n inputSchemaHash,\n outputValue: undefined,\n outputSchema: undefined,\n outputSchemaHash: \"\",\n outputValueHash: \"\",\n timestamp: {\n seconds: Math.floor(originalDate.getTime() / 1000),\n nanos: (originalDate.getTime() % 1000) * 1000000,\n },\n duration: {\n seconds: 0,\n nanos: 0,\n },\n isRootSpan: false,\n isPreAppStart: !tuskDrift.isAppReady(),\n metadata: undefined,\n status: {\n code: StatusCode.OK,\n message: \"OK\",\n },\n };\n}\n\n/**\n * Utility function to find mock responses for replay mode across all instrumentations.\n * This centralizes the common logic of:\n * 1. Getting the replay trace ID from context\n * 2. Making the mock request to TuskDrift\n * 3. Handling the response and error cases\n *\n * @param outboundSpan - The outbound span to find a mock response for\n * @param tuskDrift - The TuskDrift instance to make the mock request\n * @param inputValueSchemaOverrides - The schema overrides for the input value\n * @returns Promise<MockResponse | null> - The mock response or null if not found\n */\nexport async function findMockResponseAsync({\n mockRequestData,\n tuskDrift,\n inputValueSchemaMerges,\n}: {\n mockRequestData: MockRequestData;\n tuskDrift: TuskDriftCore;\n inputValueSchemaMerges?: SchemaMerges;\n}): Promise<MockResponse | null> {\n const outboundSpan = convertMockRequestDataToCleanSpanData(\n mockRequestData,\n tuskDrift,\n inputValueSchemaMerges,\n );\n try {\n // Get replay trace ID from context\n const replayTraceId = SpanUtils.getCurrentReplayTraceId();\n\n logger.debug(`Finding ${outboundSpan.traceId} mock for replay trace ID: ${replayTraceId}`);\n\n const mockResponse = await tuskDrift.requestMockAsync({\n outboundSpan,\n // We could have no replay trace ID if we are finding outbound mocks for calls made before the app started\n testId: replayTraceId || \"\",\n });\n\n if (!mockResponse || !mockResponse.found) {\n logger.debug(\n `No matching mock found for ${outboundSpan.traceId} with input value: ${JSON.stringify(\n outboundSpan.inputValue,\n )}`,\n replayTraceId,\n );\n return null;\n }\n\n const responseBody = mockResponse.response?.response?.body;\n logger.debug(`Found ${outboundSpan.traceId} mock response:`, responseBody, {\n timestamp: mockResponse.response?.timestamp,\n });\n\n // Track the latest timestamp for this trace\n if (mockResponse.response?.timestamp) {\n DateTracker.updateLatestTimestamp(replayTraceId || \"\", mockResponse.response.timestamp);\n }\n\n return {\n result: responseBody,\n };\n } catch (error) {\n logger.error(`Error finding ${outboundSpan.traceId} mock response:`, error);\n return null;\n }\n}\n\nexport function findMockResponseSync({\n mockRequestData,\n tuskDrift,\n inputValueSchemaMerges,\n}: {\n mockRequestData: MockRequestData;\n tuskDrift: TuskDriftCore;\n inputValueSchemaMerges?: SchemaMerges;\n}): MockResponse | null {\n const outboundSpan = convertMockRequestDataToCleanSpanData(\n mockRequestData,\n tuskDrift,\n inputValueSchemaMerges,\n );\n try {\n // Get replay trace ID from context\n const replayTraceId = SpanUtils.getCurrentReplayTraceId();\n\n logger.debug(`Finding ${outboundSpan.traceId} mock for replay trace ID: ${replayTraceId}`);\n\n const mockResponse = tuskDrift.requestMockSync({\n outboundSpan,\n testId: replayTraceId || \"\",\n });\n\n if (!mockResponse || !mockResponse.found) {\n logger.debug(\n `No matching mock found for ${outboundSpan.traceId} with input value: ${JSON.stringify(\n outboundSpan.inputValue,\n )}`,\n replayTraceId,\n );\n return null;\n }\n\n const responseBody = mockResponse.response?.response?.body;\n logger.debug(`Found ${outboundSpan.traceId} mock response and timestamp:`, responseBody, {\n timestamp: mockResponse.response?.timestamp,\n });\n\n // Track the latest timestamp for this trace\n if (mockResponse.response?.timestamp) {\n DateTracker.updateLatestTimestamp(replayTraceId || \"\", mockResponse.response.timestamp);\n }\n\n return {\n result: responseBody,\n };\n } catch (error) {\n logger.error(`Error finding ${outboundSpan.traceId} mock response:`, error);\n return null;\n }\n}\n","import { EventEmitter } from \"events\";\nimport { ClientRequest, IncomingMessage } from \"http\";\nimport { TdHttpMockSocket, TdHttpMockSocketOptions } from \"./TdHttpMockSocket\";\nimport { SpanInfo } from \"../../../../core/tracing/SpanUtils\";\nimport { getDecodedType, httpBodyEncoder, normalizeHeaders } from \"../utils\";\nimport { HttpClientInputValue, HttpClientOutputValue } from \"../types\";\nimport { TuskDriftCore } from \"../../../../core/TuskDrift\";\nimport { createMockInputValue } from \"../../../../core/utils\";\nimport { findMockResponseAsync } from \"../../../core/utils/mockResponseUtils\";\nimport { SpanKind } from \"@opentelemetry/api\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { EncodingType } from \"../../../../core/tracing/JsonSchemaHelper\";\nimport { logger } from \"../../../../core/utils/logger\";\n\nexport interface TdMockClientRequestOptions extends TdHttpMockSocketOptions {\n method?: string;\n path?: string;\n headers?: Record<string, any>;\n timeout?: number;\n auth?: string;\n agent?: any;\n protocol?: \"http\" | \"https\";\n hostname?: string;\n port?: number;\n}\n\n/**\n * Mock ClientRequest implementation for Tusk Drift HTTP replay\n */\nexport class TdMockClientRequest extends EventEmitter {\n private readonly INSTRUMENTATION_NAME = \"HttpInstrumentation\";\n public options: TdMockClientRequestOptions;\n public socket: TdHttpMockSocket;\n public connection: TdHttpMockSocket;\n public response: IncomingMessage;\n public res?: IncomingMessage;\n public path?: string;\n public method?: string;\n public finished: boolean = false;\n private tuskDrift: TuskDriftCore;\n private spanInfo: SpanInfo;\n\n private requestBodyBuffers: Buffer[] = [];\n private playbackStarted: boolean = false;\n private readyToStartPlaybackOnSocketEvent: boolean = false;\n private headers: Record<string, any> = {};\n\n constructor(\n options: TdMockClientRequestOptions,\n spanInfo: SpanInfo,\n callback?: (res: IncomingMessage) => void,\n ) {\n super();\n this.tuskDrift = TuskDriftCore.getInstance();\n\n this.spanInfo = spanInfo;\n\n if (!options || Object.keys(options).length === 0) {\n throw new Error(\n \"Making a request with empty `options` is not supported in TdMockClientRequest\",\n );\n }\n\n this.options = {\n ...options,\n headers: normalizeHeaders(options.headers || {}),\n };\n\n // Set up callback\n if (callback) {\n this.once(\"response\", callback);\n }\n\n // Create mock socket\n this.socket = new TdHttpMockSocket({\n protocol: options.protocol || \"http\",\n family: options.family || 4,\n port: options.port || 80,\n hostname: options.hostname || \"localhost\",\n });\n\n // Set timeout if specified\n const timeout = options.timeout || options.agent?.options?.timeout;\n if (timeout) {\n this.socket.setTimeout(timeout);\n }\n\n // Create response object\n this.response = new IncomingMessage(this.socket as any);\n this.connection = this.socket;\n\n this.attachRequest();\n\n // Connect socket asynchronously\n process.nextTick(async () => {\n await this.connectSocket();\n });\n }\n\n private attachRequest(): void {\n const { options } = this;\n\n // Set headers\n for (const [name, value] of Object.entries(options.headers || {})) {\n // Convert array values to string (take first value if array)\n // const headerValue = Array.isArray(value) ? value[0] : value;\n this.setHeader(name.toLowerCase(), value);\n }\n\n // Set auth header if provided\n if (options.auth && !options.headers?.authorization) {\n this.setHeader(\"authorization\", `Basic ${Buffer.from(options.auth).toString(\"base64\")}`);\n }\n\n // Set request properties\n this.path = options.path || \"/\";\n this.method = options.method || \"GET\";\n\n // Handle 100-continue\n if (options.headers?.expect === \"100-continue\") {\n setImmediate(() => {\n this.emit(\"continue\");\n });\n }\n }\n\n private async connectSocket(): Promise<void> {\n if (this.isDestroyed()) {\n return;\n }\n\n this.connection = this.socket;\n\n // Propagate events\n this.propagateEvents([\"error\", \"timeout\"], this.socket, this);\n\n this.socket.on(\"close\", () => {\n this.socketOnClose();\n });\n\n this.socket.connecting = false;\n this.emit(\"socket\", this.socket);\n this.socket.emit(\"connect\");\n\n if (this.socket.authorized) {\n this.socket.emit(\"secureConnect\");\n }\n\n if (this.readyToStartPlaybackOnSocketEvent) {\n await this.maybeStartPlayback();\n }\n }\n\n private propagateEvents(events: string[], source: EventEmitter, target: EventEmitter): void {\n for (const event of events) {\n source.on(event, (...args) => target.emit(event, ...args));\n }\n }\n\n private socketOnClose(): void {\n if (!(this.res || this.socket._hadError)) {\n this.socket._hadError = true;\n const err = new Error(\"socket hang up\") as any;\n err.code = \"ECONNRESET\";\n this.emit(\"error\", err);\n }\n this.emit(\"close\");\n }\n\n private async maybeStartPlayback(): Promise<void> {\n if (this.socket.connecting) {\n this.readyToStartPlaybackOnSocketEvent = true;\n return;\n }\n\n if (!(this.isDestroyed() || this.playbackStarted)) {\n await this.startPlayback();\n }\n }\n\n private isDestroyed(): boolean {\n return (this as any).destroyed || this.socket.destroyed;\n }\n\n public write(chunk?: any, encoding?: any, callback?: any): boolean {\n if (this.finished) {\n const err = new Error(\"write after end\") as any;\n err.code = \"ERR_STREAM_WRITE_AFTER_END\";\n process.nextTick(() => this.emit(\"error\", err));\n return true;\n }\n\n if (this.socket?.destroyed) {\n return false;\n }\n\n if (!chunk) {\n return true;\n }\n\n if (!Buffer.isBuffer(chunk)) {\n chunk = Buffer.from(chunk, encoding);\n }\n\n this.requestBodyBuffers.push(chunk);\n\n // Handle callback\n const cb = typeof encoding === \"function\" ? encoding : callback;\n if (typeof cb === \"function\") {\n cb();\n }\n\n setImmediate(() => {\n this.emit(\"drain\");\n });\n\n return false;\n }\n\n public end(chunk?: any, encoding?: any, callback?: any): this {\n let cb = callback;\n if (typeof chunk === \"function\") {\n cb = chunk;\n chunk = null;\n } else if (typeof encoding === \"function\") {\n cb = encoding;\n encoding = null;\n }\n\n if (typeof cb === \"function\") {\n this.once(\"finish\", cb);\n }\n\n if (chunk) {\n this.write(chunk, encoding);\n }\n\n this.finished = true;\n\n process.nextTick(async () => {\n await this.maybeStartPlayback();\n });\n\n return this;\n }\n\n public flushHeaders(): void {\n process.nextTick(async () => {\n await this.maybeStartPlayback();\n });\n }\n\n private async startPlayback(): Promise<void> {\n this.playbackStarted = true;\n\n try {\n // Build input value for matching\n const rawInputValue: HttpClientInputValue = {\n method: this.method || \"GET\",\n path: this.path,\n headers: this.headers,\n protocol: this.options.protocol || \"http\",\n hostname: this.options.hostname,\n port: this.options.port || undefined,\n timeout: this.options.timeout || undefined,\n };\n\n if (this.requestBodyBuffers.length > 0) {\n const bodyBuffer = Buffer.concat(\n this.requestBodyBuffers.map((chunk) =>\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk),\n ),\n );\n\n const encodedBody = await httpBodyEncoder({\n bodyBuffer,\n });\n\n rawInputValue.body = encodedBody;\n rawInputValue.bodySize = bodyBuffer.length;\n }\n\n const inputValue = createMockInputValue(rawInputValue);\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: this.spanInfo.traceId,\n spanId: this.spanInfo.spanId,\n name:\n rawInputValue.path || `${rawInputValue.protocol.toUpperCase()} ${rawInputValue.method}`,\n packageName: rawInputValue.protocol,\n packageType: PackageType.HTTP,\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: rawInputValue.method,\n inputValue,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n inputValueSchemaMerges: {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(rawInputValue.headers[\"content-type\"] || \"\"),\n },\n headers: {\n matchImportance: 0,\n },\n },\n });\n if (!mockData) {\n throw new Error(`No matching mock found for ${this.method} ${this.path}`);\n }\n\n this.emit(\"finish\");\n\n // Play the response\n process.nextTick(() => {\n // This type is used in _handleOutboundRequestInSpan when storing output value while recording\n this.playResponse(mockData.result as HttpClientOutputValue);\n });\n } catch (error) {\n logger.error(\"[TdMockClientRequest] Error during playback:\", error);\n this.emit(\"error\", error);\n }\n }\n\n private playResponse(mockDataResult: HttpClientOutputValue): void {\n logger.debug(`[TdMockClientRequest] Playing HTTP mock response:`, mockDataResult);\n try {\n // Set up response properties\n this.response.statusCode = mockDataResult.statusCode || 200;\n this.response.statusMessage = mockDataResult.statusMessage || \"OK\";\n\n // Set headers - normalize to lowercase for consistent handling\n const headers = normalizeHeaders(mockDataResult.headers || {});\n const filteredHeaders = { ...headers };\n\n // Remove compression headers since we provide uncompressed data\n const compressionHeaders = Object.keys(filteredHeaders).filter((key) =>\n key.toLowerCase().includes(\"content-encoding\"),\n );\n compressionHeaders.forEach((header) => {\n delete filteredHeaders[header];\n });\n\n this.response.headers = filteredHeaders;\n this.response.rawHeaders = [];\n\n // Convert headers to rawHeaders format\n for (const [key, value] of Object.entries(filteredHeaders)) {\n this.response.rawHeaders.push(key, String(value));\n }\n\n // Set HTTP version properties\n this.response.httpVersion = mockDataResult.httpVersion || \"1.1\";\n this.response.httpVersionMajor = mockDataResult.httpVersionMajor || 1;\n this.response.httpVersionMinor = mockDataResult.httpVersionMinor || 1;\n this.response.complete = false;\n this.response.readable = true;\n\n // Set up response methods\n (this.response as any).getHeader = (name: string) => {\n return this.response.headers?.[name.toLowerCase()];\n };\n\n (this.response as any).getHeaders = () => {\n return this.response.headers || {};\n };\n\n (this.response as any).hasHeader = (name: string) => {\n return Boolean(this.response.headers?.[name.toLowerCase()]);\n };\n\n this.res = this.response;\n (this.response as any).req = this;\n\n // Emit response event\n this.emit(\"response\", this.response);\n\n // Handle response body\n process.nextTick(async () => {\n await this.emitResponseBody(mockDataResult);\n });\n } catch (error) {\n logger.error(\"[TdMockClientRequest] Error playing response:\", error);\n this.emit(\"error\", error);\n }\n }\n\n private async emitResponseBody(outputValue: HttpClientOutputValue): Promise<void> {\n if (!outputValue.body) {\n // No body data\n this.response.push(null);\n this.response.complete = true;\n this.response.readable = false;\n return;\n }\n\n try {\n const bodyBuffer = Buffer.from(outputValue.body, \"base64\");\n\n // Push data to response stream\n this.response.push(bodyBuffer);\n } catch (error) {\n logger.error(\"[TdMockClientRequest] Error processing response body:\", error);\n this.response.push(null);\n }\n\n // Signal end of response\n this.response.push(null);\n this.response.complete = true;\n this.response.readable = false;\n }\n\n public setHeader(name: string, value: any): void {\n this.headers[name.toLowerCase()] = value;\n }\n\n public getHeader(name: string): any {\n return this.headers[name.toLowerCase()];\n }\n\n public removeHeader(name: string): void {\n delete this.headers[name.toLowerCase()];\n }\n\n public getHeaders(): Record<string, any> {\n return { ...this.headers };\n }\n\n public abort(): void {\n logger.debug(\"[TdMockClientRequest] Request aborted\");\n this.emit(\"abort\");\n this.socket.destroy();\n }\n\n public setTimeout(timeout: number, callback?: () => void): this {\n if (callback) {\n this.once(\"timeout\", callback);\n }\n return this;\n }\n\n public destroy(error?: Error): this {\n logger.debug(\"[TdMockClientRequest] Request destroyed\", error);\n if (error) {\n this.emit(\"error\", error);\n }\n this.emit(\"close\");\n this.socket.destroy();\n return this;\n }\n}\n\nObject.setPrototypeOf(TdMockClientRequest.prototype, ClientRequest.prototype);\n","import { SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDrift } from \"../../../core/TuskDrift\";\nimport { TdMockClientRequest, TdMockClientRequestOptions } from \"./mocks/TdMockClientRequest\";\nimport { RequestOptions } from \"http\";\nimport { logger } from \"../../../core/utils/logger\";\n\n/**\n * HTTP Replay Hooks - Clean separation of replay logic from instrumentation\n */\nexport class HttpReplayHooks {\n /**\n * Extract trace ID from request headers\n */\n extractTraceIdFromHeaders(req: any): string | null {\n const traceIdHeader = req.headers[\"x-td-trace-id\"] || req.headers[\"X-TD-TRACE-ID\"];\n return traceIdHeader ? String(traceIdHeader) : null;\n }\n\n extractEnvVarsFromHeaders(req: any): Record<string, string | undefined> | undefined {\n const envVarsHeader = req.headers[\"x-td-env-vars\"] || req.headers[\"X-TD-ENV-VARS\"];\n return envVarsHeader ? JSON.parse(String(envVarsHeader)) : undefined;\n }\n\n /**\n * Handle outbound HTTP requests in replay mode\n * Uses TdMockClientRequest for simplified mocking approach\n */\n handleOutboundReplayRequest({\n method,\n requestOptions,\n protocol,\n args,\n spanInfo,\n }: {\n method: string;\n requestOptions: RequestOptions;\n protocol: \"http\" | \"https\";\n args: any[];\n spanInfo: SpanInfo;\n }): TdMockClientRequest | undefined {\n logger.debug(\n `[HttpReplayHooks] Handling outbound ${protocol.toUpperCase()} ${method} request in replay mode`,\n );\n\n // Extract callback from args if present\n let callback: ((res: any) => void) | undefined;\n if (args.length > 1 && typeof args[1] === \"function\") {\n callback = args[1];\n } else if (args.length > 2 && typeof args[2] === \"function\") {\n callback = args[2];\n }\n\n logger.debug(\"[HttpReplayHooks] Creating TdMockClientRequest for replay\");\n\n // Prepare options for mock client request\n const mockOptions: TdMockClientRequestOptions = {\n path: requestOptions.path || undefined,\n headers: requestOptions.headers || {},\n timeout: requestOptions.timeout || undefined,\n auth: requestOptions.auth || undefined,\n agent: requestOptions.agent || undefined,\n protocol,\n hostname: requestOptions.hostname || undefined,\n port: requestOptions.port ? Number(requestOptions.port) : undefined,\n method,\n };\n\n // Create and return the mock client request\n return new TdMockClientRequest(mockOptions, spanInfo, callback);\n }\n}\n","import { SpanKind } from \"@opentelemetry/api\";\nimport { SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDriftCore } from \"../../../core/TuskDrift\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport type OriginalFunctionCall<T> = () => T;\nexport type RecordModeHandler<T> = ({ isPreAppStart }: { isPreAppStart: boolean }) => T;\nexport type ReplayModeHandler<T> = () => T;\n\n/**\n * Utility function that abstracts the common record mode pattern of checking for current span context\n * and deciding whether to execute record mode logic or just call the original function.\n *\n * @param originalFunctionCall - Function that calls the original function when no span context exists\n * @param recordModeHandler - Function that handles the record mode logic when span context exists\n * @param spanKind - The kind of span being created\n * @returns The result from either originalFunctionCall or recordModeHandler\n */\nexport function handleRecordMode<T>({\n originalFunctionCall,\n recordModeHandler,\n spanKind,\n}: {\n originalFunctionCall: OriginalFunctionCall<T>;\n recordModeHandler: RecordModeHandler<T>;\n spanKind: SpanKind;\n}): T {\n let isAppReady = false;\n let currentSpanInfo = null;\n try {\n isAppReady = TuskDriftCore.getInstance().isAppReady();\n currentSpanInfo = SpanUtils.getCurrentSpanInfo();\n } catch (error) {\n logger.error(`ModeUtils error checking app readiness or getting current span info:`, error);\n return originalFunctionCall();\n }\n\n if (!isAppReady) {\n logger.debug(`[ModeUtils] App is not ready, calling recordModeHandler with isPreAppStart=true`);\n // If app is not ready, call recordModeHandler with beforeAppStart=true\n return recordModeHandler({ isPreAppStart: true });\n }\n\n if ((!currentSpanInfo && spanKind !== SpanKind.SERVER) || currentSpanInfo?.isPreAppStart) {\n // If there is no current span info meaning this request isn't attached to a span (not part of an inbound request) AND isn't a server request\n // OR the current span was created before the app started. No need to keep recording these requests\n return originalFunctionCall();\n } else {\n // App is ready and we have span context, call recordModeHandler with beforeAppStart=false\n return recordModeHandler({ isPreAppStart: false });\n }\n}\n\n/**\n * Utility function that abstracts the common replay mode pattern of checking if the app is ready\n *\n * Currently just calls the replayModeHandler, but we might add some logic here in the future.\n * @param replayModeHandler - Function that handles the replay mode logic when app is ready\n * @returns The result from either originalFunctionCall or replayModeHandler\n */\nexport function handleReplayMode<T>({\n replayModeHandler,\n}: {\n replayModeHandler: ReplayModeHandler<T>;\n}): T {\n return replayModeHandler();\n}\n","/**\n * Paths to exclude from instrumentation to avoid recording SDK export traffic\n */\n\nimport { SpanExportService } from \"@use-tusk/drift-schemas/backend/span_export_service\";\n\nexport const TUSK_SKIP_HEADER = \"x-td-skip-instrumentation\";\n\nexport function isTuskDriftIngestionUrl(urlOrPath?: string | null): boolean {\n if (!urlOrPath) return false;\n\n // Use typeName to avoid hardcoding the endpoint path\n return urlOrPath.includes(SpanExportService.typeName);\n}\n","import { logger } from \"../../../core/utils/logger\";\n\n/**\n * Shimmer utility functions for wrapping and unwrapping methods\n * Based on shimmer patterns commonly used in instrumentation\n */\n\n/**\n * Check if a function has been wrapped by checking for the wrapped property\n */\nexport function isWrapped(func: any): boolean {\n return typeof func === \"function\" && func._isWrapped === true;\n}\n\n/**\n * Wrap a method on an object with a new function\n */\nexport function wrap<T = any>(\n target: any,\n propertyName: string,\n wrapper: (original: T) => T,\n): void {\n if (typeof target[propertyName] !== \"function\") {\n logger.warn(`Cannot wrap non-function property: ${propertyName}`);\n return;\n }\n\n if (isWrapped(target[propertyName])) {\n logger.warn(`Property ${propertyName} is already wrapped`);\n return;\n }\n\n const original = target[propertyName];\n const wrapped = wrapper(original);\n\n if (typeof wrapped !== \"function\") {\n logger.warn(`Wrapper must return a function for property: ${propertyName}`);\n return;\n }\n\n // Mark as wrapped and store original\n (wrapped as any)._isWrapped = true;\n (wrapped as any)._original = original;\n (wrapped as any)._propertyName = propertyName;\n\n target[propertyName] = wrapped;\n}\n","import * as crypto from \"crypto\";\nimport jp from \"jsonpath\";\nimport { SpanKind } from \"@opentelemetry/api\";\nimport {\n HttpClientInputValue,\n HttpClientOutputValue,\n HttpServerInputValue,\n HttpServerOutputValue,\n} from \"./types\";\nimport { OneOf } from \"src/core/types\";\n\nexport interface TransformConfigs {\n http: HttpTransform[];\n}\n\nexport interface HttpTransform {\n matcher: HttpTransformMatcher;\n action: HttpTransformAction;\n}\n\n/** A matcher config. An element is matched iff *all* conditions specified\n * here are true. Only one target field is allowed, but any of the common\n * fields may be provided.\n * */\nexport type HttpTransformMatcher = {\n /** Request direction, relative to this service. */\n direction: \"inbound\" | \"outbound\";\n /** HTTP method: array of methods like [\"GET\", \"POST\"]. Empty array matches all methods. */\n method?: (\"GET\" | \"POST\" | \"DELETE\" | \"PUT\")[];\n /** URL path pattern: \"/api/user/*\" */\n pathPattern?: string;\n /** Host pattern. e.g. \"api.example.com\" */\n host?: string;\n} & OneOf<HttpTransformTarget>;\n\nexport type HttpTransformTarget = {\n /** JSONPath expression: \"$.user.password\" */\n jsonPath: string;\n /** Query parameter name: \"ssn\" */\n queryParam: string;\n /** Header name: \"Authorization\" */\n headerName: string;\n /** Transform the entire URL path */\n urlPath: string;\n /** Transform the entire request/response body */\n fullBody: string;\n};\n\nexport type HttpTransformAction =\n | {\n type: \"redact\";\n /** Prefix for hash (default: \"REDACTED_\") */\n hashPrefix?: string;\n }\n | {\n type: \"mask\";\n /** Character to use for masking (default: \"*\") */\n maskChar?: string;\n }\n | {\n type: \"replace\";\n /** Static replacement value (required) */\n replaceWith: string;\n }\n | {\n type: \"drop\";\n };\n\nexport interface HttpSpanData {\n traceId: string;\n spanId: string;\n kind: SpanKind;\n protocol?: HttpClientInputValue[\"protocol\"];\n inputValue?: HttpClientInputValue | HttpServerInputValue;\n outputValue?: HttpClientOutputValue | HttpServerOutputValue;\n transformMetadata?: {\n transformed: boolean;\n actions: TransformAction[];\n };\n}\n\ntype CompiledTransform = (span: HttpSpanData) => TransformAction | undefined;\n\ntype TransformAction = {\n type: \"redact\" | \"mask\" | \"replace\" | \"drop\";\n field: string;\n reason: string;\n description?: string;\n};\n\ntype ActionFunction = (value: string) => string;\n\ntype MatcherFunction = (span: HttpSpanData) => boolean;\n\nexport class HttpTransformEngine {\n private compiledTransforms: CompiledTransform[] = [];\n\n constructor(transformConfigs?: TransformConfigs) {\n if (transformConfigs?.http) {\n this.compiledTransforms = transformConfigs.http.map((transform) =>\n this.compileHttpTransform(transform),\n );\n }\n }\n\n shouldDropInboundRequest(\n method: string,\n url: string,\n headers?: Record<string, any>,\n body?: any,\n ): boolean {\n const testSpan: HttpSpanData = {\n traceId: \"\",\n spanId: \"\",\n kind: SpanKind.SERVER,\n protocol: \"http\",\n inputValue: {\n method,\n url,\n target: url,\n headers: headers || {},\n httpVersion: \"1.1\",\n body,\n bodySize: 0,\n } as HttpServerInputValue,\n };\n\n for (const compiledTransform of this.compiledTransforms) {\n const action = compiledTransform(testSpan);\n if (action && action.type === \"drop\") {\n return true;\n }\n }\n\n return false;\n }\n\n shouldDropOutboundRequest(inputValue: HttpClientInputValue): boolean {\n const clonedInputValue = JSON.parse(JSON.stringify(inputValue)) as HttpClientInputValue;\n\n const testSpan: HttpSpanData = {\n traceId: \"\",\n spanId: \"\",\n kind: SpanKind.CLIENT,\n protocol: inputValue.protocol || \"http\",\n inputValue: clonedInputValue,\n };\n\n for (const compiledTransform of this.compiledTransforms) {\n const action = compiledTransform(testSpan);\n if (action && action.type === \"drop\") {\n return true;\n }\n }\n\n return false;\n }\n\n applyTransforms(spanData: HttpSpanData): HttpSpanData {\n const actions: TransformAction[] = [];\n\n for (const compiledTransform of this.compiledTransforms) {\n const action = compiledTransform(spanData);\n if (action) {\n actions.push(action);\n }\n }\n\n if (actions.length > 0) {\n spanData.transformMetadata = {\n transformed: true,\n actions,\n };\n }\n\n return spanData;\n }\n\n private compileHttpTransform(transform: HttpTransform): CompiledTransform {\n const { matcher, action } = transform;\n\n const matcherFunction = this.compileMatcher(matcher);\n if (action.type === \"drop\") {\n return (span) => {\n if (!matcherFunction(span)) {\n return;\n }\n\n // Drop all sensitive data\n if (span.inputValue) {\n span.inputValue = {} as any;\n }\n\n if (span.outputValue) {\n span.outputValue = {} as any;\n }\n\n return {\n type: \"drop\",\n field: \"entire_span\",\n reason: \"transforms\",\n description: this.describeTransform(transform),\n };\n };\n }\n\n const compiledAction = this.compileAction(matcher, action);\n const fieldDescription = this.getFieldDescription(matcher);\n\n return (span) => {\n if (!matcherFunction(span)) {\n return;\n }\n\n const result = compiledAction(span);\n if (result) {\n return {\n type: action.type,\n field: fieldDescription,\n reason: \"transforms\",\n };\n }\n\n return;\n };\n }\n\n private compileAction(\n matcher: HttpTransformMatcher,\n action: HttpTransformAction,\n ): (span: HttpSpanData) => boolean {\n const actionFunction = this.compileActionFunction(action);\n\n if (matcher.jsonPath) {\n return this.compileJsonPathAction(matcher.jsonPath, actionFunction, matcher.direction);\n }\n if (matcher.queryParam) {\n return this.compileQueryParamAction(matcher.queryParam, actionFunction, matcher.direction);\n }\n if (matcher.headerName) {\n return this.compileHeaderAction(matcher.headerName, actionFunction, matcher.direction);\n }\n if (matcher.urlPath !== undefined) {\n return this.compileUrlPathAction(actionFunction, matcher.direction);\n }\n if (matcher.fullBody !== undefined) {\n return this.compileFullBodyAction(actionFunction, matcher.direction);\n }\n\n return () => false;\n }\n\n private compileMatcher(matcher: HttpTransformMatcher): MatcherFunction {\n const checks: MatcherFunction[] = [];\n\n if (matcher.direction === \"outbound\") {\n checks.push((span) => span.kind === SpanKind.CLIENT);\n } else if (matcher.direction === \"inbound\") {\n checks.push((span) => span.kind === SpanKind.SERVER);\n }\n\n if (matcher.method) {\n // Empty array means match all methods (wildcard)\n if (matcher.method.length === 0) {\n // No check needed - matches all methods\n } else {\n const methods = matcher.method.map((method) => method.toUpperCase());\n checks.push((span) => {\n const spanMethod = span.inputValue?.method?.toUpperCase();\n return spanMethod ? methods.includes(spanMethod) : false;\n });\n }\n }\n\n if (matcher.pathPattern) {\n try {\n const pattern = new RegExp(matcher.pathPattern);\n if (matcher.direction === \"outbound\") {\n checks.push((span) => {\n const path = (span.inputValue as HttpClientInputValue)?.path;\n return path ? pattern.test(path) : false;\n });\n } else {\n checks.push((span) => {\n const path = (span.inputValue as HttpServerInputValue)?.url;\n return path ? pattern.test(path) : false;\n });\n }\n } catch (error) {\n throw new Error(\n `Invalid path pattern \"${matcher.pathPattern}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (matcher.host) {\n try {\n const hostPattern = new RegExp(matcher.host);\n if (matcher.direction === \"outbound\") {\n checks.push((span) => {\n const hostname = (span.inputValue as HttpClientInputValue)?.hostname;\n return hostname ? hostPattern.test(hostname) : false;\n });\n } else {\n checks.push((span) => {\n const url = (span.inputValue as HttpServerInputValue)?.url;\n if (!url) {\n return false;\n }\n try {\n const hostname = new URL(url, \"http://localhost\").hostname;\n return hostPattern.test(hostname);\n } catch {\n return false;\n }\n });\n }\n } catch (error) {\n throw new Error(\n `Invalid host pattern \"${matcher.host}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (checks.length === 0) {\n return () => true;\n }\n if (checks.length === 1) {\n return checks[0];\n }\n\n return (span) => checks.every((check) => check(span));\n }\n\n private compileJsonPathAction(\n jsonPath: string,\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): (span: HttpSpanData) => boolean {\n const selector = direction === \"inbound\" ? \"inputValue\" : \"outputValue\";\n return (span) => {\n const target = span[selector];\n if (!target) {\n return false;\n }\n\n try {\n const nodes = jp.apply((target as any).body, jsonPath, actionFunction);\n return nodes.length > 0;\n } catch (error) {\n return false;\n }\n };\n }\n\n private compileHeaderAction(\n headerName: string,\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): (span: HttpSpanData) => boolean {\n const lowerHeader = headerName.toLowerCase();\n const selector = direction === \"inbound\" ? \"inputValue\" : \"outputValue\";\n\n return (span) => {\n const target = span[selector] as any;\n if (!target?.headers) {\n return false;\n }\n\n let applied = false;\n for (const key of Object.keys(target.headers)) {\n if (key.toLowerCase() === lowerHeader) {\n target.headers[key] = actionFunction(target.headers[key]);\n applied = true;\n }\n }\n return applied;\n };\n }\n\n private compileQueryParamAction(\n queryParam: string,\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): (span: HttpSpanData) => boolean {\n return (span) => {\n if (!span.inputValue) {\n return false;\n }\n\n return this.transformQueryParamInData(span.inputValue, queryParam, actionFunction, direction);\n };\n }\n\n private compileFullBodyAction(\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): (span: HttpSpanData) => boolean {\n const selector = direction === \"inbound\" ? \"inputValue\" : \"outputValue\";\n\n return (span) => {\n const target = span[selector] as any;\n if (!target || target.body === undefined) {\n return false;\n }\n\n target.body = actionFunction(\n typeof target.body === \"string\" ? target.body : JSON.stringify(target.body),\n );\n return true;\n };\n }\n\n private compileUrlPathAction(\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): (span: HttpSpanData) => boolean {\n return (span) => {\n if (!span.inputValue) {\n return false;\n }\n return this.transformUrlPathInData(span.inputValue, actionFunction, direction);\n };\n }\n\n private transformQueryParamInData(\n data: any,\n queryParam: string,\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): boolean {\n if (!data || typeof data !== \"object\") {\n return false;\n }\n\n let applied = false;\n\n if (direction === \"outbound\") {\n if (data.path && typeof data.path === \"string\") {\n const url = new URL(data.path, \"http://localhost\");\n if (url.searchParams.has(queryParam)) {\n const oldValue = url.searchParams.get(queryParam);\n if (oldValue !== null) {\n const newValue = actionFunction(oldValue);\n url.searchParams.set(queryParam, newValue);\n data.path = url.pathname + url.search;\n applied = true;\n }\n }\n }\n } else {\n for (const field of [\"url\", \"target\"]) {\n if (data[field] && typeof data[field] === \"string\") {\n try {\n const url =\n field === \"url\" ? new URL(data[field]) : new URL(data[field], \"http://localhost\");\n if (url.searchParams.has(queryParam)) {\n const oldValue = url.searchParams.get(queryParam);\n if (oldValue !== null) {\n const newValue = actionFunction(oldValue);\n url.searchParams.set(queryParam, newValue);\n data[field] = field === \"url\" ? url.toString() : url.pathname + url.search;\n applied = true;\n }\n }\n } catch {\n // ignore\n }\n }\n }\n }\n\n return applied;\n }\n\n private transformUrlPathInData(\n data: any,\n actionFunction: ActionFunction,\n direction: HttpTransformMatcher[\"direction\"],\n ): boolean {\n if (!data || typeof data !== \"object\") {\n return false;\n }\n\n let applied = false;\n\n if (direction === \"outbound\") {\n if (data.path && typeof data.path === \"string\") {\n data.path = actionFunction(data.path);\n applied = true;\n }\n } else {\n for (const field of [\"url\", \"target\"]) {\n if (data[field] && typeof data[field] === \"string\") {\n data[field] = actionFunction(data[field]);\n applied = true;\n }\n }\n }\n\n return applied;\n }\n\n private compileActionFunction(action: HttpTransformAction): ActionFunction {\n switch (action.type) {\n case \"redact\":\n return (value) => {\n const prefix = action.hashPrefix || \"REDACTED_\";\n const hash = crypto.createHash(\"sha256\").update(String(value)).digest(\"hex\");\n return `${prefix}${hash.substring(0, 12)}...`;\n };\n case \"mask\":\n return (value) => {\n const maskChar = action.maskChar || \"*\";\n return maskChar.repeat(value.length);\n };\n case \"replace\":\n return () => action.replaceWith;\n default:\n return (value) => value;\n }\n }\n\n private getFieldDescription(matcher: HttpTransformMatcher): string {\n if (matcher.jsonPath) return `jsonPath:${matcher.jsonPath}`;\n if (matcher.queryParam) return `queryParam:${matcher.queryParam}`;\n if (matcher.headerName) return `header:${matcher.headerName}`;\n if (matcher.urlPath) return \"urlPath\";\n if (matcher.fullBody !== undefined) return \"fullBody\";\n return \"unknown\";\n }\n\n private describeTransform(transform: HttpTransform): string {\n return JSON.stringify(transform.matcher);\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { TdInstrumentationConfig } from \"../../core/baseClasses/TdInstrumentationAbstract\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind, SpanStatusCode, context } from \"@opentelemetry/api\";\nimport {\n ClientRequest,\n IncomingHttpHeaders,\n IncomingMessage,\n RequestOptions,\n Server,\n ServerResponse,\n} from \"http\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { combineChunks, getDecodedType, httpBodyEncoder, normalizeHeaders } from \"./utils\";\nimport { HttpReplayHooks } from \"./HttpReplayHooks\";\nimport {\n HttpClientInputValue,\n HttpServerInputValue,\n HttpModuleExports,\n HttpsModuleExports,\n HttpClientOutputValue,\n HttpServerOutputValue,\n HttpProtocol,\n} from \"./types\";\nimport {\n wrap,\n TUSK_SKIP_HEADER,\n handleRecordMode,\n handleReplayMode,\n isTuskDriftIngestionUrl,\n} from \"../../core/utils\";\nimport { PackageType, StatusCode } from \"@use-tusk/drift-schemas/core/span\";\nimport {\n EncodingType,\n JsonSchemaHelper,\n SchemaMerges,\n} from \"../../../core/tracing/JsonSchemaHelper\";\nimport { shouldSample, OriginalGlobalUtils, logger } from \"../../../core/utils\";\nimport { EnvVarTracker } from \"../../core/trackers\";\nimport { HttpSpanData, HttpTransformEngine, TransformConfigs } from \"./HttpTransformEngine\";\n\nexport interface HttpInstrumentationConfig extends TdInstrumentationConfig {\n requestHook?: (request: any) => void;\n responseHook?: (response: any) => void;\n mode: TuskDriftMode;\n transforms?: TransformConfigs;\n}\n\nexport class HttpInstrumentation extends TdInstrumentationBase {\n private readonly INSTRUMENTATION_NAME = \"HttpInstrumentation\";\n private mode: TuskDriftMode;\n private replayHooks: HttpReplayHooks;\n private tuskDrift: TuskDriftCore;\n private transformEngine: HttpTransformEngine;\n\n constructor(config: HttpInstrumentationConfig) {\n super(\"http\", config);\n this.mode = config.mode;\n this.replayHooks = new HttpReplayHooks();\n this.tuskDrift = TuskDriftCore.getInstance();\n this.transformEngine = new HttpTransformEngine(config.transforms);\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"http\",\n supportedVersions: [\"*\"],\n patch: (moduleExports: HttpModuleExports) => this._patchHttpModule(moduleExports, \"http\"),\n }),\n new TdInstrumentationNodeModule({\n name: \"https\",\n supportedVersions: [\"*\"],\n patch: (moduleExports: HttpsModuleExports) => this._patchHttpModule(moduleExports, \"https\"),\n }),\n ];\n }\n\n private _patchHttpModule(\n httpModule: HttpModuleExports | HttpsModuleExports,\n protocol: HttpProtocol,\n ): HttpModuleExports | HttpsModuleExports {\n const protocolUpper = protocol.toUpperCase();\n logger.debug(`[HttpInstrumentation] Patching ${protocolUpper} module in ${this.mode} mode`);\n\n if (httpModule._tdPatched) {\n logger.debug(`[HttpInstrumentation] ${protocolUpper} module already patched, skipping`);\n return httpModule;\n }\n\n this._wrap(httpModule, \"request\", this._getRequestPatchFn(protocol));\n this._wrap(httpModule, \"get\", this._getGetPatchFn(protocol));\n\n const HttpServer = httpModule.Server;\n if (HttpServer && HttpServer.prototype) {\n this._wrap(HttpServer.prototype, \"emit\", this._getServerEmitPatchFn(protocol));\n logger.debug(`[HttpInstrumentation] Wrapped Server.prototype.emit for ${protocolUpper}`);\n }\n\n httpModule._tdPatched = true;\n logger.debug(`[HttpInstrumentation] ${protocolUpper} module patching complete`);\n\n return httpModule;\n }\n\n private _createServerSpan({\n req,\n res,\n originalHandler,\n protocol,\n }: {\n req: IncomingMessage;\n res: ServerResponse;\n originalHandler: Function;\n protocol: HttpProtocol;\n }): void {\n const method = req.method || \"GET\";\n const url = req.url || \"/\";\n const target = req.url || \"/\";\n const spanProtocol = this._normalizeProtocol(protocol, \"http\");\n\n // Ignore drift ingestion endpoints (avoid recording SDK export traffic)\n if (isTuskDriftIngestionUrl(url) || isTuskDriftIngestionUrl(target)) {\n return originalHandler.call(this);\n }\n\n // Check if transforms want to drop this inbound request entirely (prevents trace creation)\n if (this.transformEngine.shouldDropInboundRequest(method, url, req.headers)) {\n logger.debug(\n `[HttpInstrumentation] Dropping inbound request due to transforms: ${method} ${url}`,\n );\n return originalHandler.call(this);\n }\n\n // Handle replay mode using replay hooks (only if app is ready)\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Remove accept-encoding header to prevent compression during replay\n // since we're providing already-decompressed data\n if (req.headers[\"accept-encoding\"]) {\n delete req.headers[\"accept-encoding\"];\n }\n\n // Build input value object for server request in replay mode\n const fullUrl = `${spanProtocol}://${req.headers.host || \"localhost\"}${url}`;\n const inputValue = {\n method,\n url: fullUrl,\n target,\n headers: req.headers,\n httpVersion: req.httpVersion,\n remoteAddress: req.socket?.remoteAddress,\n remotePort: req.socket?.remotePort,\n };\n\n // Set replay trace context (replaces previous replayHooks-only call)\n const replayTraceId = this.replayHooks.extractTraceIdFromHeaders(req);\n if (!replayTraceId) {\n // No trace context; proceed without span\n return originalHandler.call(this);\n }\n\n // Only done if we are running integration tests\n this.tuskDrift.createReplayMappingsForTrace(replayTraceId);\n\n // Set env vars for current trace\n const envVars = this.replayHooks.extractEnvVarsFromHeaders(req);\n if (envVars) {\n EnvVarTracker.setEnvVars(replayTraceId, envVars);\n }\n\n const ctxWithReplayTraceId = SpanUtils.setCurrentReplayTraceId(replayTraceId);\n\n if (!ctxWithReplayTraceId) {\n // Replay mode, okay to throw error\n throw new Error(\"Error setting current replay trace id\");\n }\n\n return context.with(ctxWithReplayTraceId, () => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => originalHandler.call(this),\n {\n name: `${target}`,\n kind: SpanKind.SERVER,\n packageName: spanProtocol,\n submodule: method,\n packageType: PackageType.HTTP,\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue,\n inputSchemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n isPreAppStart: false,\n },\n (spanInfo) => {\n // Use the full server-span handler to capture input/output and end the span\n return this._handleInboundRequestInSpan({\n req,\n res,\n originalHandler,\n spanInfo,\n inputValue,\n schemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n protocol: spanProtocol,\n });\n },\n );\n });\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n // Skip CORS preflight in RECORD mode (don't create a span)\n if (method.toUpperCase() === \"OPTIONS\" || !!req.headers[\"access-control-request-method\"]) {\n return originalHandler.call(this);\n }\n\n if (\n !shouldSample({\n samplingRate: this.tuskDrift.getSamplingRate(),\n isAppReady: this.tuskDrift.isAppReady(),\n })\n ) {\n logger.debug(\n `Skipping server span due to sampling rate`,\n url,\n this.tuskDrift.getSamplingRate(),\n );\n return originalHandler.call(this);\n }\n\n logger.debug(`[HttpInstrumentation] Creating server span for ${method} ${url}`);\n return handleRecordMode({\n originalFunctionCall: () => originalHandler.call(this),\n recordModeHandler: ({ isPreAppStart }) => {\n // Build input value object for server request\n const fullUrl = `${spanProtocol}://${req.headers.host || \"localhost\"}${url}`;\n const filteredHeaders = { ...req.headers };\n // Remove accept-encoding header (case-insensitive) to prevent compression during replay\n //\n // During RECORD mode, responses are compressed by the server (gzip/deflate/br),\n // then decompressed by our instrumentation and stored as uncompressed base64 data.\n // During REPLAY mode, if the client sends Accept-Encoding headers, the server's\n // compression middleware will compress our already-decompressed response data,\n // resulting in double-compressed garbage that the client can't decode.\n //\n // Therefore, we remove all Accept-Encoding headers during replay so compression middleware\n // skips compression and returns our stored decompressed data directly.\n // IMPORTANT: only update the headers object we are recording, not the original request headers\n Object.keys(filteredHeaders).forEach((key) => {\n if (key.toLowerCase() === \"accept-encoding\") {\n delete filteredHeaders[key];\n }\n });\n const inputValue = {\n method,\n url: fullUrl,\n target,\n headers: filteredHeaders,\n httpVersion: req.httpVersion,\n remoteAddress: req.socket?.remoteAddress,\n remotePort: req.socket?.remotePort,\n };\n\n logger.debug(\n `[HttpInstrumentation] Http inbound request arriving, inputValue: ${JSON.stringify(inputValue)}`,\n );\n\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => originalHandler.call(this),\n {\n name: `${target}`,\n kind: SpanKind.SERVER,\n packageName: spanProtocol,\n packageType: PackageType.HTTP,\n submodule: method,\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue,\n inputSchemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n isPreAppStart,\n },\n (spanInfo) => {\n return this._handleInboundRequestInSpan({\n req,\n res,\n originalHandler,\n spanInfo,\n inputValue, // Body will be populated by _captureServerRequestBody in _handleInboundRequestInSpan\n schemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n protocol: spanProtocol,\n });\n },\n );\n },\n spanKind: SpanKind.SERVER,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalHandler.call(this);\n }\n }\n\n /**\n * Handles server-side request processing within a span context.\n *\n * TypeScript typing notes:\n * - req: IncomingMessage - We can use proper typing because we only patch req.read() with signature-compatible changes\n * - res: any - We must use 'any' because we patch res.end() with incompatible signatures (async function vs sync overloads)\n *\n * NOTE: addAttributes() will override the current attributes so we need to pass current schema merges\n * to make sure we don't lose any information\n */\n private _handleInboundRequestInSpan({\n req,\n res,\n originalHandler,\n spanInfo,\n inputValue,\n schemaMerges,\n protocol,\n }: {\n req: IncomingMessage;\n res: ServerResponse;\n originalHandler: Function;\n spanInfo: SpanInfo;\n inputValue: {\n method: string;\n url: string;\n target: string;\n headers: IncomingHttpHeaders;\n httpVersion: string;\n remoteAddress?: string;\n remotePort?: number;\n };\n schemaMerges: SchemaMerges | undefined;\n protocol: HttpProtocol;\n }) {\n const self = this;\n const spanProtocol = this._normalizeProtocol(protocol, \"http\");\n // Bind context to request/response objects\n context.bind(spanInfo.context, req);\n context.bind(spanInfo.context, res);\n\n // Track the complete input value (will be updated when body is captured)\n let completeInputValue: any = inputValue;\n\n // Capture request body if it exists\n // NOTE: IncomingMessage doesn't have a .body property - we need to capture it from the stream\n // This patches req.read() and listens for 'data'/'end' events to collect body chunks as they arrive\n // Handles both read() consumption and pipe/stream consumption patterns used by different frameworks\n this._captureServerRequestBody(req, spanInfo, inputValue, schemaMerges, (updatedInputValue) => {\n completeInputValue = updatedInputValue;\n });\n\n // Track response completion\n const originalEnd = res.end.bind(res);\n const responseChunks: (string | Buffer)[] = [];\n\n // Patch response write to capture body with Buffer support\n const originalWrite = res.write?.bind(res);\n if (originalWrite) {\n res.write = function (chunk: string | Buffer, encoding?: any, callback?: any) {\n if (chunk) {\n responseChunks.push(chunk);\n }\n return originalWrite.call(this, chunk, encoding, callback);\n };\n }\n\n res.end = function (chunk: any, encoding?: any, callback?: any) {\n const statusCode = res.statusCode;\n\n // Capture any final response data\n if (chunk) {\n responseChunks.push(chunk);\n }\n\n logger.debug(\n `[HttpInstrumentation] Server request completed: ${statusCode} (${SpanUtils.getTraceInfo()})`,\n );\n\n // Process response body asynchronously without blocking\n process.nextTick(async () => {\n // Normalize headers to lowercase for consistent access\n const rawHeaders = res.getHeaders ? (res.getHeaders() as Record<string, string>) : {};\n const normalizedHeaders = normalizeHeaders(rawHeaders);\n\n const outputValue: HttpServerOutputValue = {\n statusCode,\n statusMessage: res.statusMessage,\n headers: normalizedHeaders,\n };\n\n // Process response body if we have chunks\n if (responseChunks.length > 0) {\n try {\n const responseBuffer = combineChunks(responseChunks);\n const contentEncoding = outputValue.headers?.[\"content-encoding\"];\n\n const encodedBody = await httpBodyEncoder({\n bodyBuffer: responseBuffer,\n contentEncoding,\n });\n\n // Store parsed body data\n outputValue.body = encodedBody;\n outputValue.bodySize = responseBuffer.length;\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error processing server response body:`, error);\n const errorMessage = error instanceof Error ? error.message : String(error);\n outputValue.bodyProcessingError = errorMessage;\n }\n }\n\n try {\n // Apply transforms to span data before adding attributes\n // Use completeInputValue which includes the request body\n const spanData: HttpSpanData = {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n kind: SpanKind.SERVER,\n protocol: spanProtocol,\n inputValue: completeInputValue,\n outputValue,\n };\n self.transformEngine.applyTransforms(spanData);\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n inputValue: spanData.inputValue,\n outputValue: spanData.outputValue,\n outputSchemaMerges: {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(\n (spanData.outputValue as any).headers?.[\"content-type\"] || \"\",\n ),\n },\n headers: {\n matchImportance: 0,\n },\n },\n metadata: {\n ENV_VARS: EnvVarTracker.getEnvVars(spanInfo.traceId),\n },\n ...(spanData.transformMetadata && {\n transformMetadata: spanData.transformMetadata,\n }),\n });\n\n // Make sure to delete the env vars from the tracker\n EnvVarTracker.clearEnvVars(spanInfo.traceId);\n\n const status =\n statusCode >= 400\n ? { code: SpanStatusCode.ERROR, message: `HTTP ${statusCode}` }\n : { code: SpanStatusCode.OK };\n\n SpanUtils.setStatus(spanInfo.span, status);\n SpanUtils.endSpan(spanInfo.span);\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error adding response attributes to span:`, error);\n }\n\n if (self.mode === TuskDriftMode.REPLAY) {\n try {\n const now = OriginalGlobalUtils.getOriginalDate();\n const replayTraceId = SpanUtils.getCurrentReplayTraceId() || spanInfo.traceId;\n\n // Derive packageName from URL if needed\n let packageName = spanProtocol;\n try {\n const u = new URL(completeInputValue.url || inputValue.url);\n packageName = self._normalizeProtocol(u.protocol || undefined, spanProtocol);\n } catch {}\n\n // Compute schemas and hashes using the complete input value (with body)\n const { schema: inputSchema, decodedValueHash: inputValueHash } =\n JsonSchemaHelper.generateSchemaAndHash(completeInputValue, {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(\n (completeInputValue.headers && completeInputValue.headers[\"content-type\"]) ||\n \"\",\n ),\n },\n headers: {\n matchImportance: 0,\n },\n });\n\n const { schema: outputSchema, decodedValueHash: outputValueHash } =\n JsonSchemaHelper.generateSchemaAndHash(outputValue, {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(outputValue.headers[\"content-type\"] || \"\"),\n },\n headers: {\n matchImportance: 0,\n },\n });\n\n const cleanSpan = {\n traceId: replayTraceId,\n spanId: spanInfo.spanId,\n parentSpanId: \"\",\n name: `${completeInputValue.target || inputValue.target}`,\n packageName,\n instrumentationName: \"HttpInstrumentation\",\n submoduleName: completeInputValue.method || inputValue.method,\n inputValue: completeInputValue,\n outputValue,\n inputSchema,\n outputSchema,\n inputSchemaHash: JsonSchemaHelper.generateDeterministicHash(inputSchema),\n outputSchemaHash: JsonSchemaHelper.generateDeterministicHash(outputSchema),\n inputValueHash,\n outputValueHash,\n // Use OpenTelemetry SpanKind for CleanSpanData.kind\n kind: SpanKind.SERVER,\n packageType: PackageType.HTTP,\n status: {\n code: statusCode >= 400 ? StatusCode.ERROR : StatusCode.OK,\n message: statusCode >= 400 ? `HTTP ${statusCode}` : \"\",\n },\n timestamp: {\n seconds: Math.floor(now.getTime() / 1000),\n nanos: (now.getTime() % 1000) * 1_000_000,\n },\n duration: { seconds: 0, nanos: 0 },\n isRootSpan: true,\n isPreAppStart: false,\n metadata: undefined,\n };\n\n await self.tuskDrift.sendInboundSpanForReplay(cleanSpan);\n } catch (e) {\n logger.error(\"[HttpInstrumentation] Failed to build/send inbound replay span:\", e);\n }\n }\n });\n\n return originalEnd.call(this, chunk, encoding, callback);\n };\n\n // Track errors\n req.on(\"error\", (error: Error) => {\n try {\n logger.debug(\n `[HttpInstrumentation] Server request error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error ending span:`, error);\n }\n });\n\n res.on(\"error\", (error: Error) => {\n try {\n logger.debug(\n `[HttpInstrumentation] Server response error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error ending span:`, error);\n }\n });\n\n // Call the original handler within the span context\n return originalHandler.call(this);\n }\n\n /**\n * Captures the request body from an IncomingMessage stream by patching req.read() and listening for data events.\n * This is necessary because IncomingMessage doesn't expose the body directly - it must be read from the stream.\n *\n * The method handles two consumption patterns:\n * - READ mode: When application calls req.read() directly\n * - PIPE mode: When request is piped/streamed (data events)\n *\n * When the request body is fully captured (on 'end' event), it parses the body and updates the span\n * with the complete input data. This ensures exported spans contain the full request body information.\n *\n * NOTE: addAttributes() will override the current attributes so we need to pass current schema merges\n * to make sure we don't lose any information\n */\n private _captureServerRequestBody(\n req: IncomingMessage,\n spanInfo: SpanInfo,\n inputValue: {\n method: string;\n url: string;\n target: string;\n headers: IncomingHttpHeaders;\n httpVersion: string;\n remoteAddress?: string;\n remotePort?: number;\n },\n schemaMerges: SchemaMerges | undefined,\n onBodyCaptured?: (updatedInputValue: HttpServerInputValue) => void,\n ): void {\n const requestBodyChunks: Buffer[] = [];\n let streamConsumptionMode: \"NOT_CONSUMING\" | \"READ\" | \"PIPE\" = \"NOT_CONSUMING\";\n\n // Patch req.read to capture body chunks when application calls read()\n const originalRead = req.read.bind(req);\n req.read = function read(size?: number) {\n const chunk = originalRead(size);\n if (\n chunk &&\n (streamConsumptionMode === \"READ\" || streamConsumptionMode === \"NOT_CONSUMING\")\n ) {\n streamConsumptionMode = \"READ\";\n requestBodyChunks.push(Buffer.from(chunk));\n }\n return chunk;\n };\n\n // Listen for 'resume' event to know when streaming starts\n req.once(\"resume\", () => {\n req.addListener(\"data\", (chunk: string | Buffer) => {\n if (\n chunk &&\n (streamConsumptionMode === \"PIPE\" || streamConsumptionMode === \"NOT_CONSUMING\")\n ) {\n streamConsumptionMode = \"PIPE\";\n requestBodyChunks.push(Buffer.from(chunk));\n }\n });\n });\n\n // Process the complete body when the request ends\n req.addListener(\"end\", async (chunk?: string | Buffer) => {\n if (chunk) {\n requestBodyChunks.push(Buffer.from(chunk));\n }\n\n if (requestBodyChunks.length > 0) {\n try {\n const bodyBuffer = Buffer.concat(requestBodyChunks);\n\n // Parse the request body using existing body parser\n const encodedBody = await httpBodyEncoder({\n bodyBuffer,\n contentEncoding: req.headers[\"content-encoding\"] as string,\n });\n\n // Update input value with parsed body\n const updatedInputValue: HttpServerInputValue = {\n ...inputValue,\n body: encodedBody,\n bodySize: bodyBuffer.length,\n };\n\n if (onBodyCaptured) {\n onBodyCaptured(updatedInputValue);\n }\n\n // Update the span with the complete request body information\n SpanUtils.addSpanAttributes(spanInfo.span, {\n inputValue: updatedInputValue,\n inputSchemaMerges: {\n ...schemaMerges,\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(req.headers[\"content-type\"] || \"\"),\n },\n },\n });\n\n logger.debug(\n `[HttpInstrumentation] Captured request body for ${req.method} ${req.url}: ${bodyBuffer.length} bytes`,\n );\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error processing request body:`, error);\n }\n }\n });\n }\n\n private _captureClientRequestBody(\n req: ClientRequest,\n spanInfo: SpanInfo,\n inputValue: HttpClientInputValue,\n schemaMerges: SchemaMerges | undefined,\n ): void {\n const requestBodyChunks: (string | Buffer)[] = [];\n let requestBodyCaptured = false;\n\n // Patch the write method to capture request body\n const originalWrite = req.write?.bind(req);\n if (originalWrite) {\n req.write = function (chunk: any, encoding?: any, callback?: any): boolean {\n if (chunk && !requestBodyCaptured) {\n requestBodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));\n }\n return originalWrite.call(this, chunk, encoding, callback);\n };\n }\n\n // Patch the end method to capture final request body and process it\n const originalEnd = req.end?.bind(req);\n if (originalEnd) {\n req.end = function (chunk?: any, encoding?: any, callback?: any): ClientRequest {\n // Capture final chunk if provided\n if (chunk && !requestBodyCaptured) {\n requestBodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));\n }\n\n // Process captured request body asynchronously (don't block the request)\n if (requestBodyChunks.length > 0 && !requestBodyCaptured) {\n requestBodyCaptured = true;\n (async () => {\n try {\n const bodyBuffer = Buffer.concat(\n requestBodyChunks.map((chunk) =>\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk),\n ),\n );\n\n // Parse the request body using existing body parser\n const encodedBody = await httpBodyEncoder({\n bodyBuffer,\n });\n\n // Update input value with parsed body\n const updatedInputValue: HttpClientInputValue = {\n ...inputValue,\n body: encodedBody,\n bodySize: bodyBuffer.length,\n };\n\n // Update the span with the complete request body information\n SpanUtils.addSpanAttributes(spanInfo.span, {\n inputValue: updatedInputValue,\n inputSchemaMerges: {\n ...schemaMerges,\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(inputValue.headers[\"content-type\"] || \"\"),\n },\n },\n });\n\n logger.debug(\n `[HttpInstrumentation] Captured request body for ${req.method} ${req.path}: ${bodyBuffer.length} bytes`,\n );\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error processing request body:`, error);\n }\n })();\n }\n\n return originalEnd.call(this, chunk, encoding, callback);\n };\n }\n }\n\n /*\n * This is the main function that executes a real HTTP request with proper span handling\n * Should be passed to SpanExecutor.createAndExecuteSpan\n */\n private _handleOutboundRequestInSpan(\n originalRequest: Function,\n args: any[],\n spanInfo: SpanInfo,\n inputValue: HttpClientInputValue,\n schemaMerges: SchemaMerges | undefined,\n ) {\n const req = originalRequest.apply(this, args);\n\n // NOTE: This is a patch to capture the request body\n // This is necessary because ClientRequest doesn't have a .body property - we need to capture it from the stream\n // This patches req.write() and listens for 'data'/'end' events to collect body chunks as they arrive\n // Handles both write() consumption and pipe/stream consumption patterns used by different frameworks\n this._captureClientRequestBody(req, spanInfo, inputValue, schemaMerges);\n\n // Add event listeners to track request/response within span context\n req.on(\"response\", (res: IncomingMessage) => {\n logger.debug(\n `[HttpInstrumentation] HTTP response received: ${res.statusCode} (${SpanUtils.getTraceInfo()})`,\n );\n\n // Build basic output value object\n const outputValue: HttpClientOutputValue = {\n statusCode: res.statusCode,\n statusMessage: res.statusMessage,\n headers: this._captureHeadersFromRawHeaders(res.rawHeaders),\n httpVersion: res.httpVersion,\n httpVersionMajor: res.httpVersionMajor,\n httpVersionMinor: res.httpVersionMinor,\n complete: res.complete,\n readable: res.readable,\n };\n\n // Capture response body\n const responseChunks: (string | Buffer)[] = [];\n\n if (res.readable) {\n res.on(\"data\", (chunk: any) => {\n responseChunks.push(chunk);\n });\n\n res.on(\"end\", async () => {\n if (responseChunks.length > 0) {\n try {\n // Combine all chunks into a single buffer\n const responseBuffer = combineChunks(responseChunks);\n\n // Capture raw headers before processing\n const rawHeaders = this._captureHeadersFromRawHeaders(res.rawHeaders);\n\n // Store the raw headers\n outputValue.headers = rawHeaders;\n\n // Parse response body\n const contentEncoding = rawHeaders[\"content-encoding\"];\n const encodedBody = await httpBodyEncoder({\n bodyBuffer: responseBuffer,\n contentEncoding,\n });\n\n // Store parsed body data\n outputValue.body = encodedBody;\n outputValue.bodySize = responseBuffer.length;\n\n this._addOutputAttributesToSpan({\n spanInfo,\n outputValue,\n statusCode: res.statusCode || 1,\n outputSchemaMerges: {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(outputValue.headers[\"content-type\"] || \"\"),\n },\n headers: {\n matchImportance: 0,\n },\n },\n inputValue,\n });\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error processing response body:`, error);\n }\n }\n });\n } else {\n try {\n this._addOutputAttributesToSpan({\n spanInfo,\n outputValue,\n statusCode: res.statusCode || 1,\n outputSchemaMerges: {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(outputValue.headers[\"content-type\"] || \"\"),\n },\n headers: {\n matchImportance: 0,\n },\n },\n inputValue,\n });\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error adding output attributes to span:`, error);\n }\n }\n });\n\n req.on(\"error\", (error: Error) => {\n try {\n logger.debug(\n `[HttpInstrumentation] HTTP request error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[HttpInstrumentation] Error ending span:`, error);\n }\n });\n\n return req;\n }\n\n /**\n * Helper method to add output attributes to span\n */\n private _addOutputAttributesToSpan({\n spanInfo,\n outputValue,\n statusCode,\n outputSchemaMerges,\n inputValue,\n }: {\n spanInfo: SpanInfo;\n outputValue: HttpClientOutputValue;\n statusCode: number;\n outputSchemaMerges?: SchemaMerges;\n inputValue: HttpClientInputValue;\n }): void {\n // Apply transforms\n const normalizedProtocol = this._normalizeProtocol(inputValue.protocol, \"http\");\n const spanData: HttpSpanData = {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n kind: SpanKind.CLIENT,\n protocol: normalizedProtocol,\n inputValue,\n outputValue,\n };\n\n this.transformEngine.applyTransforms(spanData);\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n inputValue: spanData.inputValue,\n outputValue: spanData.outputValue,\n outputSchemaMerges,\n transformMetadata: spanData.transformMetadata ? spanData.transformMetadata : undefined,\n });\n\n // Set span status based on HTTP status\n const status =\n statusCode >= 400\n ? { code: SpanStatusCode.ERROR, message: `HTTP ${statusCode}` }\n : { code: SpanStatusCode.OK };\n\n SpanUtils.endSpan(spanInfo.span, status);\n }\n\n private _captureHeadersFromRawHeaders(rawHeaders: string[]): Record<string, string> {\n const headers: Record<string, string> = {};\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const key = rawHeaders[i].toLowerCase();\n const value = rawHeaders[i + 1];\n headers[key] = value;\n }\n return headers;\n }\n\n private _getRequestPatchFn(protocol: HttpProtocol) {\n const self = this;\n\n return (originalRequest: Function) => {\n return function (this: Request, ...args: any[]) {\n // Handle both URL string and RequestOptions object\n let requestOptions: RequestOptions;\n if (typeof args[0] === \"string\") {\n // Parse URL string into RequestOptions\n const url = new URL(args[0]);\n requestOptions = {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port ? parseInt(url.port) : undefined,\n path: url.pathname + url.search,\n method: args[1]?.method || \"GET\",\n headers: args[1]?.headers || {},\n };\n } else {\n requestOptions = args[0] || {};\n }\n const method = requestOptions.method || \"GET\";\n const requestProtocol = self._normalizeProtocol(\n requestOptions.protocol || undefined,\n protocol,\n );\n\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Build input value object for replay mode\n const headers = normalizeHeaders(requestOptions.headers || {});\n const inputValue: HttpClientInputValue = {\n method,\n path: requestOptions.path || undefined,\n headers,\n protocol: requestProtocol,\n hostname: requestOptions.hostname || requestOptions.host || undefined,\n port: requestOptions.port ? Number(requestOptions.port) : undefined,\n timeout: requestOptions.timeout || undefined,\n };\n\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalRequest.apply(this, args),\n {\n name: requestOptions.path || `${requestProtocol.toUpperCase()} ${method}`,\n kind: SpanKind.CLIENT,\n packageName: requestProtocol,\n packageType: PackageType.HTTP,\n instrumentationName: self.INSTRUMENTATION_NAME,\n submodule: method,\n inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self.replayHooks.handleOutboundReplayRequest({\n method,\n requestOptions,\n protocol: requestProtocol,\n args,\n spanInfo,\n });\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalRequest.apply(this, args),\n recordModeHandler: ({ isPreAppStart }) => {\n const headers = normalizeHeaders(requestOptions.headers || {});\n\n // Ignore SDK's own drift export calls\n if (\n headers[TUSK_SKIP_HEADER] === \"true\" ||\n isTuskDriftIngestionUrl(requestOptions.path)\n ) {\n return originalRequest.apply(this, args);\n }\n\n const inputValue: HttpClientInputValue = {\n method,\n path: requestOptions.path || undefined,\n headers,\n protocol: requestProtocol,\n hostname: requestOptions.hostname || requestOptions.host || undefined,\n port: requestOptions.port ? Number(requestOptions.port) : undefined,\n timeout: requestOptions.timeout || undefined,\n };\n\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalRequest.apply(this, args),\n {\n name: requestOptions.path || `${requestProtocol.toUpperCase()} ${method}`,\n kind: SpanKind.CLIENT,\n packageName: requestProtocol,\n packageType: PackageType.HTTP,\n instrumentationName: self.INSTRUMENTATION_NAME,\n submodule: method,\n inputValue,\n inputSchemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n isPreAppStart,\n },\n (spanInfo: SpanInfo) => {\n return self._handleOutboundRequestInSpan(\n originalRequest,\n args,\n spanInfo,\n inputValue,\n {\n headers: {\n matchImportance: 0,\n },\n },\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalRequest.apply(this, args);\n }\n };\n };\n }\n\n private _getGetPatchFn(protocol: HttpProtocol) {\n const self = this;\n\n return (originalGet: Function) => {\n return function (this: Request, ...args: any[]) {\n // Handle both URL string and RequestOptions object\n let requestOptions: RequestOptions;\n if (typeof args[0] === \"string\") {\n // Parse URL string into RequestOptions\n const url = new URL(args[0]);\n requestOptions = {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port ? parseInt(url.port) : undefined,\n path: url.pathname + url.search,\n headers: args[1]?.headers || {},\n };\n } else {\n requestOptions = args[0] || {};\n }\n const method = \"GET\";\n const requestProtocol = self._normalizeProtocol(\n requestOptions.protocol || undefined,\n protocol,\n );\n\n // Handle replay mode using replay hooks (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Build input value object for replay mode\n const headers = normalizeHeaders(requestOptions.headers || {});\n const inputValue: HttpClientInputValue = {\n method,\n path: requestOptions.path || undefined,\n headers,\n protocol: requestProtocol,\n hostname: requestOptions.hostname || requestOptions.host || undefined,\n port: requestOptions.port ? Number(requestOptions.port) : undefined,\n timeout: requestOptions.timeout || undefined,\n };\n\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalGet.apply(this, args),\n {\n name: requestOptions.path || `${requestProtocol.toUpperCase()} ${method}`,\n kind: SpanKind.CLIENT,\n packageName: requestProtocol,\n packageType: PackageType.HTTP,\n instrumentationName: self.INSTRUMENTATION_NAME,\n submodule: method,\n inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self.replayHooks.handleOutboundReplayRequest({\n method,\n requestOptions,\n protocol: requestProtocol,\n args,\n spanInfo,\n });\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalGet.apply(this, args),\n recordModeHandler: ({ isPreAppStart }) => {\n const headers = normalizeHeaders(requestOptions.headers || {});\n\n // Ignore SDK's own drift export calls\n if (\n headers[TUSK_SKIP_HEADER] === \"true\" ||\n isTuskDriftIngestionUrl(requestOptions.path)\n ) {\n return originalGet.apply(this, args);\n }\n\n const inputValue: HttpClientInputValue = {\n method,\n path: requestOptions.path || undefined,\n headers,\n protocol: requestProtocol,\n hostname: requestOptions.hostname || requestOptions.host || undefined,\n port: requestOptions.port ? Number(requestOptions.port) : undefined,\n timeout: requestOptions.timeout || undefined,\n };\n\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalGet.apply(this, args),\n {\n name: requestOptions.path || `${requestProtocol.toUpperCase()} ${method}`,\n kind: SpanKind.CLIENT,\n packageName: requestProtocol,\n packageType: PackageType.HTTP,\n instrumentationName: self.INSTRUMENTATION_NAME,\n submodule: method,\n inputValue,\n inputSchemaMerges: {\n headers: {\n matchImportance: 0,\n },\n },\n isPreAppStart,\n },\n (spanInfo: SpanInfo) => {\n return self._handleOutboundRequestInSpan(\n originalGet,\n args,\n spanInfo,\n inputValue,\n {\n headers: {\n matchImportance: 0,\n },\n },\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalGet.apply(this, args);\n }\n };\n };\n }\n\n private _getServerEmitPatchFn(protocol: HttpProtocol) {\n const self = this;\n\n return (originalEmit: Function) => {\n return function (this: Server, eventName: string, ...args: any[]) {\n if (eventName === \"request\") {\n const req = args[0];\n const res = args[1];\n\n return self._createServerSpan({\n req,\n res,\n originalHandler: () => {\n return originalEmit.apply(this, [eventName, ...args]);\n },\n protocol,\n });\n }\n\n return originalEmit.apply(this, [eventName, ...args]);\n };\n };\n }\n\n private _normalizeProtocol(protocol: string | undefined, fallback: HttpProtocol): HttpProtocol {\n if (!protocol) {\n return fallback;\n }\n\n const normalized = protocol.toLowerCase().replace(/:$/, \"\");\n if (normalized === \"http\" || normalized === \"https\") {\n return normalized;\n }\n\n return fallback;\n }\n\n private _wrap(\n target: HttpModuleExports | HttpsModuleExports | Server,\n propertyName: string,\n wrapper: (original: Function) => Function,\n ): void {\n wrap(target, propertyName, wrapper);\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { EnvVarTracker } from \"../../core/trackers\";\nimport { TdInstrumentationConfig } from \"../../core/baseClasses/TdInstrumentationAbstract\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport interface EnvInstrumentationConfig extends TdInstrumentationConfig {\n mode?: TuskDriftMode;\n}\n\n/**\n * Environment variable instrumentation that records and replays process.env access.\n * In record mode, captures environment variable values.\n * In replay mode, returns previously recorded values for deterministic behavior.\n */\nexport class EnvInstrumentation extends TdInstrumentationBase {\n private mode: TuskDriftMode;\n private originalProcessEnv?: typeof process.env;\n private isInPatchedCall = false;\n\n constructor(config: EnvInstrumentationConfig = {}) {\n super(\"env\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n }\n\n init(): TdInstrumentationNodeModule[] {\n // Environment variables are global, not a module, so we patch process.env directly\n this.patchProcessEnv();\n return [];\n }\n\n private patchProcessEnv(): void {\n // Unlike other instrumentations that patch modules when they're required (lazy patching),\n // env var instrumentation patches process.env immediately during init() since process.env\n // is a global object, not a module. This means we need to explicitly check if the\n // instrumentation is enabled before patching, otherwise we'd always patch process.env\n // even when the user has disabled env var recording via enable_env_var_recording config.\n if (this.mode === TuskDriftMode.DISABLED || !this._config.enabled) {\n return;\n }\n\n this.originalProcessEnv = process.env;\n\n // Create a proxy around process.env\n const envProxy = new Proxy(this.originalProcessEnv, {\n get: (target, property, receiver) => {\n return this._handleEnvAccess(target, property as string);\n },\n set: (target, property, value, receiver) => {\n // Allow setting env vars normally\n target[property as string] = value;\n return true;\n },\n deleteProperty: (target, property) => {\n delete target[property as string];\n return true;\n },\n ownKeys: (target) => {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor: (target, property) => {\n return Reflect.getOwnPropertyDescriptor(target, property);\n },\n has: (target, property) => {\n return Reflect.has(target, property);\n },\n });\n\n // Replace global process.env with our proxy\n process.env = envProxy;\n }\n\n private _handleEnvAccess(target: typeof process.env, key: string): string | undefined {\n // Prevent recursion\n if (this.isInPatchedCall) {\n return target[key];\n }\n\n if (!TuskDriftCore.getInstance().isAppReady()) {\n // Want to use the original process.env when app is in process of starting up\n return target[key];\n }\n\n this.isInPatchedCall = true;\n try {\n return this._handleEnvAccessInMode(target, key);\n } finally {\n this.isInPatchedCall = false;\n }\n }\n\n private _handleEnvAccessInMode(target: typeof process.env, key: string): string | undefined {\n let currentSpanInfo: SpanInfo | null = null;\n try {\n currentSpanInfo = SpanUtils.getCurrentSpanInfo();\n } catch (error) {\n logger.error(`EnvInstrumentation error getting current span info:`, error);\n }\n\n if (!currentSpanInfo) {\n return target[key];\n }\n\n if (this.mode === TuskDriftMode.REPLAY) {\n return this._handleReplayMode(target, key);\n } else if (this.mode === TuskDriftMode.RECORD) {\n return this._handleRecordMode(currentSpanInfo, target, key);\n } else {\n return target[key];\n }\n }\n\n private _handleReplayMode(target: typeof process.env, key: string): string | undefined {\n const replayTraceId = SpanUtils.getCurrentReplayTraceId();\n if (!replayTraceId) {\n return target[key];\n }\n\n const envVar = EnvVarTracker.getEnvVar(replayTraceId, key);\n if (envVar) {\n logger.debug(`Returning env var ${key} for trace ${replayTraceId}: ${envVar}`);\n return envVar;\n }\n\n return target[key];\n }\n\n private _handleRecordMode(\n spanInfo: SpanInfo,\n target: typeof process.env,\n key: string,\n ): string | undefined {\n try {\n EnvVarTracker.setEnvVar({\n traceId: spanInfo.traceId,\n key,\n value: target[key] || undefined,\n });\n } catch (error) {\n logger.error(`EnvInstrumentation error storing env var:`, error);\n }\n return target[key];\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind } from \"@opentelemetry/api\";\nimport { TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { SPAN_KIND_CONTEXT_KEY } from \"../../../core/types\";\nimport { wrap } from \"../../core/utils\";\nimport { DateInstrumentationConfig } from \"./types\";\nimport { DateTracker } from \"../../core/trackers\";\nimport { logger } from \"../../../core/utils/logger\";\n\n/**\n * Date instrumentation that provides consistent dates in replay mode.\n * In replay mode, new Date() calls return the latest mock response timestamp.\n *\n * Note: this probably won't match exactly to the milliseconds, but it will be very close to date the application probably expects\n */\nexport class DateInstrumentation extends TdInstrumentationBase {\n private mode: TuskDriftMode;\n private originalDate?: typeof Date;\n private isInPatchedCall = false;\n private static instance: DateInstrumentation;\n\n constructor(config: DateInstrumentationConfig = {}) {\n super(\"date\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n DateInstrumentation.instance = this;\n }\n\n init(): TdInstrumentationNodeModule[] {\n // Date is a global, not a module, so we patch it directly\n this.patchGlobalDate();\n return [];\n }\n\n private patchGlobalDate(): void {\n // Unlike other instrumentations that patch modules when they're required (lazy patching),\n // date instrumentation patches the global Date function immediately during init() since\n // Date is a global API, not a module. This means we need to explicitly check if the\n // instrumentation is enabled before patching, otherwise we'd always patch globalThis.Date\n // even when the user has disabled date instrumentation.\n if (this.mode === TuskDriftMode.DISABLED || !this._config.enabled) {\n return;\n }\n\n this.originalDate = globalThis.Date;\n\n const _TdDate = this._wrap(globalThis, \"Date\", this.getDatePatchFn());\n\n // Copy static methods\n _TdDate.now = function (): number {\n return new _TdDate().getTime();\n };\n _TdDate.parse = this.originalDate!.parse.bind(this.originalDate!);\n _TdDate.UTC = this.originalDate!.UTC.bind(this.originalDate!);\n\n // Set up prototype chain\n Object.setPrototypeOf(_TdDate.prototype, this.originalDate!.prototype);\n Object.defineProperty(_TdDate, Symbol.hasInstance, {\n value: (instance: any) => instance instanceof this.originalDate!,\n });\n\n logger.debug(\"Global Date patching complete\");\n }\n\n static getOriginalDate(): Date | string {\n return new DateInstrumentation.instance.originalDate!();\n }\n\n private _handleDateCall(args: any[], isConstructorCall: boolean): Date | string {\n // Prevent recursion\n if (this.isInPatchedCall) {\n return this._callOriginalDate(args, isConstructorCall);\n }\n\n // Only handle replay mode, pass through everything else\n if (this.mode !== TuskDriftMode.REPLAY) {\n return this._callOriginalDate(args, isConstructorCall);\n }\n\n const currentSpanInfo = SpanUtils.getCurrentSpanInfo();\n if (!currentSpanInfo) {\n return this._callOriginalDate(args, isConstructorCall);\n }\n\n // We only want to replace Date calls from server spans\n const spanKind = currentSpanInfo.context.getValue(SPAN_KIND_CONTEXT_KEY);\n if (spanKind !== SpanKind.SERVER) {\n return this._callOriginalDate(args, isConstructorCall);\n }\n\n this.isInPatchedCall = true;\n try {\n return this._handleReplayDate(args, isConstructorCall);\n } finally {\n this.isInPatchedCall = false;\n }\n }\n\n private _handleReplayDate(args: any[], isConstructorCall: boolean): Date | string {\n // If new Date() is called without arguments, use the latest timestamp from trace\n if (args.length === 0) {\n const latestDate = DateTracker.getCurrentTraceLatestDate();\n if (latestDate) {\n logger.debug(\n `Replacing new Date() with latest trace timestamp: ${latestDate.toISOString()}`,\n );\n return isConstructorCall\n ? new this.originalDate!(latestDate.getTime())\n : latestDate.toString();\n }\n }\n\n // For all other cases (Date with arguments), use original behavior\n return this._callOriginalDate(args, isConstructorCall);\n }\n\n private _callOriginalDate(args: any[], isConstructorCall: boolean): Date | string {\n if (isConstructorCall) {\n if (args.length === 0) {\n return new this.originalDate!();\n }\n return new (this.originalDate as any)(...args);\n } else {\n // Function call: Date() - should return string\n return new this.originalDate!().toString();\n }\n }\n\n private getDatePatchFn() {\n const self = this;\n return (OriginalDate: typeof Date) => {\n function _TdDate(this: any, ...args: any[]): Date | string {\n const isConstructorCall = new.target !== undefined;\n return self._handleDateCall(args, isConstructorCall);\n }\n return _TdDate;\n };\n }\n\n private _wrap(target: any, propertyName: string, wrapper: (original: any) => any): any {\n wrap(target, propertyName, wrapper);\n return target[propertyName];\n }\n}\n","import { normalize } from \"path\";\n\nexport type PatchFunction = (moduleExports: any, moduleVersion?: string) => any;\n\nexport class TdInstrumentationNodeModuleFile {\n name: string;\n supportedVersions: string[];\n patch: PatchFunction;\n moduleExports?: any;\n\n constructor({\n name,\n supportedVersions,\n patch,\n }: {\n name: string;\n supportedVersions: string[];\n patch: PatchFunction;\n }) {\n this.name = normalize(name);\n this.supportedVersions = supportedVersions;\n this.patch = patch;\n }\n}\n","interface GraphQLTypeNode {\n kind: string;\n type?: GraphQLTypeNode;\n name?: { value: string };\n}\n\ninterface GraphQLVariableDefinition {\n variable?: { name?: { value: string } };\n type?: GraphQLTypeNode;\n}\n\ninterface GraphQLSelectionSet {\n selections: GraphQLSelection[];\n}\n\ninterface GraphQLSelection {\n kind: string;\n name?: { value: string };\n alias?: { value: string };\n selectionSet?: GraphQLSelectionSet;\n arguments?: GraphQLArgument[];\n directives?: GraphQLDirective[];\n}\n\ninterface GraphQLArgument {\n kind: string;\n value?: any;\n}\n\ninterface GraphQLDirective {\n arguments: GraphQLArgument[];\n}\n\ninterface GraphQLOperationDefinition {\n kind: string;\n operation: string;\n name?: { value: string };\n variableDefinitions?: GraphQLVariableDefinition[];\n selectionSet: GraphQLSelectionSet;\n}\n\ninterface GraphQLExecutionArgs {\n document: { definitions: any[] };\n variableValues?: any;\n operationName?: string;\n}\n\nexport const getOperationDefinition = (\n payload: GraphQLExecutionArgs,\n): GraphQLOperationDefinition | undefined =>\n payload.document.definitions.find(\n (definition: any) => definition?.kind === \"OperationDefinition\",\n ) as GraphQLOperationDefinition | undefined;\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { TdInstrumentationConfig } from \"../../core/baseClasses/TdInstrumentationAbstract\";\nimport { TdInstrumentationNodeModuleFile } from \"../../core/baseClasses/TdInstrumentationNodeModuleFile\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { wrap } from \"../../core/utils\";\nimport { getOperationDefinition } from \"./utils\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { Span } from \"@opentelemetry/api\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport interface GraphqlInstrumentationConfig extends TdInstrumentationConfig {\n mode?: TuskDriftMode;\n}\n\n/**\n * GraphQL is instrumented purely for presentational metadata.\n * We do not replay GraphQL operations.\n *\n * Behavior:\n * - REPLAY mode: Just call original functions (no patching)\n * - RECORD mode: Intercept GraphQL execute calls and add presentational metadata to parent HTTP spans\n * - Add presentational metadata to parent HTTP spans\n * - Always call original GraphQL functions\n */\nexport class GraphqlInstrumentation extends TdInstrumentationBase {\n private tuskDrift: TuskDriftCore;\n\n constructor(config: GraphqlInstrumentationConfig = {}) {\n super(\"graphql\", config);\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n // Patch GraphQL v16\n const patchGraphqlExecuteV16 = new TdInstrumentationNodeModuleFile({\n name: \"graphql/execution/execute.js\",\n supportedVersions: [\"16.*\"],\n // Graphql v16 deprecated executeSync\n patch: (moduleExports: any) => {\n this._wrap(moduleExports, \"execute\", this._patchExecuteFn());\n return moduleExports;\n },\n });\n\n // Patch GraphQL v15\n const patchGraphqlExecuteV15 = new TdInstrumentationNodeModuleFile({\n name: \"graphql/execution/execute.js\",\n supportedVersions: [\"15.*\"],\n patch: (moduleExports: any) => {\n this._wrap(moduleExports, \"execute\", this._patchExecuteFn());\n this._wrap(moduleExports, \"executeSync\", this._patchExecuteFn());\n return moduleExports;\n },\n });\n\n const moduleGraphqlV16 = new TdInstrumentationNodeModule({\n name: \"graphql\",\n supportedVersions: [\"16.*\"],\n patch: (moduleExports: any) => moduleExports,\n // execute doesn't exist in the main module export\n // Hence we patch the files directly\n files: [patchGraphqlExecuteV16],\n });\n\n const moduleGraphqlV15 = new TdInstrumentationNodeModule({\n name: \"graphql\",\n supportedVersions: [\"15.*\"],\n patch: (moduleExports: any) => moduleExports,\n // execute and executeSync don't exist in the main module export\n // Hence we patch the files directly\n files: [patchGraphqlExecuteV15],\n });\n\n return [moduleGraphqlV15, moduleGraphqlV16];\n }\n\n /**\n * Patch GraphQL execute function to add metadata to parent HTTP server spans\n */\n private _patchExecuteFn() {\n const self = this;\n return (originalExecute: any) => {\n return function execute(this: any, ...args: any[]) {\n return self._handleGraphQLExecution(\"execute\", originalExecute, args, this);\n };\n };\n }\n\n /**\n * Handle GraphQL execution - add metadata to parent server span if present\n */\n private _handleGraphQLExecution(\n methodName: string,\n originalMethod: Function,\n args: any[],\n context: any,\n ): any {\n if (this.tuskDrift.getMode() !== TuskDriftMode.RECORD) {\n logger.debug(`[GraphQLInstrumentation] Not in RECORD mode, skipping instrumentation`);\n return originalMethod.apply(context, args);\n }\n\n let currentSpanInfo: SpanInfo | null = null;\n try {\n currentSpanInfo = SpanUtils.getCurrentSpanInfo();\n } catch (error) {\n logger.error(`[GraphQLInstrumentation] error getting current span info:`, error);\n }\n\n if (!currentSpanInfo) {\n logger.debug(\n `[GraphQLInstrumentation] No current span found for ${methodName}, calling original`,\n );\n return originalMethod.apply(context, args);\n }\n\n try {\n logger.debug(`[GraphQLInstrumentation] Update span attributes with GraphQL info`);\n this._addGraphQLMetadataToSpan(currentSpanInfo.span, args);\n } catch (error) {\n logger.warn(\n `[GraphQLInstrumentation] Failed to update span attributes with GraphQL info:`,\n error,\n );\n }\n\n return originalMethod.apply(context, args);\n }\n\n /**\n * Extract GraphQL metadata from execution args and add to span\n */\n private _addGraphQLMetadataToSpan(span: Span, args: any[]): void {\n const [executionArgs] = args;\n\n if (!executionArgs || !executionArgs.document) {\n logger.warn(`[GraphQLInstrumentation] No execution args or document found`);\n return;\n }\n\n try {\n // Extract operation information\n const operationDef = getOperationDefinition(executionArgs);\n const operationType = operationDef?.operation || \"query\";\n const operationName = executionArgs.operationName || operationDef?.name?.value || \"Anonymous\";\n\n SpanUtils.addSpanAttributes(span, {\n name: `${operationType} ${operationName}`,\n packageType: PackageType.GRAPHQL,\n });\n } catch (error) {\n logger.warn(`[GraphQLInstrumentation] Error extracting GraphQL metadata:`, error);\n }\n }\n\n private _wrap(target: any, propertyName: string, wrapper: (original: any) => any): void {\n wrap(target, propertyName, wrapper);\n }\n}\n","import { EventEmitter } from \"events\";\nimport { PgInstrumentation } from \"../Instrumentation\";\nimport { createMockInputValue } from \"../../../../core/utils\";\nimport { SpanInfo } from \"../../../../core/tracing/SpanUtils\";\nimport { logger } from \"../../../../core/utils/logger\";\n\n/**\n * Mock PostgreSQL client for replay mode\n * Extends EventEmitter to properly handle all client methods and events\n */\nexport class TdPgClientMock extends EventEmitter {\n private pgInstrumentation: PgInstrumentation;\n private spanInfo: SpanInfo;\n\n constructor(pgInstrumentation: PgInstrumentation, spanInfo: SpanInfo) {\n super();\n this.pgInstrumentation = pgInstrumentation;\n this.spanInfo = spanInfo;\n }\n\n query(...args: any[]) {\n logger.debug(`[TdPgClientMock] Mock pool client query intercepted in REPLAY mode`);\n\n // Parse query arguments similar to the main query patch\n const queryConfig = this.pgInstrumentation.parseQueryArgs(args);\n\n if (!queryConfig || !queryConfig.text) {\n logger.debug(`[TdPgClientMock] Could not parse mock client query, returning empty result`);\n return Promise.resolve({ rows: [], rowCount: 0 });\n }\n\n const rawInputValue = {\n text: queryConfig.text,\n values: queryConfig.values || [],\n clientType: \"client\",\n };\n\n const inputValue = createMockInputValue(rawInputValue);\n\n return this.pgInstrumentation.handleReplayQuery(queryConfig, inputValue, this.spanInfo);\n }\n\n release() {\n // No-op for pool client release - just emit end event to simulate normal behavior\n this.emit(\"end\");\n }\n\n end() {\n this.emit(\"end\");\n return Promise.resolve();\n }\n\n connect(callback?: Function) {\n // Mock connect - already connected\n if (callback) {\n process.nextTick(() => callback(null));\n return;\n }\n return Promise.resolve();\n }\n\n // Additional pg Client properties and methods that might be expected by ORMs\n get connectionParameters() {\n return {\n host: \"localhost\",\n port: 5432,\n database: \"mock\",\n user: \"mock\",\n };\n }\n\n get readyForQuery() {\n return true;\n }\n\n get processID() {\n return 12345;\n }\n\n get secretKey() {\n return 67890;\n }\n\n get activeQuery() {\n return false;\n }\n\n pauseDrain() {\n // No-op\n }\n\n resumeDrain() {\n // No-op\n }\n\n escapeIdentifier(str: string) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n escapeLiteral(str: string) {\n return `'${str.replace(/'/g, \"''\")}'`;\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { wrap } from \"../../core/utils\";\nimport { TdPgClientMock } from \"./mocks/TdPgClientMock\";\nimport { findMockResponseAsync } from \"../../core/utils/mockResponseUtils\";\nimport { handleRecordMode, handleReplayMode } from \"../../core/utils/modeUtils\";\nimport {\n PgModuleExports,\n PgPoolModuleExports,\n PgClientInputValue,\n PgInstrumentationConfig,\n QueryConfig,\n PgResult,\n} from \"./types\";\n// NOTE: these types are from version 8.15.5 of pg\n// Older versions of pg may have different types, but this is fine for now\nimport { Connection, Query, Pool, PoolClient, Client } from \"pg\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport class PgInstrumentation extends TdInstrumentationBase {\n private readonly INSTRUMENTATION_NAME = \"PgInstrumentation\";\n private mode: TuskDriftMode;\n private tuskDrift: TuskDriftCore;\n\n constructor(config: PgInstrumentationConfig = {}) {\n super(\"pg\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"pg\",\n supportedVersions: [\"8.*\"],\n patch: (moduleExports: PgModuleExports) => this._patchPgModule(moduleExports),\n }),\n new TdInstrumentationNodeModule({\n name: \"pg-pool\",\n supportedVersions: [\"2.*\", \"3.*\"],\n patch: (moduleExports: PgPoolModuleExports) => this._patchPgPoolModule(moduleExports),\n }),\n // TODO: instrument pg-cursor\n ];\n }\n\n private _patchPgModule(pgModule: PgModuleExports): PgModuleExports {\n logger.debug(`[PgInstrumentation] Patching PG module in ${this.mode} mode`);\n\n if (pgModule._tdPatched) {\n logger.debug(`[PgInstrumentation] PG module already patched, skipping`);\n return pgModule;\n }\n\n // Wrap Client.prototype.query\n if (pgModule.Client && pgModule.Client.prototype) {\n this._wrap(pgModule.Client.prototype, \"query\", this._getQueryPatchFn(\"client\"));\n logger.debug(`[PgInstrumentation] Wrapped Client.prototype.query`);\n }\n\n // Wrap Client.prototype.connect\n if (pgModule.Client && pgModule.Client.prototype) {\n this._wrap(pgModule.Client.prototype, \"connect\", this._getConnectPatchFn(\"client\"));\n logger.debug(`[PgInstrumentation] Wrapped Client.prototype.connect`);\n }\n\n pgModule._tdPatched = true;\n logger.debug(`[PgInstrumentation] PG module patching complete`);\n\n return pgModule;\n }\n\n private _getQueryPatchFn(clientType: string) {\n const self = this;\n\n return (originalQuery: Function) => {\n return function query(this: Query, ...args: any[]) {\n // Parse query arguments - pg supports multiple signatures\n let queryConfig: QueryConfig | null = null;\n try {\n queryConfig = self.parseQueryArgs(args);\n } catch (error) {\n logger.error(`[PgInstrumentation] error parsing query args:`, error);\n }\n\n if (!queryConfig || !queryConfig.text) {\n // If we can't parse the query, let it pass through\n logger.debug(`[PgInstrumentation] Could not parse query, returning`, args);\n return originalQuery.apply(this, args);\n }\n\n const inputValue: PgClientInputValue = {\n text: queryConfig.text,\n values: queryConfig.values || [],\n clientType,\n };\n\n // Handle replay mode (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Create span in replay mode\n const packageName = inputValue.clientType === \"pool\" ? \"pg-pool\" : \"pg\";\n const spanName = inputValue.clientType === \"pool\" ? \"pg-pool.query\" : \"pg.query\";\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalQuery.apply(this, args),\n {\n name: spanName,\n kind: SpanKind.CLIENT,\n submodule: \"query\",\n packageType: PackageType.PG,\n packageName: packageName,\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self.handleReplayQuery(queryConfig, inputValue, spanInfo);\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalQuery.apply(this, args),\n recordModeHandler: ({ isPreAppStart }) => {\n // Record mode - create span and execute real query\n // Create span for database query\n const packageName = inputValue.clientType === \"pool\" ? \"pg-pool\" : \"pg\";\n const spanName = inputValue.clientType === \"pool\" ? \"pg-pool.query\" : \"pg.query\";\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalQuery.apply(this, args),\n {\n name: spanName,\n kind: SpanKind.CLIENT,\n submodule: \"query\",\n packageType: PackageType.PG,\n instrumentationName: self.INSTRUMENTATION_NAME,\n packageName: packageName,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return self._handleRecordQueryInSpan(\n spanInfo,\n originalQuery,\n queryConfig,\n args,\n this,\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalQuery.apply(this, args);\n }\n };\n };\n }\n\n private _getConnectPatchFn(clientType: string) {\n const self = this;\n\n return (originalConnect: Function) => {\n return function connect(this: Connection, callback?: Function) {\n const inputValue = { clientType };\n\n // Handle replay mode (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalConnect.apply(this, [callback]),\n {\n name: `pg.connect`,\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageName: \"pg\",\n packageType: PackageType.PG,\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self._handleReplayConnect(callback);\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalConnect.apply(this, [callback]),\n recordModeHandler: ({ isPreAppStart }) => {\n // Record mode - create span and execute real connect\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalConnect.apply(this, [callback]),\n {\n name: `pg.connect`,\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageName: \"pg\",\n packageType: PackageType.PG,\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return self._handleRecordConnectInSpan(spanInfo, originalConnect, callback, this);\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalConnect.apply(this, [callback]);\n }\n };\n };\n }\n\n parseQueryArgs(args: any[]): QueryConfig | null {\n if (args.length === 0) return null;\n\n const firstArg = args[0];\n\n // String query: query(text, values?, callback?)\n if (typeof firstArg === \"string\") {\n const config: QueryConfig = {\n text: firstArg,\n callback: typeof args[args.length - 1] === \"function\" ? args[args.length - 1] : undefined,\n };\n if (Array.isArray(args[1])) {\n config.values = args[1];\n }\n return config;\n }\n\n // Query config object: query(config, callback?)\n if (typeof firstArg === \"object\" && firstArg.text) {\n return {\n text: firstArg.text,\n values: firstArg.values,\n callback: firstArg.callback || (typeof args[1] === \"function\" ? args[1] : undefined),\n };\n }\n\n return null;\n }\n\n private _handleRecordQueryInSpan(\n spanInfo: SpanInfo,\n originalQuery: Function,\n queryConfig: QueryConfig,\n args: any[],\n context: Query,\n ): Query {\n const hasCallback = !!queryConfig.callback;\n\n if (hasCallback) {\n // Callback-based query\n const originalCallback = queryConfig.callback!;\n const wrappedCallback = (error: Error | null, result?: PgResult) => {\n if (error) {\n logger.debug(\n `[PgInstrumentation] PG query error (hasCallback): ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n } else {\n logger.debug(\n `[PgInstrumentation] PG query completed successfully (hasCallback) (${SpanUtils.getTraceInfo()})`,\n );\n try {\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing response:`, error);\n }\n }\n return originalCallback(error, result);\n };\n\n // Replace callback in args\n try {\n const firstArg = args[0];\n const isConfigObject = typeof firstArg === \"object\" && firstArg.text && firstArg.callback;\n\n if (isConfigObject) {\n // Callback was in config object\n const configIndex = 0; // First argument is the config\n args[configIndex] = { ...args[configIndex], callback: wrappedCallback };\n } else {\n // Callback was separate argument (last argument)\n const callbackIndex = args.findIndex((arg) => typeof arg === \"function\");\n if (callbackIndex >= 0) {\n args[callbackIndex] = wrappedCallback;\n }\n }\n } catch (error) {\n logger.error(`[PgInstrumentation] error replacing callback:`, error, args);\n }\n\n return originalQuery.apply(context, args);\n } else {\n // Promise-based query\n const promise = originalQuery.apply(context, args);\n\n return promise\n .then((result: PgResult) => {\n logger.debug(\n `[PgInstrumentation] PG query completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing response:`, error);\n }\n return result;\n })\n .catch((error: Error) => {\n logger.debug(\n `[PgInstrumentation] PG query error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n throw error;\n });\n }\n }\n\n async handleReplayQuery(\n queryConfig: QueryConfig,\n inputValue: PgClientInputValue,\n spanInfo: SpanInfo,\n ): Promise<any> {\n logger.debug(`[PgInstrumentation] Replaying PG query`);\n\n const packageName = inputValue.clientType === \"pool\" ? \"pg-pool\" : \"pg\";\n const spanName = inputValue.clientType === \"pool\" ? \"pg-pool.query\" : \"pg.query\";\n\n // Look for matching recorded response\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name: spanName,\n inputValue: inputValue,\n packageName: packageName,\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: \"query\",\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n if (!mockData) {\n const queryText = queryConfig.text || inputValue.text || \"UNKNOWN_QUERY\";\n logger.warn(`[PgInstrumentation] No mock data found for PG query: ${queryText}`);\n if (queryConfig.callback) {\n process.nextTick(() => queryConfig.callback!(new Error(\"No mock data found\")));\n return;\n } else {\n return Promise.reject(new Error(\"No mock data found\"));\n }\n }\n\n // Convert string timestamps back to Date objects based on field metadata\n const processedResult = this.convertPostgresTypes(mockData.result);\n\n // Return mocked response\n if (queryConfig.callback) {\n process.nextTick(() => {\n queryConfig.callback!(null, processedResult);\n });\n return;\n } else {\n return Promise.resolve(processedResult);\n }\n }\n\n /**\n * Convert PostgreSQL string values back to appropriate JavaScript types\n * based on field metadata from the recorded response.\n *\n * Reference for data type IDs: https://jdbc.postgresql.org/documentation/publicapi/constant-values.html\n */\n private convertPostgresTypes(result: any): any {\n if (!result || !result.fields || !result.rows) {\n return result;\n }\n\n // Create a map of field names to their PostgreSQL data types\n const fieldTypeMap: Record<string, number> = {};\n result.fields.forEach((field: any) => {\n fieldTypeMap[field.name] = field.dataTypeID;\n });\n\n // Convert rows based on field types\n const convertedRows = result.rows.map((row: any, rowIndex: number) => {\n const convertedRow = { ...row };\n\n Object.keys(row).forEach((fieldName) => {\n const dataTypeID = fieldTypeMap[fieldName];\n const value = row[fieldName];\n\n if (value === null || value === undefined) {\n return; // Keep null/undefined values as-is\n }\n\n switch (dataTypeID) {\n case 1184: // timestamptz (timestamp with timezone)\n case 1114: // timestamp (timestamp without timezone)\n if (typeof value === \"string\") {\n const dateObj = new Date(value);\n convertedRow[fieldName] = dateObj;\n }\n break;\n case 1082: // date\n if (typeof value === \"string\") {\n convertedRow[fieldName] = new Date(value);\n }\n break;\n case 1083: // time\n case 1266: // timetz (time with timezone)\n // Keep time fields as strings for now, as they're not typically\n // converted to Date objects by pg client\n break;\n // Add other type conversions as needed\n default:\n // Keep other types as-is\n break;\n }\n });\n\n return convertedRow;\n });\n\n const finalResult = {\n ...result,\n rows: convertedRows,\n };\n\n return finalResult;\n }\n\n private _handleRecordConnectInSpan(\n spanInfo: SpanInfo,\n originalConnect: Function,\n callback: Function | undefined,\n context: Connection,\n ): Connection {\n if (callback) {\n // Callback-based connect\n const wrappedCallback = (error: Error | null) => {\n if (error) {\n logger.debug(\n `[PgInstrumentation] PG connect error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n } else {\n logger.debug(\n `[PgInstrumentation] PG connect completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { connected: true },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing connect response:`, error);\n }\n }\n return callback(error);\n };\n\n return originalConnect.call(context, wrappedCallback);\n } else {\n // Promise-based connect\n const promise = originalConnect.call(context);\n\n return promise\n .then((result: Connection) => {\n logger.debug(\n `[PgInstrumentation] PG connect completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { connected: true },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing connect response:`, error);\n }\n return result;\n })\n .catch((error: Error) => {\n logger.debug(\n `[PgInstrumentation] PG connect error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n throw error;\n });\n }\n }\n\n private _handleReplayConnect(callback?: Function) {\n logger.debug(`[PgInstrumentation] Replaying PG connect`);\n\n // For connect operations, just simulate success\n if (callback) {\n process.nextTick(() => callback(null));\n return;\n } else {\n return Promise.resolve();\n }\n }\n\n private _addOutputAttributesToSpan(spanInfo: SpanInfo, result?: PgResult): void {\n if (!result) return;\n\n const outputValue = {\n command: result.command,\n rowCount: result.rowCount,\n oid: result.oid,\n rows: result.rows || [],\n fields: result.fields || [],\n };\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue,\n });\n }\n\n private _patchPgPoolModule(pgPoolModule: PgPoolModuleExports): PgPoolModuleExports {\n if (pgPoolModule._tdPatched) {\n logger.debug(`[PgInstrumentation] PG Pool module already patched, skipping`);\n return pgPoolModule;\n }\n\n // Wrap Pool.prototype.query\n if (pgPoolModule.prototype) {\n this._wrap(pgPoolModule.prototype, \"query\", this._getQueryPatchFn(\"pool\"));\n logger.debug(`[PgInstrumentation] Wrapped Pool.prototype.query`);\n }\n\n // Wrap Pool.prototype.connect\n if (pgPoolModule.prototype) {\n this._wrap(pgPoolModule.prototype, \"connect\", this._getPoolConnectPatchFn());\n logger.debug(`[PgInstrumentation] Wrapped Pool.prototype.connect`);\n }\n\n pgPoolModule._tdPatched = true;\n logger.debug(`[PgInstrumentation] PG Pool module patching complete`);\n\n return pgPoolModule;\n }\n\n private _getPoolConnectPatchFn() {\n const self = this;\n\n return (originalConnect: Function) => {\n return function connect(this: Connection, callback?: Function) {\n const inputValue = { clientType: \"pool\" };\n\n // Handle replay mode (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalConnect.apply(this, [callback]),\n {\n name: `pg-pool.connect`,\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageName: \"pg-pool\",\n packageType: PackageType.PG,\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self._handleReplayPoolConnect(spanInfo, callback);\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalConnect.apply(this, [callback]),\n recordModeHandler: ({ isPreAppStart }) => {\n // Record mode - create span and execute real connect\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalConnect.apply(this, [callback]),\n {\n name: `pg-pool.connect`,\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageName: \"pg-pool\",\n packageType: PackageType.PG,\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return self._handleRecordPoolConnectInSpan(\n spanInfo,\n originalConnect,\n callback,\n this,\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalConnect.apply(this, [callback]);\n }\n };\n };\n }\n\n private _handleRecordPoolConnectInSpan(\n spanInfo: SpanInfo,\n originalConnect: Function,\n callback: Function | undefined,\n context: Connection,\n ): Connection {\n if (callback) {\n // Callback-based pool connect\n const wrappedCallback = (error: Error | null, client?: PoolClient, done?: Function) => {\n if (error) {\n logger.debug(\n `[PgInstrumentation] PG Pool connect error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n } else {\n logger.debug(\n `[PgInstrumentation] PG Pool connect completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: {\n connected: true,\n hasClient: !!client,\n },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing pool connect response:`, error);\n }\n }\n return callback(error, client, done);\n };\n\n return originalConnect.call(context, wrappedCallback);\n } else {\n // Promise-based pool connect\n const promise = originalConnect.call(context);\n\n return promise\n .then((client: PoolClient) => {\n logger.debug(\n `[PgInstrumentation] PG Pool connect completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: {\n connected: true,\n hasClient: !!client,\n },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PgInstrumentation] error processing pool connect response:`, error);\n }\n return client;\n })\n .catch((error: Error) => {\n logger.debug(\n `[PgInstrumentation] PG Pool connect error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PgInstrumentation] error ending span:`, error);\n }\n throw error;\n });\n }\n }\n\n private _handleReplayPoolConnect(spanInfo: SpanInfo, callback?: Function) {\n logger.debug(`[PgInstrumentation] Replaying PG Pool connect`);\n\n // For pool connect operations, simulate returning a mock client\n // The client's query method should also be instrumented for replay\n const mockClient = new TdPgClientMock(this, spanInfo);\n\n if (callback) {\n process.nextTick(() => callback(null, mockClient, () => {}));\n return;\n } else {\n return Promise.resolve(mockClient);\n }\n }\n\n private _wrap(\n target: Query | Connection | Client | Pool,\n propertyName: string,\n wrapper: (original: any) => any,\n ): void {\n wrap(target, propertyName, wrapper);\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { wrap } from \"../../core/utils\";\nimport { findMockResponseAsync } from \"../../core/utils/mockResponseUtils\";\nimport { handleRecordMode, handleReplayMode } from \"../../core/utils/modeUtils\";\nimport {\n PostgresModuleExports,\n PostgresClientInputValue,\n PostgresInstrumentationConfig,\n PostgresRow,\n PostgresConvertedResult,\n} from \"./types\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport class PostgresInstrumentation extends TdInstrumentationBase {\n private readonly INSTRUMENTATION_NAME = \"PostgresInstrumentation\";\n private mode: TuskDriftMode;\n private tuskDrift: TuskDriftCore;\n\n constructor(config: PostgresInstrumentationConfig = {}) {\n super(\"postgres\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"postgres\",\n supportedVersions: [\"3.*\"],\n patch: (moduleExports: PostgresModuleExports) => this._patchPostgresModule(moduleExports),\n }),\n ];\n }\n\n private _patchPostgresModule(postgresModule: PostgresModuleExports): PostgresModuleExports {\n logger.debug(`[PostgresInstrumentation] Patching Postgres module in ${this.mode} mode`);\n\n if (postgresModule._tdPatched) {\n logger.debug(`[PostgresInstrumentation] Postgres module already patched, skipping`);\n return postgresModule;\n }\n\n // The postgres package exports a function that creates sql instances\n // We need to wrap the main function to intercept connection creation and sql queries\n if (typeof postgresModule === \"function\") {\n // For default export (the main function that creates sql instances)\n const originalFunction = postgresModule as any;\n const self = this;\n\n const wrappedFunction = function (...args: any[]) {\n return self._handlePostgresConnection(originalFunction, args);\n };\n\n // Copy properties from original function\n Object.setPrototypeOf(wrappedFunction, Object.getPrototypeOf(originalFunction));\n Object.defineProperty(wrappedFunction, \"name\", { value: originalFunction.name });\n\n postgresModule = wrappedFunction as any;\n }\n\n // Also patch the sql function if it exists as a named export\n if (postgresModule.sql && typeof postgresModule.sql === \"function\") {\n this._wrap(postgresModule, \"sql\", this._getSqlPatchFn());\n logger.debug(`[PostgresInstrumentation] Wrapped sql function`);\n }\n\n postgresModule._tdPatched = true;\n logger.debug(`[PostgresInstrumentation] Postgres module patching complete`);\n\n return postgresModule;\n }\n\n private _handlePostgresConnection(originalFunction: Function, args: any[]): any {\n // Extract connection parameters from args\n // postgres() signature: postgres(url, options?) or postgres(options)\n const connectionString = typeof args[0] === \"string\" ? args[0] : undefined;\n const options = typeof args[0] === \"string\" ? args[1] : args[0];\n\n const inputValue = {\n connectionString: connectionString\n ? this._sanitizeConnectionString(connectionString)\n : undefined,\n options: options ? this._sanitizeConnectionOptions(options) : undefined,\n };\n\n // Handle replay mode\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => {\n const sqlInstance = originalFunction(...args);\n return this._wrapSqlInstance(sqlInstance);\n },\n {\n name: \"postgres.connect\",\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return this._handleReplayConnect(spanInfo, originalFunction, args);\n },\n );\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => {\n const sqlInstance = originalFunction(...args);\n return this._wrapSqlInstance(sqlInstance);\n },\n recordModeHandler: ({ isPreAppStart }) => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => {\n const sqlInstance = originalFunction(...args);\n return this._wrapSqlInstance(sqlInstance);\n },\n {\n name: \"postgres.connect\",\n kind: SpanKind.CLIENT,\n submodule: \"connect\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return this._handleRecordConnect(spanInfo, originalFunction, args);\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n return originalFunction(...args);\n }\n }\n\n private _sanitizeConnectionString(connectionString: string): string {\n try {\n // Remove password from connection string for security\n const url = new URL(connectionString);\n if (url.password) {\n url.password = \"***\";\n }\n return url.toString();\n } catch {\n return \"[INVALID_URL]\";\n }\n }\n\n private _sanitizeConnectionOptions(options: any): any {\n if (!options || typeof options !== \"object\") {\n return options;\n }\n\n const sanitized = { ...options };\n\n // Remove sensitive fields\n if (sanitized.password) {\n sanitized.password = \"***\";\n }\n if (sanitized.ssl && typeof sanitized.ssl === \"object\") {\n sanitized.ssl = { ...sanitized.ssl };\n if (sanitized.ssl.key) sanitized.ssl.key = \"***\";\n if (sanitized.ssl.cert) sanitized.ssl.cert = \"***\";\n if (sanitized.ssl.ca) sanitized.ssl.ca = \"***\";\n }\n\n return sanitized;\n }\n\n private _handleRecordConnect(spanInfo: SpanInfo, originalFunction: Function, args: any[]): any {\n const sqlInstance = originalFunction(...args);\n const wrappedInstance = this._wrapSqlInstance(sqlInstance);\n\n try {\n logger.debug(\n `[PostgresInstrumentation] Postgres connection created successfully (${SpanUtils.getTraceInfo()})`,\n );\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { connected: true },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PostgresInstrumentation] error adding span attributes:`, error);\n }\n\n return wrappedInstance;\n }\n\n private _handleReplayConnect(spanInfo: SpanInfo, originalFunction: Function, args: any[]): any {\n logger.debug(`[PostgresInstrumentation] Replaying Postgres connection`);\n\n // In replay mode, we still create the sql instance but wrap it\n // The actual queries will be mocked when they're executed\n try {\n const sqlInstance = originalFunction(...args);\n const wrappedInstance = this._wrapSqlInstance(sqlInstance);\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { connected: true },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n\n return wrappedInstance;\n } catch (error: any) {\n logger.debug(\n `[PostgresInstrumentation] Postgres connection error in replay: ${error.message}`,\n );\n\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n\n throw error;\n }\n }\n\n private _wrapSqlInstance(sqlInstance: any): any {\n if (!sqlInstance || typeof sqlInstance !== \"function\") {\n return sqlInstance;\n }\n\n const self = this;\n const originalSql = sqlInstance;\n\n // Create wrapped sql function\n const wrappedSql = function (strings: TemplateStringsArray, ...values: any[]) {\n return self._handleSqlQuery(originalSql, strings, values);\n };\n\n // Copy all properties from the original sql instance\n Object.setPrototypeOf(wrappedSql, Object.getPrototypeOf(originalSql));\n for (const key in originalSql) {\n if (typeof originalSql[key] !== \"function\") {\n (wrappedSql as any)[key] = originalSql[key];\n } else {\n (wrappedSql as any)[key] = originalSql[key].bind(originalSql);\n }\n }\n\n // Patch the unsafe method specifically\n if (typeof originalSql.unsafe === \"function\") {\n (wrappedSql as any).unsafe = self._wrapUnsafeMethod(originalSql);\n logger.debug(`[PostgresInstrumentation] Wrapped unsafe method on sql instance`);\n }\n\n // Patch the begin method for transaction support\n if (typeof originalSql.begin === \"function\") {\n (wrappedSql as any).begin = self._wrapBeginMethod(originalSql);\n logger.debug(`[PostgresInstrumentation] Wrapped begin method on sql instance`);\n }\n\n return wrappedSql;\n }\n\n private _wrapUnsafeMethod(sqlInstance: any) {\n const self = this;\n const originalUnsafe = sqlInstance.unsafe;\n\n return function unsafe(\n query: string,\n parameters?: any[],\n queryOptions?: { prepare?: boolean },\n ): any {\n return self._handleUnsafeQuery(sqlInstance, originalUnsafe, query, parameters, queryOptions);\n };\n }\n\n private _wrapBeginMethod(sqlInstance: any) {\n const self = this;\n const originalBegin = sqlInstance.begin;\n\n return function begin(\n optionsOrCallback?: string | ((sql: any) => any),\n callback?: (sql: any) => any,\n ): any {\n // Handle both signatures: begin(callback) and begin(options, callback)\n const options = typeof optionsOrCallback === \"string\" ? optionsOrCallback : \"\";\n const transactionCallback =\n typeof optionsOrCallback === \"function\" ? optionsOrCallback : callback;\n\n return self._handleBeginTransaction(sqlInstance, originalBegin, options, transactionCallback);\n };\n }\n\n private _getSqlPatchFn() {\n const self = this;\n\n return (originalSql: Function) => {\n return function sql(strings: TemplateStringsArray, ...values: any[]) {\n return self._handleSqlQuery(originalSql, strings, values);\n };\n };\n }\n\n private _handleSqlQuery(\n originalSql: Function,\n strings: TemplateStringsArray,\n values: any[],\n ): any {\n // Reconstruct the query from template strings and values\n let query = \"\";\n for (let i = 0; i < strings.length; i++) {\n query += strings[i];\n if (i < values.length) {\n query += `$${i + 1}`; // PostgreSQL parameter placeholder\n }\n }\n\n const inputValue: PostgresClientInputValue = {\n query: query.trim(),\n parameters: values,\n };\n\n // Handle replay mode (only if app is ready)\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => originalSql.call(this, strings, ...values),\n {\n name: \"postgres.query\",\n kind: SpanKind.CLIENT,\n submodule: \"query\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return this.handleReplaySqlQuery({\n inputValue,\n spanInfo,\n submodule: \"query\",\n name: \"postgres.query\",\n });\n },\n );\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalSql.call(this, strings, ...values),\n recordModeHandler: ({ isPreAppStart }) => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => originalSql.call(this, strings, ...values),\n {\n name: \"postgres.query\",\n kind: SpanKind.CLIENT,\n submodule: \"query\",\n packageType: PackageType.PG,\n instrumentationName: this.INSTRUMENTATION_NAME,\n packageName: \"postgres\",\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return this._handleRecordQueryInSpan(spanInfo, originalSql, strings, values);\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalSql.call(this, strings, ...values);\n }\n }\n\n private _handleUnsafeQuery(\n sqlInstance: any,\n originalUnsafe: Function,\n query: string,\n parameters?: any[],\n queryOptions?: { prepare?: boolean },\n ): any {\n // Create a function that calls unsafe with the correct arguments\n const executeUnsafe = () => {\n // Only pass arguments that were actually provided\n if (queryOptions !== undefined) {\n return originalUnsafe.call(sqlInstance, query, parameters, queryOptions);\n } else if (parameters !== undefined) {\n return originalUnsafe.call(sqlInstance, query, parameters);\n } else {\n return originalUnsafe.call(sqlInstance, query);\n }\n };\n\n const inputValue: PostgresClientInputValue = {\n query: query.trim(),\n parameters: parameters || [],\n options: queryOptions,\n };\n\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n return this._createPendingQueryWrapper(() => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => executeUnsafe(),\n {\n name: \"postgres.unsafe\",\n kind: SpanKind.CLIENT,\n submodule: \"unsafe\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return this.handleReplayUnsafeQuery({\n inputValue,\n spanInfo,\n submodule: \"unsafe\",\n name: \"postgres.unsafe\",\n });\n },\n );\n });\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: executeUnsafe,\n recordModeHandler: ({ isPreAppStart }) => {\n // Execute postgres.js query first, then create span afterwards\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n executeUnsafe,\n {\n name: \"postgres.unsafe\",\n kind: SpanKind.CLIENT,\n submodule: \"unsafe\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return this._executeThenAddOutputAttributes(spanInfo, executeUnsafe);\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return executeUnsafe();\n }\n }\n\n private _handleBeginTransaction(\n sqlInstance: any,\n originalBegin: Function,\n options: string,\n transactionCallback?: (sql: any) => any,\n ): any {\n const inputValue = {\n query: \"BEGIN\",\n options: options ? { transactionOptions: options } : undefined,\n };\n\n const executeBegin = () => {\n if (options && transactionCallback) {\n return originalBegin.call(sqlInstance, options, transactionCallback);\n } else if (transactionCallback) {\n return originalBegin.call(sqlInstance, transactionCallback);\n } else {\n return originalBegin.call(sqlInstance, options || undefined);\n }\n };\n\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => executeBegin(),\n {\n name: \"postgres.begin\",\n kind: SpanKind.CLIENT,\n submodule: \"transaction\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return this._handleReplayBeginTransaction(spanInfo, options);\n },\n );\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: executeBegin,\n recordModeHandler: ({ isPreAppStart }) => {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n executeBegin,\n {\n name: \"postgres.begin\",\n kind: SpanKind.CLIENT,\n submodule: \"transaction\",\n packageType: PackageType.PG,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return this._handleRecordBeginTransaction(spanInfo, executeBegin);\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n return executeBegin();\n }\n }\n\n /**\n * Execute postgres.js unsafe query and create span afterwards.\n *\n * postgres.js has sophisticated internal session and connection management\n * that is extremely sensitive to async context changes. Unlike the regular 'pg' library,\n * postgres.js maintains internal state using promise identity and async context tracking.\n *\n * The issue: promise chain modification breaks postgres.js.\n * Calling .then()/.catch() creates new promise objects, breaking postgres.js's internal tracking\n *\n * Solution: We must execute the postgres.js query in its completely unmodified context:\n * - Return the original promise object unchanged\n * - Use promise.finally() to track completion without creating a new promise chain\n *\n * This preserves postgres.js's internal session management while still providing tracing.\n * The 'pg' library doesn't have this issue because it has simpler internal state management.\n */\n private _executeThenAddOutputAttributes(\n spanInfo: SpanInfo,\n executeUnsafe: () => Promise<any>,\n ): Promise<any> {\n const promise = executeUnsafe();\n\n // Use finally() which doesn't change the promise chain's behavior\n promise.finally(() => {\n // Create span after completion without affecting the original promise\n promise\n .then((result) => {\n logger.debug(`[PostgresInstrumentation] Postgres unsafe query completed successfully`);\n try {\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(\n `[PostgresInstrumentation] error processing unsafe query response:`,\n error,\n );\n }\n })\n .catch((error) => {\n logger.debug(`[PostgresInstrumentation] Postgres unsafe query error: ${error.message}`);\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[PostgresInstrumentation] error ending span:`, error);\n }\n });\n });\n\n return promise; // Return the original promise\n }\n\n private _handleRecordBeginTransaction(\n spanInfo: SpanInfo,\n executeBegin: () => Promise<any>,\n ): Promise<any> {\n const promise = executeBegin();\n\n // Use finally() which doesn't change the promise chain's behavior\n promise.finally(() => {\n // Create span after completion without affecting the original promise\n promise\n .then((result) => {\n logger.debug(\n `[PostgresInstrumentation] Postgres transaction completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { status: \"committed\", result },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PostgresInstrumentation] error processing transaction response:`, error);\n }\n })\n .catch((error) => {\n logger.debug(\n `[PostgresInstrumentation] Postgres transaction error (rolled back): ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n try {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { status: \"rolled_back\", error: error.message },\n });\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (spanError) {\n logger.error(`[PostgresInstrumentation] error ending span:`, spanError);\n }\n });\n });\n\n return promise; // Return the original promise\n }\n\n private async _handleReplayBeginTransaction(spanInfo: SpanInfo, options?: string): Promise<any> {\n logger.debug(`[PostgresInstrumentation] Replaying Postgres transaction`);\n\n // Find mock data for the transaction\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name: \"postgres.begin\",\n inputValue: {\n query: \"BEGIN\",\n options: options ? { transactionOptions: options } : undefined,\n },\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: \"transaction\",\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n if (!mockData) {\n logger.warn(`[PostgresInstrumentation] No mock data found for transaction BEGIN`);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n return;\n }\n\n logger.debug(\n `[PostgresInstrumentation] Found mock data for transaction: ${JSON.stringify(mockData)}`,\n );\n\n // Transaction results are stored directly without type conversion\n const transactionResult = mockData.result;\n\n // Check if the transaction was successful or rolled back\n const wasCommitted =\n transactionResult &&\n typeof transactionResult === \"object\" &&\n \"status\" in transactionResult &&\n transactionResult.status === \"committed\";\n\n if (wasCommitted) {\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { status: \"committed\", result: transactionResult.result },\n });\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n return transactionResult.result;\n } else {\n // Transaction was rolled back\n const errorMessage =\n transactionResult &&\n typeof transactionResult === \"object\" &&\n \"error\" in transactionResult &&\n transactionResult.error\n ? transactionResult.error\n : \"Transaction rolled back\";\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: { status: \"rolled_back\", error: errorMessage },\n });\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n throw new Error(errorMessage);\n }\n }\n\n private async _handleRecordQueryInSpan(\n spanInfo: SpanInfo,\n originalSql: Function,\n strings: TemplateStringsArray,\n values: any[],\n ): Promise<any> {\n try {\n const result = await originalSql.call(this, strings, ...values);\n\n try {\n logger.debug(\n `[PostgresInstrumentation] Postgres query completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[PostgresInstrumentation] error processing query response:`, error);\n }\n\n return result;\n } catch (error: any) {\n try {\n logger.debug(\n `[PostgresInstrumentation] Postgres query error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (spanError) {\n logger.error(`[PostgresInstrumentation] error ending span:`, spanError);\n }\n\n throw error;\n }\n }\n\n async handleReplaySqlQuery({\n inputValue,\n spanInfo,\n submodule,\n name,\n }: {\n inputValue: PostgresClientInputValue;\n spanInfo: SpanInfo;\n submodule: string;\n name: string;\n }): Promise<PostgresRow[] | undefined> {\n logger.debug(`[PostgresInstrumentation] Replaying Postgres sql query`);\n\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name,\n inputValue: inputValue,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: submodule,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n if (!mockData) {\n const queryText = inputValue.query || \"UNKNOWN_QUERY\";\n logger.warn(\n `[PostgresInstrumentation] No mock data found for Postgres sql query: ${queryText}`,\n );\n return;\n }\n\n logger.debug(\n `[PostgresInstrumentation] Found mock data for Postgres sql query: ${JSON.stringify(mockData)}`,\n );\n\n const processedResult = this.convertPostgresTypes(mockData.result);\n\n logger.debug(\n `[PostgresInstrumentation] Sql query processed result: ${JSON.stringify(processedResult)}`,\n );\n\n // Template string queries return just the rows array\n // Type guard: check if processedResult has a 'rows' property (PostgresResult type)\n const isResultObject =\n processedResult && typeof processedResult === \"object\" && \"rows\" in processedResult;\n const rows = isResultObject\n ? processedResult.rows || []\n : (processedResult as PostgresRow[]) || [];\n\n // postgres.js returns an array with metadata properties attached\n const resultArray = Object.assign(rows, {\n command: isResultObject ? processedResult.command : \"SELECT\",\n count: isResultObject ? processedResult.count : rows.length,\n });\n return resultArray;\n }\n\n async handleReplayUnsafeQuery({\n inputValue,\n spanInfo,\n submodule,\n name,\n }: {\n inputValue: PostgresClientInputValue;\n spanInfo: SpanInfo;\n submodule: string;\n name: string;\n }): Promise<PostgresConvertedResult | undefined> {\n logger.debug(`[PostgresInstrumentation] Replaying Postgres unsafe query`);\n\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name,\n inputValue: inputValue,\n packageName: \"postgres\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: submodule,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n if (!mockData) {\n const queryText = inputValue.query || \"UNKNOWN_QUERY\";\n logger.warn(\n `[PostgresInstrumentation] No mock data found for Postgres unsafe query: ${queryText}`,\n );\n return;\n }\n\n logger.debug(\n `[PostgresInstrumentation] Found mock data for Postgres unsafe query: ${JSON.stringify(mockData)}`,\n );\n\n const processedResult = this.convertPostgresTypes(mockData.result);\n\n logger.debug(\n `[PostgresInstrumentation] Unsafe query processed result: ${JSON.stringify(processedResult)}`,\n );\n\n return processedResult;\n }\n\n /**\n * Create a postgres.js-compatible PendingQuery wrapper.\n * This creates a thenable object with .values(), .raw(), etc. methods\n * that matches the postgres.js PendingQuery interface.\n *\n * NOTE: This wrapper is ONLY needed for unsafe() queries, not template string queries.\n * - unsafe() returns a PendingQuery with .values() method that Drizzle calls\n * - Template strings return a plain Promise/array and don't need the wrapper\n *\n * Also NOTE: unsafe expects a PendingQuery in return. This includes most common ones, but not all.\n * There is a possiblity we need to add the rest of the methods to the PendingQuery interface from \"postgres\" library.\n */\n private _createPendingQueryWrapper(\n queryPromiseFactory: () => Promise<PostgresConvertedResult>,\n ): Promise<any> {\n // Create the main promise\n const mainPromise = queryPromiseFactory();\n\n // Create a thenable wrapper that has the postgres.js methods\n const pendingQuery = Object.assign(mainPromise, {\n // .values() returns a promise that resolves to array of value arrays\n values: () => {\n return mainPromise.then((result: PostgresConvertedResult) => {\n if (!result) {\n return [];\n }\n\n // Type guard: check if result is a PostgresResult object with 'rows' property\n const isResultObject = typeof result === \"object\" && \"rows\" in result;\n const rows = isResultObject ? result.rows || [] : Array.isArray(result) ? result : [];\n\n // Convert rows to arrays if they're objects\n const valueArrays = rows.map((row: PostgresRow) => {\n if (Array.isArray(row)) {\n return row;\n }\n // If row is an object, convert to array of values\n return Object.values(row);\n });\n\n // Return array with metadata\n return Object.assign(valueArrays, {\n command: isResultObject ? result.command : \"SELECT\",\n count: isResultObject ? result.count : valueArrays.length,\n });\n });\n },\n });\n\n return pendingQuery;\n }\n\n /**\n * Convert PostgreSQL string values back to appropriate JavaScript types\n * based on common PostgreSQL data patterns.\n */\n private convertPostgresTypes(result: any): PostgresConvertedResult {\n if (!result) {\n return result;\n }\n\n // Handle postgres.js result format: { command, count, rows }\n if (result && typeof result === \"object\" && \"rows\" in result) {\n const convertedResult = { ...result };\n\n if (Array.isArray(result.rows)) {\n convertedResult.rows = result.rows.map((row: any) => {\n if (typeof row !== \"object\" || row === null) {\n return row;\n }\n\n const convertedRow = { ...row };\n\n Object.keys(row).forEach((fieldName) => {\n const value = row[fieldName];\n\n if (value === null || value === undefined) {\n return; // Keep null/undefined values as-is\n }\n\n // Try to detect and convert date/timestamp strings\n if (typeof value === \"string\") {\n // Check if it looks like an ISO date string\n const isoDateRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n if (isoDateRegex.test(value)) {\n const dateObj = new Date(value);\n if (!isNaN(dateObj.getTime())) {\n convertedRow[fieldName] = dateObj;\n }\n }\n }\n });\n\n return convertedRow;\n });\n }\n\n return convertedResult;\n }\n\n // Handle direct array format (fallback)\n if (Array.isArray(result)) {\n const convertedRows = result.map((row: any) => {\n if (typeof row !== \"object\" || row === null) {\n return row;\n }\n\n const convertedRow = { ...row };\n\n Object.keys(row).forEach((fieldName) => {\n const value = row[fieldName];\n\n if (value === null || value === undefined) {\n return; // Keep null/undefined values as-is\n }\n\n // Try to detect and convert date/timestamp strings\n if (typeof value === \"string\") {\n // Check if it looks like an ISO date string\n const isoDateRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n if (isoDateRegex.test(value)) {\n const dateObj = new Date(value);\n if (!isNaN(dateObj.getTime())) {\n convertedRow[fieldName] = dateObj;\n }\n }\n }\n });\n\n return convertedRow;\n });\n\n return convertedRows;\n }\n\n // Return as-is for other formats\n return result;\n }\n\n private _addOutputAttributesToSpan(spanInfo: SpanInfo, result?: any): void {\n if (!result) return;\n\n let outputValue: any;\n\n if (Array.isArray(result)) {\n // Direct array result\n outputValue = {\n count: result.length,\n rows: result,\n command: \"SELECT\", // Default assumption for array results\n };\n } else if (result && typeof result === \"object\" && \"count\" in result) {\n // postgres.js style result with count property\n outputValue = {\n count: result.count || 0,\n rows: result.rows || result,\n command: result.command || \"UNKNOWN\",\n };\n } else {\n // Fallback\n outputValue = {\n count: 1,\n rows: [result],\n command: \"UNKNOWN\",\n };\n }\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue,\n });\n }\n\n private _wrap(target: any, propertyName: string, wrapper: (original: any) => any): void {\n wrap(target, propertyName, wrapper);\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { TdInstrumentationConfig } from \"../../core/baseClasses/TdInstrumentationAbstract\";\nimport { SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { SPAN_KIND_CONTEXT_KEY, CALLING_LIBRARY_CONTEXT_KEY } from \"../../../core/types\";\nimport { SpanKind } from \"@opentelemetry/api\";\nimport { sendUnpatchedDependencyAlert } from \"../../../core/analytics\";\nimport { logger } from \"../../../core/utils/logger\";\nimport { SpanInfo } from \"../../../core/tracing/SpanUtils\";\n\nexport interface TcpInstrumentationConfig extends TdInstrumentationConfig {\n mode?: TuskDriftMode;\n}\n\n/**\n * TCP Instrumentation for Tusk Drift\n *\n * Behavior:\n * - REPLAY mode: Intercept TCP calls and check parent span\n * - If parent span is SERVER (inbound), log it out\n * - If parent span is not SERVER, log warning about unpached dependency\n * - Custom checks for HTTP related TCP calls + ProtobufCommunicator calls, no need to log those\n */\nexport class TcpInstrumentation extends TdInstrumentationBase {\n private mode: TuskDriftMode;\n private loggedSpans = new Set<string>(); // Track spans that have been logged\n\n constructor(config: TcpInstrumentationConfig = {}) {\n super(\"tcp\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"net\",\n supportedVersions: [\"*\"],\n patch: (moduleExports: any) => this._patchNetModule(moduleExports),\n }),\n ];\n }\n\n private _patchNetModule(netModule: any): any {\n logger.debug(`[TcpInstrumentation] Patching NET module in ${this.mode} mode`);\n\n if (netModule._tdPatched) {\n logger.debug(`[TcpInstrumentation] NET module already patched, skipping`);\n return netModule;\n }\n\n if (this.mode !== TuskDriftMode.REPLAY) {\n logger.debug(`[TcpInstrumentation] Not in replay mode, returning original net module`);\n return netModule;\n }\n\n const originalConnect = netModule.Socket.prototype.connect;\n const originalWrite = netModule.Socket.prototype.write;\n\n const self = this;\n\n // Patch net.Socket.prototype.connect\n // Socket.prototype has other methods we can patch (read, _write, end, etc)\n // But connect should be sufficient since we are only patching TCP to get insights into what modules we haven't patched\n netModule.Socket.prototype.connect = function (...args: any[]) {\n return self._handleTcpCall(\"connect\", originalConnect, args, this);\n };\n\n netModule.Socket.prototype.write = function (...args: any[]) {\n return self._handleTcpCall(\"write\", originalWrite, args, this);\n };\n\n netModule._tdPatched = true;\n return netModule;\n }\n\n private _logUnpatchedDependency(\n methodName: string,\n currentSpanInfo: SpanInfo,\n socketContext: any,\n ) {\n const spanKey = `${currentSpanInfo.spanId}-${methodName}`;\n\n if (!this.loggedSpans.has(spanKey)) {\n this.loggedSpans.add(spanKey);\n Error.stackTraceLimit = Infinity;\n\n logger.warn(\n `[TcpInstrumentation] TCP ${methodName} called from inbound request context, likely unpatched dependency`,\n {\n spanId: currentSpanInfo.spanId,\n traceId: currentSpanInfo.traceId,\n method: methodName,\n socketContext,\n },\n );\n\n logger.warn(`[TcpInstrumentation] Full stack trace:\\n${new Error().stack}`);\n\n Error.stackTraceLimit = 10;\n sendUnpatchedDependencyAlert({\n method: methodName,\n spanId: currentSpanInfo.spanId,\n traceId: currentSpanInfo.traceId,\n });\n\n // Clean up old span entries periodically to prevent memory leaks\n if (this.loggedSpans.size > 1000) {\n logger.debug(\n `[TcpInstrumentation] Cleaning up logged spans cache (${this.loggedSpans.size} entries)`,\n );\n this.loggedSpans.clear();\n }\n }\n }\n\n private _handleTcpCall(\n methodName: string,\n originalMethod: Function,\n args: any[],\n socketContext: any,\n ): any {\n // Don't want to log any HTTP response socket calls\n if (this._isHttpResponseSocket(socketContext)) {\n return originalMethod.apply(socketContext, args);\n }\n\n const currentSpanInfo = SpanUtils.getCurrentSpanInfo();\n\n if (!currentSpanInfo) {\n return originalMethod.apply(socketContext, args);\n }\n\n const callingLibrary = currentSpanInfo.context.getValue(CALLING_LIBRARY_CONTEXT_KEY);\n const spanKind = currentSpanInfo.context.getValue(SPAN_KIND_CONTEXT_KEY);\n\n // Don't want to log any TCP calls made to the CLI\n if (spanKind === SpanKind.SERVER && callingLibrary !== \"ProtobufCommunicator\") {\n // Log unpatched dependency without expensive stack trace\n this._logUnpatchedDependency(methodName, currentSpanInfo, socketContext);\n }\n\n // TODO: if we are confident in our ability to detect unpatched dependencies, instead of returning the original method when we detect a unpatched dependency\n // We can throw an error to prevent the server from making actual outbound calls in replay mode\n return originalMethod.apply(socketContext, args);\n }\n\n private _isHttpResponseSocket(socketContext: any): boolean {\n // Check if this socket is associated with HTTP response handling\n return socketContext && socketContext._httpMessage;\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanUtils, SpanInfo } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { wrap } from \"../../core/utils\";\nimport { findMockResponseAsync } from \"../../core/utils/mockResponseUtils\";\nimport { handleRecordMode, handleReplayMode } from \"../../core/utils/modeUtils\";\nimport {\n JsonwebtokenModuleExports,\n JsonwebtokenInstrumentationConfig,\n JwtVerifyInputValue,\n JwtSignInputValue,\n VerifyQueryConfig,\n SignQueryConfig,\n} from \"./types\";\nimport { createMockInputValue } from \"../../../core/utils\";\nimport { logger } from \"../../../core/utils/logger\";\n\nexport class JsonwebtokenInstrumentation extends TdInstrumentationBase {\n private readonly INSTRUMENTATION_NAME = \"JsonwebtokenInstrumentation\";\n private mode: TuskDriftMode;\n private tuskDrift: TuskDriftCore;\n private _JsonWebTokenError?: any;\n private _NotBeforeError?: any;\n private _TokenExpiredError?: any;\n\n constructor(config: JsonwebtokenInstrumentationConfig = {}) {\n super(\"jsonwebtoken\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"jsonwebtoken\",\n supportedVersions: [\"5.*\", \"6.*\", \"7.*\", \"8.*\", \"9.*\"],\n patch: (moduleExports: JsonwebtokenModuleExports) =>\n this._patchJsonwebtokenModule(moduleExports),\n }),\n ];\n }\n\n private _patchJsonwebtokenModule(\n jwtModule: JsonwebtokenModuleExports,\n ): JsonwebtokenModuleExports {\n if (jwtModule._tdPatched) {\n logger.debug(`[JsonwebtokenInstrumentation] jsonwebtoken module already patched, skipping`);\n return jwtModule;\n }\n\n // Store original functions and error classes\n this._JsonWebTokenError = jwtModule.JsonWebTokenError;\n this._NotBeforeError = jwtModule.NotBeforeError;\n this._TokenExpiredError = jwtModule.TokenExpiredError;\n\n // Wrap jwt.verify\n if (jwtModule.verify) {\n this._wrap(jwtModule, \"verify\", this._getVerifyPatchFn());\n logger.debug(`[JsonwebtokenInstrumentation] Wrapped jwt.verify`);\n }\n\n // Wrap jwt.sign\n if (jwtModule.sign) {\n this._wrap(jwtModule, \"sign\", this._getSignPatchFn());\n logger.debug(`[JsonwebtokenInstrumentation] Wrapped jwt.sign`);\n }\n\n jwtModule._tdPatched = true;\n logger.debug(`[JsonwebtokenInstrumentation] jsonwebtoken module patching complete`);\n\n return jwtModule;\n }\n\n private _getVerifyPatchFn() {\n const self = this;\n\n return (originalVerify: Function) => {\n return function verify(this: any, ...args: any[]) {\n // Parse verify arguments - jwt.verify supports multiple signatures\n let verifyConfig: VerifyQueryConfig | null = null;\n try {\n verifyConfig = self.parseVerifyArgs(args);\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error parsing verify args:`, error);\n }\n\n if (!verifyConfig || !verifyConfig.token) {\n // If we can't parse the arguments, let it pass through\n logger.debug(\n `[JsonwebtokenInstrumentation] Could not parse jwt.verify args, executing original`,\n args,\n );\n return originalVerify.apply(this, args);\n }\n\n const rawInputValue: JwtVerifyInputValue = {\n token: verifyConfig.token,\n secretOrPublicKey:\n typeof verifyConfig.secretOrPublicKey === \"function\"\n ? \"[Function:secretProvider]\"\n : verifyConfig.secretOrPublicKey,\n options: verifyConfig.options,\n };\n\n // Normalize the input value for consistent hashing\n let inputValue: JwtVerifyInputValue;\n\n try {\n inputValue = createMockInputValue(rawInputValue);\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error creating mock input value:`, error);\n return originalVerify.apply(this, args);\n }\n\n // Handle replay mode (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalVerify.apply(this, args),\n {\n name: \"jsonwebtoken.verify\",\n kind: SpanKind.CLIENT,\n submodule: \"verify\",\n packageName: \"jsonwebtoken\",\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self.handleReplayVerify(verifyConfig, inputValue, spanInfo);\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalVerify.apply(this, args),\n recordModeHandler: ({ isPreAppStart }) => {\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalVerify.apply(this, args),\n {\n name: \"jsonwebtoken.verify\",\n kind: SpanKind.CLIENT,\n submodule: \"verify\",\n packageName: \"jsonwebtoken\",\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return self._handleRecordVerifyInSpan(\n spanInfo,\n originalVerify,\n verifyConfig,\n args,\n this,\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalVerify.apply(this, args);\n }\n };\n };\n }\n\n private _getSignPatchFn() {\n const self = this;\n\n return (originalSign: Function) => {\n return function sign(this: any, ...args: any[]) {\n // Parse sign arguments - jwt.sign supports multiple signatures\n let signConfig: SignQueryConfig | null = null;\n try {\n signConfig = self.parseSignArgs(args);\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error parsing sign args:`, error);\n }\n\n if (!signConfig || !signConfig.payload) {\n // If we can't parse the arguments, let it pass through\n logger.warn(\n `[JsonwebtokenInstrumentation] Could not parse jwt.sign args, executing original`,\n args,\n );\n return originalSign.apply(this, args);\n }\n\n const inputValue: JwtSignInputValue = {\n payload: signConfig.payload,\n secretOrPrivateKey: signConfig.secretOrPrivateKey,\n options: signConfig.options,\n };\n\n // Handle replay mode (only if app is ready)\n if (self.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalSign.apply(this, args),\n {\n name: \"jsonwebtoken.sign\",\n kind: SpanKind.CLIENT,\n submodule: \"sign\",\n packageName: \"jsonwebtoken\",\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return self.handleReplaySign(signConfig, inputValue, spanInfo);\n },\n );\n },\n });\n } else if (self.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => originalSign.apply(this, args),\n recordModeHandler: ({ isPreAppStart }) => {\n // Record mode - create span and execute real sign\n return SpanUtils.createAndExecuteSpan(\n self.mode,\n () => originalSign.apply(this, args),\n {\n name: \"jsonwebtoken.sign\",\n kind: SpanKind.CLIENT,\n submodule: \"sign\",\n packageName: \"jsonwebtoken\",\n instrumentationName: self.INSTRUMENTATION_NAME,\n inputValue: inputValue,\n isPreAppStart,\n },\n (spanInfo) => {\n return self._handleRecordSignInSpan(\n spanInfo,\n originalSign,\n signConfig,\n args,\n this,\n );\n },\n );\n },\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return originalSign.apply(this, args);\n }\n };\n };\n }\n\n parseVerifyArgs(args: any[]): VerifyQueryConfig | null {\n if (args.length < 2) return null;\n\n const token = args[0];\n const secretOrPublicKey = args[1];\n\n if (typeof token !== \"string\") return null;\n\n const config: VerifyQueryConfig = {\n token,\n secretOrPublicKey,\n callback: typeof args[args.length - 1] === \"function\" ? args[args.length - 1] : undefined,\n };\n\n // Check for options parameter\n if (\n args.length >= 3 &&\n typeof args[2] === \"object\" &&\n typeof args[args.length - 1] !== \"function\"\n ) {\n config.options = args[2];\n } else if (args.length >= 4 && typeof args[2] === \"object\") {\n config.options = args[2];\n }\n\n return config;\n }\n\n parseSignArgs(args: any[]): SignQueryConfig | null {\n if (args.length < 2) return null;\n\n const payload = args[0];\n const secretOrPrivateKey = args[1];\n\n const config: SignQueryConfig = {\n payload,\n secretOrPrivateKey,\n callback: typeof args[args.length - 1] === \"function\" ? args[args.length - 1] : undefined,\n };\n\n // Check for options parameter\n if (\n args.length >= 3 &&\n typeof args[2] === \"object\" &&\n typeof args[args.length - 1] !== \"function\"\n ) {\n config.options = args[2];\n } else if (args.length >= 4 && typeof args[2] === \"object\") {\n config.options = args[2];\n }\n\n return config;\n }\n\n private _handleRecordVerifyInSpan(\n spanInfo: SpanInfo,\n originalVerify: Function,\n verifyConfig: VerifyQueryConfig,\n args: any[],\n context: any,\n ): any {\n const hasCallback = !!verifyConfig.callback;\n\n if (hasCallback) {\n // Callback-based verify\n const originalCallback = verifyConfig.callback!;\n const wrappedCallback = (error: Error | null, decoded?: any) => {\n if (error) {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT verify error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n this._addErrorOutputAttributesToSpan(spanInfo, error);\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n } else {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT verify completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n this._addOutputAttributesToSpan(spanInfo, decoded);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n }\n return originalCallback(error, decoded);\n };\n\n try {\n // Replace callback in args\n args[args.length - 1] = wrappedCallback;\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error replacing callback:`, error, args);\n }\n\n try {\n const retVal = originalVerify.apply(context, args);\n return retVal;\n } catch (error: any) {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT verify sync error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n this._addErrorOutputAttributesToSpan(spanInfo, error);\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n throw error;\n }\n } else {\n // Synchronous verify\n try {\n const result = originalVerify.apply(context, args);\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT verify completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n\n return result;\n } catch (error: any) {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT verify error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n this._addErrorOutputAttributesToSpan(spanInfo, error);\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n throw error;\n }\n }\n }\n\n private _handleRecordSignInSpan(\n spanInfo: SpanInfo,\n originalSign: Function,\n signConfig: SignQueryConfig,\n args: any[],\n context: any,\n ): any {\n const hasCallback = !!signConfig.callback;\n\n if (hasCallback) {\n // Callback-based sign\n const originalCallback = signConfig.callback!;\n const wrappedCallback = (error: Error | null, token?: string) => {\n if (error) {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT sign error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n this._addErrorOutputAttributesToSpan(spanInfo, error);\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n } else {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT sign completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n this._addOutputAttributesToSpan(spanInfo, token);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n }\n return originalCallback(error, token);\n };\n\n try {\n // Replace callback in args\n args[args.length - 1] = wrappedCallback;\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error replacing callback:`, error, args);\n }\n\n const retVal = originalSign.apply(context, args);\n return retVal;\n } else {\n // Synchronous sign\n try {\n const result = originalSign.apply(context, args);\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT sign completed successfully (${SpanUtils.getTraceInfo()})`,\n );\n this._addOutputAttributesToSpan(spanInfo, result);\n SpanUtils.endSpan(spanInfo.span, { code: SpanStatusCode.OK });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n return result;\n } catch (error: any) {\n try {\n logger.debug(\n `[JsonwebtokenInstrumentation] JWT sign error: ${error.message} (${SpanUtils.getTraceInfo()})`,\n );\n this._addErrorOutputAttributesToSpan(spanInfo, error);\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`[JsonwebtokenInstrumentation] error ending span:`, error);\n }\n throw error;\n }\n }\n }\n\n async handleReplayVerify(\n verifyConfig: VerifyQueryConfig,\n inputValue: JwtVerifyInputValue,\n spanInfo: SpanInfo,\n ): Promise<any> {\n logger.debug(`[JsonwebtokenInstrumentation] Replaying JWT verify`);\n\n // Look for matching recorded response\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name: inputValue.token,\n packageName: \"jsonwebtoken\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: \"verify\",\n inputValue: inputValue,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n const hasCallback = !!verifyConfig.callback;\n\n if (!mockData) {\n logger.warn(\n `[JsonwebtokenInstrumentation] No mock data found for JWT verify: ${verifyConfig.token}`,\n );\n const error = new Error(\"No mock data found\");\n\n if (hasCallback) {\n process.nextTick(() => verifyConfig.callback!(error));\n return;\n } else {\n throw error;\n }\n }\n\n // Handle errors from the mock data (errors are embedded in the result)\n if (mockData.result && mockData.result.error) {\n let error = mockData.result.error;\n\n // Recreate specific JWT error types\n if (this._TokenExpiredError && mockData.result.error.name === \"TokenExpiredError\") {\n error = new this._TokenExpiredError(\n mockData.result.error.message,\n mockData.result.error.expiredAt,\n );\n } else if (this._JsonWebTokenError && mockData.result.error.name === \"JsonWebTokenError\") {\n error = new this._JsonWebTokenError(mockData.result.error.message);\n } else if (this._NotBeforeError && mockData.result.error.name === \"NotBeforeError\") {\n error = new this._NotBeforeError(mockData.result.error.message, mockData.result.error.date);\n } else {\n // Create a generic error if we don't have the specific error class\n error = new Error(mockData.result.error.message);\n error.name = mockData.result.error.name;\n }\n\n if (hasCallback) {\n process.nextTick(() => verifyConfig.callback!(error));\n return;\n } else {\n throw error;\n }\n }\n\n // Handle successful verification\n const result = mockData.result.token !== undefined ? mockData.result.token : mockData.result;\n if (hasCallback) {\n process.nextTick(() => {\n verifyConfig.callback!(null, result);\n });\n return;\n } else {\n return result;\n }\n }\n\n async handleReplaySign(\n signConfig: SignQueryConfig,\n inputValue: JwtSignInputValue,\n spanInfo: SpanInfo,\n ): Promise<any> {\n logger.debug(`[JsonwebtokenInstrumentation] Replaying JWT sign`);\n\n // Look for matching recorded response\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo?.traceId,\n spanId: spanInfo?.spanId,\n name: JSON.stringify(inputValue.payload),\n packageName: \"jsonwebtoken\",\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: \"sign\",\n inputValue: inputValue,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n });\n\n const hasCallback = !!signConfig.callback;\n\n if (!mockData) {\n logger.warn(`[JsonwebtokenInstrumentation] No mock data found for JWT sign`);\n const error = new Error(\"No mock data found\");\n\n if (hasCallback) {\n process.nextTick(() => signConfig.callback!(error));\n return;\n } else {\n throw error;\n }\n }\n\n // Handle errors from the mock data (errors are embedded in the result)\n if (mockData.result && mockData.result.error) {\n let error = mockData.result.error;\n\n // Recreate specific JWT error types\n if (this._JsonWebTokenError && mockData.result.error.name === \"JsonWebTokenError\") {\n error = new this._JsonWebTokenError(mockData.result.error.message);\n } else {\n // Create a generic error if we don't have the specific error class\n error = new Error(mockData.result.error.message);\n error.name = mockData.result.error.name;\n }\n\n if (hasCallback) {\n process.nextTick(() => signConfig.callback!(error));\n return;\n } else {\n throw error;\n }\n }\n\n // Handle successful signing\n const result = mockData.result.token !== undefined ? mockData.result.token : mockData.result;\n if (hasCallback) {\n process.nextTick(() => {\n signConfig.callback!(null, result);\n });\n return;\n } else {\n return result;\n }\n }\n\n private _addOutputAttributesToSpan(spanInfo: SpanInfo, result?: any): void {\n if (!result) return;\n\n const outputValue = typeof result === \"string\" ? { token: result } : result;\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue,\n });\n }\n\n private _addErrorOutputAttributesToSpan(spanInfo: SpanInfo, error: Error): void {\n const errorOutput = {\n error: {\n name: error.name,\n message: error.message,\n // Include any additional properties that specific JWT errors might have\n ...((error as any).expiredAt && { expiredAt: (error as any).expiredAt }),\n ...((error as any).date && { date: (error as any).date }),\n },\n };\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue: errorOutput,\n });\n }\n\n private _wrap(target: any, propertyName: string, wrapper: (original: any) => any): void {\n wrap(target, propertyName, wrapper);\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { JwksRsaModuleExports, JwksRsaInstrumentationConfig } from \"./types\";\nimport { logger } from \"../../../core/utils/logger\";\n\n/**\n * JwksRsa is just patched to override rate limits enforced on the client side in replay mode\n *\n * No spans are being recorded or replayed for jwks-rsa.\n */\nexport class JwksRsaInstrumentation extends TdInstrumentationBase {\n private tuskDrift: TuskDriftCore;\n\n constructor(config: JwksRsaInstrumentationConfig = {}) {\n super(\"jwks-rsa\", config);\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n return [\n new TdInstrumentationNodeModule({\n name: \"jwks-rsa\",\n supportedVersions: [\"1.*\", \"2.*\", \"3.*\"],\n patch: (moduleExports: JwksRsaModuleExports) => this._patchJwksRsaModule(moduleExports),\n }),\n ];\n }\n\n private _patchJwksRsaModule(jwksModule: any): any {\n logger.debug(\n `[JwksRsaInstrumentation] Patching jwks-rsa module, current mode: ${this.tuskDrift.getMode()}`,\n );\n\n if (jwksModule._tdPatched) {\n logger.debug(`[JwksRsaInstrumentation] jwks-rsa module already patched, skipping`);\n return jwksModule;\n }\n\n const self = this;\n\n if (jwksModule.expressJwtSecret) {\n const originalExpressJwtSecret = jwksModule.expressJwtSecret;\n jwksModule.expressJwtSecret = function (options: any) {\n logger.debug(`[JwksRsaInstrumentation] expressJwtSecret called with options:`, options);\n let modifiedOptions = { ...options };\n // Only disable rate limiting in replay mode\n if (self.tuskDrift.getMode() === TuskDriftMode.REPLAY) {\n logger.debug(\n `[JwksRsaInstrumentation] REPLAY MODE - Disabling rate limiting for expressJwtSecret`,\n );\n modifiedOptions.rateLimit = false;\n delete modifiedOptions.jwksRequestsPerMinute;\n logger.debug(`[JwksRsaInstrumentation] Modified options:`, modifiedOptions);\n }\n return originalExpressJwtSecret(modifiedOptions);\n };\n logger.debug(`[JwksRsaInstrumentation] Patched expressJwtSecret method`);\n }\n\n jwksModule._tdPatched = true;\n\n logger.debug(`[JwksRsaInstrumentation] jwks-rsa module patching complete`);\n return jwksModule;\n }\n}\n","import { TdInstrumentationBase } from \"../../core/baseClasses/TdInstrumentationBase\";\nimport { TdInstrumentationNodeModule } from \"../../core/baseClasses/TdInstrumentationNodeModule\";\nimport { SpanInfo, SpanUtils } from \"../../../core/tracing/SpanUtils\";\nimport { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { TuskDriftCore, TuskDriftMode } from \"../../../core/TuskDrift\";\nimport { getDecodedType, httpBodyEncoder } from \"../http/utils\";\nimport { isTuskDriftIngestionUrl, TUSK_SKIP_HEADER } from \"../../core/utils\";\nimport { findMockResponseAsync } from \"../../core/utils/mockResponseUtils\";\nimport { handleReplayMode, handleRecordMode } from \"../../core/utils/modeUtils\";\nimport { FetchInputValue, FetchOutputValue, FetchInstrumentationConfig } from \"./types\";\nimport { PackageType } from \"@use-tusk/drift-schemas/core/span\";\nimport { EncodingType } from \"../../../core/tracing/JsonSchemaHelper\";\nimport { logger } from \"../../../core/utils/logger\";\nimport { BodyInit } from \"undici-types/fetch\";\n\n/**\n * Fetch API instrumentation for capturing requests made via fetch()\n * This covers libraries like @octokit/rest, axios (when using fetch adapter), etc.\n */\nexport class FetchInstrumentation extends TdInstrumentationBase {\n private readonly INSTRUMENTATION_NAME = \"FetchInstrumentation\";\n private mode: TuskDriftMode;\n private tuskDrift: TuskDriftCore;\n private originalFetch?: typeof globalThis.fetch;\n\n constructor(config: FetchInstrumentationConfig = {}) {\n super(\"fetch\", config);\n this.mode = config.mode || TuskDriftMode.DISABLED;\n this.tuskDrift = TuskDriftCore.getInstance();\n }\n\n init(): TdInstrumentationNodeModule[] {\n // Fetch is a global, not a module, so we patch it directly\n // Fetch doesn't need to be reuired'd like other node modules hence we just directly patch it\n this.patchGlobalFetch();\n return [];\n }\n\n private patchGlobalFetch(): void {\n // Unlike other instrumentations that patch modules when they're required (lazy patching),\n // fetch instrumentation patches the global fetch function immediately during init() since\n // fetch is a global API, not a module. This means we need to explicitly check if the\n // instrumentation is enabled before patching, otherwise we'd always patch globalThis.fetch\n // even when the user has disabled fetch instrumentation.\n if (this.mode === TuskDriftMode.DISABLED || !this._config.enabled) {\n return;\n }\n\n if (typeof globalThis.fetch !== \"function\") {\n logger.debug(\"fetch not available in this environment\");\n return;\n }\n\n this.originalFetch = globalThis.fetch;\n const self = this;\n\n globalThis.fetch = function (\n input: string | URL | Request,\n init?: RequestInit,\n ): Promise<Response> {\n return self._handleFetchRequest(input, init);\n } as typeof globalThis.fetch;\n\n logger.debug(\"Global fetch patching complete\");\n }\n\n private async _handleFetchRequest(\n input: string | URL | Request,\n init?: RequestInit,\n ): Promise<Response> {\n // Parse request details\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const method = init?.method || \"GET\";\n const headers = init?.headers || {};\n\n let normalizedHeaders = {};\n let encodedBody = init?.body;\n try {\n normalizedHeaders = this._normalizeHeaders(headers);\n encodedBody = init?.body ? await this._encodeRequestBody(init?.body) : init?.body;\n } catch (error) {\n logger.error(`FetchInstrumentation error normalizing headers:`, error);\n }\n\n // Ignore SDK's own drift export calls\n const shouldSkip =\n (normalizedHeaders as any)[TUSK_SKIP_HEADER] === \"true\" || isTuskDriftIngestionUrl(url);\n\n if (shouldSkip) {\n return this.originalFetch!(input, init);\n }\n\n const inputValue: FetchInputValue = {\n url,\n method,\n headers: normalizedHeaders,\n body: encodedBody,\n };\n\n // Handle replay mode (only if app is ready)\n if (this.mode === TuskDriftMode.REPLAY) {\n return handleReplayMode({\n replayModeHandler: () => {\n // Create span in replay mode\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => this.originalFetch!(input, init),\n {\n name: url,\n kind: SpanKind.CLIENT,\n packageName: \"fetch\",\n packageType: PackageType.HTTP,\n instrumentationName: this.INSTRUMENTATION_NAME,\n submodule: inputValue.method,\n inputValue,\n isPreAppStart: false,\n },\n (spanInfo) => {\n return this._handleReplayFetch(inputValue, spanInfo);\n },\n );\n },\n });\n } else if (this.mode === TuskDriftMode.RECORD) {\n return handleRecordMode({\n originalFunctionCall: () => this.originalFetch!(input, init),\n recordModeHandler: ({ isPreAppStart }) =>\n this._handleRecordFetch(input, inputValue, isPreAppStart, init),\n spanKind: SpanKind.CLIENT,\n });\n } else {\n // Should never happen since we're only patching record and replay modes\n return this.originalFetch!(input, init);\n }\n }\n\n private _handleRecordFetch(\n input: string | URL | Request,\n inputValue: FetchInputValue,\n isPreAppStart: boolean,\n init?: RequestInit,\n ): Promise<Response> {\n return SpanUtils.createAndExecuteSpan(\n this.mode,\n () => this.originalFetch!(input, init),\n {\n name: inputValue.url,\n kind: SpanKind.CLIENT,\n packageName: \"fetch\",\n packageType: PackageType.HTTP,\n instrumentationName: this.INSTRUMENTATION_NAME,\n submodule: inputValue.method,\n inputValue,\n inputSchemaMerges: {\n ...(inputValue.body && {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(inputValue.headers[\"content-type\"] || \"\"),\n },\n }),\n ...(inputValue.headers && {\n headers: {\n matchImportance: 0,\n },\n }),\n },\n isPreAppStart,\n },\n (spanInfo) => {\n return this.originalFetch!(input, init)\n .then(async (response) => {\n // Clone response to read body without consuming it\n try {\n const responseClone = response.clone();\n const encodedBody = await this._encodeResponseBody(responseClone);\n\n const outputValue = {\n status: response.status,\n statusText: response.statusText,\n headers: this._responseHeadersToObject(response.headers),\n body: encodedBody,\n bodySize: encodedBody?.length || 0,\n } as FetchOutputValue;\n\n SpanUtils.addSpanAttributes(spanInfo.span, {\n outputValue,\n outputSchemaMerges: {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(outputValue.headers[\"content-type\"] || \"\"),\n },\n headers: {\n matchImportance: 0,\n },\n },\n });\n\n const status =\n response.status >= 400\n ? { code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` }\n : { code: SpanStatusCode.OK };\n\n SpanUtils.endSpan(spanInfo.span, status);\n } catch (error) {\n logger.error(`FetchInstrumentation error processing response body:`, error);\n }\n return response;\n })\n .catch((error) => {\n try {\n SpanUtils.endSpan(spanInfo.span, {\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } catch (error) {\n logger.error(`FetchInstrumentation error ending span:`, error);\n }\n throw error;\n });\n },\n );\n }\n\n private async _handleReplayFetch(\n inputValue: FetchInputValue,\n spanInfo: SpanInfo,\n ): Promise<Response> {\n const mockData = await findMockResponseAsync({\n mockRequestData: {\n traceId: spanInfo.traceId,\n spanId: spanInfo.spanId,\n name: inputValue.url,\n packageName: \"fetch\",\n packageType: PackageType.HTTP,\n instrumentationName: this.INSTRUMENTATION_NAME,\n submoduleName: inputValue.method,\n inputValue,\n kind: SpanKind.CLIENT,\n },\n tuskDrift: this.tuskDrift,\n inputValueSchemaMerges: {\n ...(inputValue.body && {\n body: {\n encoding: EncodingType.BASE64,\n decodedType: getDecodedType(inputValue.headers[\"content-type\"] || \"\"),\n },\n }),\n ...(inputValue.headers && {\n headers: {\n matchImportance: 0,\n },\n }),\n },\n });\n\n if (!mockData) {\n throw new Error(\n `No matching mock found for fetch request with input value: ${JSON.stringify(inputValue)}`,\n );\n }\n\n const { result } = mockData;\n const responseBody = this._constructFetchResponseBody(result);\n\n const mockResponse = new Response(responseBody, {\n status: result.status,\n statusText: result.statusText,\n headers: new Headers(result.headers),\n });\n\n return Promise.resolve(mockResponse);\n }\n\n private _normalizeHeaders(headers: any): Record<string, string> {\n if (headers instanceof Headers) {\n const result: Record<string, string> = {};\n headers.forEach((value, key) => {\n result[key.toLowerCase()] = value;\n });\n return result;\n } else if (Array.isArray(headers)) {\n const result: Record<string, string> = {};\n headers.forEach(([key, value]) => {\n result[key.toLowerCase()] = value;\n });\n return result;\n } else if (typeof headers === \"object\" && headers !== null) {\n const result: Record<string, string> = {};\n Object.entries(headers).forEach(([key, value]) => {\n if (typeof value === \"string\") {\n result[key.toLowerCase()] = value;\n }\n });\n return result;\n }\n return {};\n }\n\n private async _encodeRequestBody(body: BodyInit): Promise<string | undefined> {\n try {\n let bodyBuffer: Buffer;\n\n if (body === null) {\n return undefined;\n }\n\n if (typeof body === \"string\") {\n // String body - convert to buffer\n bodyBuffer = Buffer.from(body, \"utf8\");\n } else if (body instanceof ArrayBuffer) {\n // ArrayBuffer - convert directly\n bodyBuffer = Buffer.from(body);\n } else if (\n body instanceof Uint8Array ||\n body instanceof Int8Array ||\n body instanceof Uint16Array ||\n body instanceof Int16Array ||\n body instanceof Uint32Array ||\n body instanceof Int32Array ||\n body instanceof Float32Array ||\n body instanceof Float64Array ||\n body instanceof DataView\n ) {\n // TypedArray or DataView - convert to buffer\n bodyBuffer = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n } else if (body instanceof URLSearchParams) {\n // URLSearchParams - convert to string first\n bodyBuffer = Buffer.from(body.toString(), \"utf8\");\n } else if (body instanceof FormData) {\n // FormData - this is tricky, we need to serialize it\n // For now, let's skip encoding FormData as it's complex\n logger.warn(\"FormData encoding not yet supported, skipping body encoding\");\n return undefined;\n } else if (body instanceof Blob) {\n // Blob - read as array buffer\n const arrayBuffer = await body.arrayBuffer();\n bodyBuffer = Buffer.from(arrayBuffer);\n } else if (body && typeof body === \"object\" && Symbol.asyncIterator in body) {\n // AsyncIterable<Uint8Array>\n const chunks: Uint8Array[] = [];\n for await (const chunk of body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n bodyBuffer = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n } else if (body && typeof body === \"object\" && Symbol.iterator in body) {\n // Iterable<Uint8Array>\n const chunks: Uint8Array[] = [];\n for (const chunk of body as Iterable<Uint8Array>) {\n chunks.push(chunk);\n }\n bodyBuffer = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n } else {\n // Unknown type\n logger.warn(\"Unknown body type, cannot encode:\", typeof body, body);\n return undefined;\n }\n\n return await httpBodyEncoder({ bodyBuffer });\n } catch (error) {\n logger.warn(\"Failed to encode request body:\", error);\n return undefined;\n }\n }\n\n /**\n * Encode response body using existing httpBodyEncoder\n */\n private async _encodeResponseBody(response: Response): Promise<string | undefined> {\n try {\n if (!response.body) {\n return undefined;\n }\n const arrayBuffer = await response.arrayBuffer();\n const bodyBuffer = Buffer.from(arrayBuffer);\n\n return await httpBodyEncoder({ bodyBuffer });\n } catch (error) {\n return undefined;\n }\n }\n\n /**\n * Construct response body for replay mode\n */\n private _constructFetchResponseBody(result: FetchOutputValue): Buffer<ArrayBuffer> | null {\n if (result.body) {\n return Buffer.from(result.body, \"base64\");\n }\n return null;\n }\n\n private _responseHeadersToObject(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n headers.forEach((value, key) => {\n result[key.toLowerCase()] = value;\n });\n return result;\n }\n}\n","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key SUPPRESS_TRACING');\nfunction suppressTracing(context) {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\nexports.suppressTracing = suppressTracing;\nfunction unsuppressTracing(context) {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\nexports.unsuppressTracing = unsuppressTracing;\nfunction isTracingSuppressed(context) {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\nexports.isTracingSuppressed = isTracingSuppressed;\n//# sourceMappingURL=suppress-tracing.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = void 0;\nexports.BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexports.BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexports.BAGGAGE_ITEMS_SEPARATOR = ',';\n// Name of the http header used to propagate the baggage\nexports.BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexports.BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n//# sourceMappingURL=constants.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parseKeyPairsIntoRecord = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = void 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 */\nconst api_1 = require(\"@opentelemetry/api\");\nconst constants_1 = require(\"./constants\");\nfunction serializeKeyPairs(keyPairs) {\n return keyPairs.reduce((hValue, current) => {\n const value = `${hValue}${hValue !== '' ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ''}${current}`;\n return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\nexports.serializeKeyPairs = serializeKeyPairs;\nfunction getKeyPairs(baggage) {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\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 += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n return entry;\n });\n}\nexports.getKeyPairs = getKeyPairs;\nfunction parsePairKeyValue(entry) {\n const valueProps = entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0)\n return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart)\n return;\n const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0)\n return;\n const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim());\n const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim());\n let metadata;\n if (valueProps.length > 0) {\n metadata = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR));\n }\n return { key, value, metadata };\n}\nexports.parsePairKeyValue = parsePairKeyValue;\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 */\nfunction parseKeyPairsIntoRecord(value) {\n if (typeof value !== 'string' || value.length === 0)\n return {};\n return value\n .split(constants_1.BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair.key] = keyPair.value;\n return headers;\n }, {});\n}\nexports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord;\n//# sourceMappingURL=utils.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.W3CBaggagePropagator = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst suppress_tracing_1 = require(\"../../trace/suppress-tracing\");\nconst constants_1 = require(\"../constants\");\nconst utils_1 = require(\"../utils\");\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nclass W3CBaggagePropagator {\n inject(context, carrier, setter) {\n const baggage = api_1.propagation.getBaggage(context);\n if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context))\n return;\n const keyPairs = (0, utils_1.getKeyPairs)(baggage)\n .filter((pair) => {\n return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue);\n }\n }\n extract(context, carrier, getter) {\n const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER);\n const baggageString = Array.isArray(headerValue)\n ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString)\n return context;\n const baggage = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = (0, utils_1.parsePairKeyValue)(entry);\n if (keyPair) {\n const 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 api_1.propagation.setBaggage(context, api_1.propagation.createBaggage(baggage));\n }\n fields() {\n return [constants_1.BAGGAGE_HEADER];\n }\n}\nexports.W3CBaggagePropagator = W3CBaggagePropagator;\n//# sourceMappingURL=W3CBaggagePropagator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AnchoredClock = void 0;\n/**\n * A utility for returning wall times anchored to a given point in time. Wall time measurements will\n * not be taken from the system, but instead are computed by adding a monotonic clock time\n * to the anchor point.\n *\n * This is needed because the system time can change and result in unexpected situations like\n * spans ending before they are started. Creating an anchored clock for each local root span\n * ensures that span timings and durations are accurate while preventing span times from drifting\n * too far from the system clock.\n *\n * Only creating an anchored clock once per local trace ensures span times are correct relative\n * to each other. For example, a child span will never have a start time before its parent even\n * if the system clock is corrected during the local trace.\n *\n * Heavily inspired by the OTel Java anchored clock\n * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java\n */\nclass AnchoredClock {\n /**\n * Create a new AnchoredClock anchored to the current time returned by systemClock.\n *\n * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date\n * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance\n */\n constructor(systemClock, monotonicClock) {\n this._monotonicClock = monotonicClock;\n this._epochMillis = systemClock.now();\n this._performanceMillis = monotonicClock.now();\n }\n /**\n * Returns the current time by adding the number of milliseconds since the\n * AnchoredClock was created to the creation epoch time\n */\n now() {\n const delta = this._monotonicClock.now() - this._performanceMillis;\n return this._epochMillis + delta;\n }\n}\nexports.AnchoredClock = AnchoredClock;\n//# sourceMappingURL=anchored-clock.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nfunction sanitizeAttributes(attributes) {\n const out = {};\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n for (const [key, val] of Object.entries(attributes)) {\n if (!isAttributeKey(key)) {\n api_1.diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n if (!isAttributeValue(val)) {\n api_1.diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n }\n else {\n out[key] = val;\n }\n }\n return out;\n}\nexports.sanitizeAttributes = sanitizeAttributes;\nfunction isAttributeKey(key) {\n return typeof key === 'string' && key.length > 0;\n}\nexports.isAttributeKey = isAttributeKey;\nfunction isAttributeValue(val) {\n if (val == null) {\n return true;\n }\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n return isValidPrimitiveAttributeValue(val);\n}\nexports.isAttributeValue = isAttributeValue;\nfunction isHomogeneousAttributeValueArray(arr) {\n let type;\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null)\n continue;\n if (!type) {\n if (isValidPrimitiveAttributeValue(element)) {\n type = typeof element;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n if (typeof element === type) {\n continue;\n }\n return false;\n }\n return true;\n}\nfunction isValidPrimitiveAttributeValue(val) {\n switch (typeof val) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n return false;\n}\n//# sourceMappingURL=attributes.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loggingErrorHandler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nfunction loggingErrorHandler() {\n return (ex) => {\n api_1.diag.error(stringifyException(ex));\n };\n}\nexports.loggingErrorHandler = loggingErrorHandler;\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex) {\n if (typeof ex === 'string') {\n return ex;\n }\n else {\n return JSON.stringify(flattenException(ex));\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) {\n const result = {};\n let current = ex;\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName])\n return;\n const value = current[propertyName];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n return result;\n}\n//# sourceMappingURL=logging-error-handler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.globalErrorHandler = exports.setGlobalErrorHandler = void 0;\nconst logging_error_handler_1 = require(\"./logging-error-handler\");\n/** The global error handler delegate */\nlet delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)();\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nfunction setGlobalErrorHandler(handler) {\n delegateHandler = handler;\n}\nexports.setGlobalErrorHandler = setGlobalErrorHandler;\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nfunction globalErrorHandler(ex) {\n try {\n delegateHandler(ex);\n }\n catch (_a) { } // eslint-disable-line no-empty\n}\nexports.globalErrorHandler = globalErrorHandler;\n//# sourceMappingURL=global-error-handler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TracesSamplerValues = void 0;\nvar TracesSamplerValues;\n(function (TracesSamplerValues) {\n TracesSamplerValues[\"AlwaysOff\"] = \"always_off\";\n TracesSamplerValues[\"AlwaysOn\"] = \"always_on\";\n TracesSamplerValues[\"ParentBasedAlwaysOff\"] = \"parentbased_always_off\";\n TracesSamplerValues[\"ParentBasedAlwaysOn\"] = \"parentbased_always_on\";\n TracesSamplerValues[\"ParentBasedTraceIdRatio\"] = \"parentbased_traceidratio\";\n TracesSamplerValues[\"TraceIdRatio\"] = \"traceidratio\";\n})(TracesSamplerValues = exports.TracesSamplerValues || (exports.TracesSamplerValues = {}));\n//# sourceMappingURL=sampling.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports._globalThis = void 0;\n// Updates to this file should also be replicated to @opentelemetry/api too.\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/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexports._globalThis = typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : {};\n//# sourceMappingURL=globalThis.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getEnvWithoutDefaults = exports.parseEnvironment = exports.DEFAULT_ENVIRONMENT = exports.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = exports.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst sampling_1 = require(\"./sampling\");\nconst globalThis_1 = require(\"../platform/browser/globalThis\");\nconst DEFAULT_LIST_SEPARATOR = ',';\n/**\n * Environment interface to define all names\n */\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'];\nfunction isEnvVarABoolean(key) {\n return (ENVIRONMENT_BOOLEAN_KEYS.indexOf(key) > -1);\n}\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n];\nfunction isEnvVarANumber(key) {\n return (ENVIRONMENT_NUMBERS_KEYS.indexOf(key) > -1);\n}\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n];\nfunction isEnvVarAList(key) {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key) > -1;\n}\nexports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\nexports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexports.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexports.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n/**\n * Default environment variables\n */\nexports.DEFAULT_ENVIRONMENT = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: api_1.DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT: exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT: exports.DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT: exports.DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: sampling_1.TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(key, environment, values) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(name, environment, values, min = -Infinity, max = Infinity) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name]);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n }\n else if (value > max) {\n environment[name] = max;\n }\n else {\n environment[name] = value;\n }\n }\n }\n}\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(name, output, input, separator = DEFAULT_LIST_SEPARATOR) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n// The support string -> DiagLogLevel mappings\nconst logLevelMap = {\n ALL: api_1.DiagLogLevel.ALL,\n VERBOSE: api_1.DiagLogLevel.VERBOSE,\n DEBUG: api_1.DiagLogLevel.DEBUG,\n INFO: api_1.DiagLogLevel.INFO,\n WARN: api_1.DiagLogLevel.WARN,\n ERROR: api_1.DiagLogLevel.ERROR,\n NONE: api_1.DiagLogLevel.NONE,\n};\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(key, environment, values) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n/**\n * Parses environment values\n * @param values\n */\nfunction parseEnvironment(values) {\n const environment = {};\n for (const env in exports.DEFAULT_ENVIRONMENT) {\n const key = env;\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n }\n else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n }\n else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n }\n else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n return environment;\n}\nexports.parseEnvironment = parseEnvironment;\n/**\n * Get environment in node or browser without\n * populating default values.\n */\nfunction getEnvWithoutDefaults() {\n return typeof process !== 'undefined' && process && process.env\n ? parseEnvironment(process.env)\n : parseEnvironment(globalThis_1._globalThis);\n}\nexports.getEnvWithoutDefaults = getEnvWithoutDefaults;\n//# sourceMappingURL=environment.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getEnv = void 0;\nconst os = require(\"os\");\nconst environment_1 = require(\"../../utils/environment\");\n/**\n * Gets the environment variables\n */\nfunction getEnv() {\n const processEnv = (0, environment_1.parseEnvironment)(process.env);\n return Object.assign({\n HOSTNAME: os.hostname(),\n }, environment_1.DEFAULT_ENVIRONMENT, processEnv);\n}\nexports.getEnv = getEnv;\n//# sourceMappingURL=environment.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports._globalThis = void 0;\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexports._globalThis = typeof globalThis === 'object' ? globalThis : global;\n//# sourceMappingURL=globalThis.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hexToBase64 = void 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 */\nfunction intValue(charCode) {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n // A-F\n return charCode - 55;\n}\nconst buf8 = Buffer.alloc(8);\nconst buf16 = Buffer.alloc(16);\nfunction hexToBase64(hexStr) {\n let buf;\n if (hexStr.length === 16) {\n buf = buf8;\n }\n else if (hexStr.length === 32) {\n buf = buf16;\n }\n else {\n buf = Buffer.alloc(hexStr.length / 2);\n }\n let offset = 0;\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf.writeUInt8((hi << 4) | lo, offset++);\n }\n return buf.toString('base64');\n}\nexports.hexToBase64 = hexToBase64;\n//# sourceMappingURL=hex-to-base64.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RandomIdGenerator = void 0;\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n */\nclass RandomIdGenerator {\n constructor() {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n this.generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n this.generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n }\n}\nexports.RandomIdGenerator = RandomIdGenerator;\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes) {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n }\n else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n//# sourceMappingURL=RandomIdGenerator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.otperformance = void 0;\nconst perf_hooks_1 = require(\"perf_hooks\");\nexports.otperformance = perf_hooks_1.performance;\n//# sourceMappingURL=performance.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.VERSION = void 0;\n// this is autogenerated file, see scripts/version-update.js\nexports.VERSION = '1.18.1';\n//# sourceMappingURL=version.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SDK_INFO = void 0;\nconst version_1 = require(\"../../version\");\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\n/** Constants describing the SDK in use */\nexports.SDK_INFO = {\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME]: 'opentelemetry',\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'node',\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TelemetrySdkLanguageValues.NODEJS,\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION]: version_1.VERSION,\n};\n//# sourceMappingURL=sdk-info.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.unrefTimer = void 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 */\nfunction unrefTimer(timer) {\n timer.unref();\n}\nexports.unrefTimer = unrefTimer;\n//# sourceMappingURL=timer-util.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./environment\"), exports);\n__exportStar(require(\"./globalThis\"), exports);\n__exportStar(require(\"./hex-to-base64\"), exports);\n__exportStar(require(\"./RandomIdGenerator\"), exports);\n__exportStar(require(\"./performance\"), exports);\n__exportStar(require(\"./sdk-info\"), exports);\n__exportStar(require(\"./timer-util\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\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__exportStar(require(\"./node\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToMicroseconds = exports.hrTimeToMilliseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = void 0;\nconst platform_1 = require(\"../platform\");\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 * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nfunction millisToHrTime(epochMillis) {\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}\nexports.millisToHrTime = millisToHrTime;\nfunction getTimeOrigin() {\n let timeOrigin = platform_1.otperformance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf = platform_1.otperformance;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\nexports.getTimeOrigin = getTimeOrigin;\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nfunction hrTime(performanceNow) {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : platform_1.otperformance.now());\n return addHrTimes(timeOrigin, now);\n}\nexports.hrTime = hrTime;\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nfunction timeInputToHrTime(time) {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time;\n }\n else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n }\n else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n }\n else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n }\n else {\n throw TypeError('Invalid input type');\n }\n}\nexports.timeInputToHrTime = timeInputToHrTime;\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nfunction hrTimeDuration(startTime, endTime) {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n return [seconds, nanos];\n}\nexports.hrTimeDuration = hrTimeDuration;\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nfunction hrTimeToTimeStamp(time) {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\nexports.hrTimeToTimeStamp = hrTimeToTimeStamp;\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nfunction hrTimeToNanoseconds(time) {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\nexports.hrTimeToNanoseconds = hrTimeToNanoseconds;\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nfunction hrTimeToMilliseconds(time) {\n return time[0] * 1e3 + time[1] / 1e6;\n}\nexports.hrTimeToMilliseconds = hrTimeToMilliseconds;\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nfunction hrTimeToMicroseconds(time) {\n return time[0] * 1e6 + time[1] / 1e3;\n}\nexports.hrTimeToMicroseconds = hrTimeToMicroseconds;\n/**\n * check if time is HrTime\n * @param value\n */\nfunction isTimeInputHrTime(value) {\n return (Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number');\n}\nexports.isTimeInputHrTime = isTimeInputHrTime;\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nfunction isTimeInput(value) {\n return (isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date);\n}\nexports.isTimeInput = isTimeInput;\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nfunction addHrTimes(time1, time2) {\n const out = [time1[0] + time2[0], time1[1] + time2[1]];\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n return out;\n}\nexports.addHrTimes = addHrTimes;\n//# sourceMappingURL=time.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExportResultCode = void 0;\nvar ExportResultCode;\n(function (ExportResultCode) {\n ExportResultCode[ExportResultCode[\"SUCCESS\"] = 0] = \"SUCCESS\";\n ExportResultCode[ExportResultCode[\"FAILED\"] = 1] = \"FAILED\";\n})(ExportResultCode = exports.ExportResultCode || (exports.ExportResultCode = {}));\n//# sourceMappingURL=ExportResult.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CompositePropagator = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/** Combines multiple propagators into a single propagator. */\nclass CompositePropagator {\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config = {}) {\n var _a;\n this._propagators = (_a = config.propagators) !== null && _a !== void 0 ? _a : [];\n this._fields = Array.from(new Set(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 * 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, carrier, setter) {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n }\n catch (err) {\n api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);\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, carrier, getter) {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n }\n catch (err) {\n api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`);\n }\n return ctx;\n }, context);\n }\n fields() {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\nexports.CompositePropagator = CompositePropagator;\n//# sourceMappingURL=composite.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateValue = exports.validateKey = void 0;\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 * 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 */\nfunction validateKey(key) {\n return VALID_KEY_REGEX.test(key);\n}\nexports.validateKey = validateKey;\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 */\nfunction validateValue(value) {\n return (VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value));\n}\nexports.validateValue = validateValue;\n//# sourceMappingURL=validators.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TraceState = void 0;\nconst validators_1 = require(\"../internal/validators\");\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\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 */\nclass TraceState {\n constructor(rawTraceState) {\n this._internalState = new Map();\n if (rawTraceState)\n this._parse(rawTraceState);\n }\n set(key, value) {\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 unset(key) {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n get(key) {\n return this._internalState.get(key);\n }\n serialize() {\n return this._keys()\n .reduce((agg, key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n _parse(rawTraceState) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN)\n 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, part) => {\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 ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) {\n agg.set(key, value);\n }\n else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\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(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 _keys() {\n return Array.from(this._internalState.keys()).reverse();\n }\n _clone() {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\nexports.TraceState = TraceState;\n//# sourceMappingURL=TraceState.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst suppress_tracing_1 = require(\"./suppress-tracing\");\nconst TraceState_1 = require(\"./TraceState\");\nexports.TRACE_PARENT_HEADER = 'traceparent';\nexports.TRACE_STATE_HEADER = 'tracestate';\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(`^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`);\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 */\nfunction parseTraceParent(traceParent) {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match)\n return null;\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])\n return null;\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\nexports.parseTraceParent = parseTraceParent;\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 */\nclass W3CTraceContextPropagator {\n inject(context, carrier, setter) {\n const spanContext = api_1.trace.getSpanContext(context);\n if (!spanContext ||\n (0, suppress_tracing_1.isTracingSuppressed)(context) ||\n !(0, api_1.isSpanContextValid)(spanContext))\n return;\n const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;\n setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize());\n }\n }\n extract(context, carrier, getter) {\n const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER);\n if (!traceParentHeader)\n return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string')\n return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext)\n return context;\n spanContext.isRemote = true;\n const traceStateHeader = getter.get(carrier, exports.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_1.TraceState(typeof state === 'string' ? state : undefined);\n }\n return api_1.trace.setSpanContext(context, spanContext);\n }\n fields() {\n return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER];\n }\n}\nexports.W3CTraceContextPropagator = W3CTraceContextPropagator;\n//# sourceMappingURL=W3CTraceContextPropagator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=IdGenerator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst RPC_METADATA_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key RPC_METADATA');\nvar RPCType;\n(function (RPCType) {\n RPCType[\"HTTP\"] = \"http\";\n})(RPCType = exports.RPCType || (exports.RPCType = {}));\nfunction setRPCMetadata(context, meta) {\n return context.setValue(RPC_METADATA_KEY, meta);\n}\nexports.setRPCMetadata = setRPCMetadata;\nfunction deleteRPCMetadata(context) {\n return context.deleteValue(RPC_METADATA_KEY);\n}\nexports.deleteRPCMetadata = deleteRPCMetadata;\nfunction getRPCMetadata(context) {\n return context.getValue(RPC_METADATA_KEY);\n}\nexports.getRPCMetadata = getRPCMetadata;\n//# sourceMappingURL=rpc-metadata.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AlwaysOffSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples no traces.\n */\nclass AlwaysOffSampler {\n shouldSample() {\n return {\n decision: api_1.SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return 'AlwaysOffSampler';\n }\n}\nexports.AlwaysOffSampler = AlwaysOffSampler;\n//# sourceMappingURL=AlwaysOffSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AlwaysOnSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples all traces.\n */\nclass AlwaysOnSampler {\n shouldSample() {\n return {\n decision: api_1.SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n toString() {\n return 'AlwaysOnSampler';\n }\n}\nexports.AlwaysOnSampler = AlwaysOnSampler;\n//# sourceMappingURL=AlwaysOnSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ParentBasedSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst global_error_handler_1 = require(\"../../common/global-error-handler\");\nconst AlwaysOffSampler_1 = require(\"./AlwaysOffSampler\");\nconst AlwaysOnSampler_1 = require(\"./AlwaysOnSampler\");\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nclass ParentBasedSampler {\n constructor(config) {\n var _a, _b, _c, _d;\n this._root = config.root;\n if (!this._root) {\n (0, global_error_handler_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured'));\n this._root = new AlwaysOnSampler_1.AlwaysOnSampler();\n }\n this._remoteParentSampled =\n (_a = config.remoteParentSampled) !== null && _a !== void 0 ? _a : new AlwaysOnSampler_1.AlwaysOnSampler();\n this._remoteParentNotSampled =\n (_b = config.remoteParentNotSampled) !== null && _b !== void 0 ? _b : new AlwaysOffSampler_1.AlwaysOffSampler();\n this._localParentSampled =\n (_c = config.localParentSampled) !== null && _c !== void 0 ? _c : new AlwaysOnSampler_1.AlwaysOnSampler();\n this._localParentNotSampled =\n (_d = config.localParentNotSampled) !== null && _d !== void 0 ? _d : new AlwaysOffSampler_1.AlwaysOffSampler();\n }\n shouldSample(context, traceId, spanName, spanKind, attributes, links) {\n const parentContext = api_1.trace.getSpanContext(context);\n if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {\n return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n toString() {\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}\nexports.ParentBasedSampler = ParentBasedSampler;\n//# sourceMappingURL=ParentBasedSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TraceIdRatioBasedSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples a given fraction of traces based of trace id deterministically.\n */\nclass TraceIdRatioBasedSampler {\n constructor(_ratio = 0) {\n this._ratio = _ratio;\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n shouldSample(context, traceId) {\n return {\n decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound\n ? api_1.SamplingDecision.RECORD_AND_SAMPLED\n : api_1.SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n _normalize(ratio) {\n if (typeof ratio !== 'number' || isNaN(ratio))\n return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n _accumulate(traceId) {\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}\nexports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;\n//# sourceMappingURL=TraceIdRatioBasedSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isPlainObject = void 0;\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\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 getPrototype = overArg(Object.getPrototypeOf, Object);\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function (arg) {\n return func(transform(arg));\n };\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 */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString);\n}\nexports.isPlainObject = isPlainObject;\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) {\n return value != null && typeof value == 'object';\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) {\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 * 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) {\n const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];\n let unmasked = false;\n try {\n value[symToStringTag] = undefined;\n unmasked = true;\n }\n catch (e) {\n // silence\n }\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n }\n else {\n delete value[symToStringTag];\n }\n }\n return result;\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) {\n return nativeObjectToString.call(value);\n}\n//# sourceMappingURL=lodash.merge.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.merge = void 0;\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst lodash_merge_1 = require(\"./lodash.merge\");\nconst MAX_LEVEL = 20;\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nfunction merge(...args) {\n let result = args.shift();\n const objects = new WeakMap();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n return result;\n}\nexports.merge = merge;\nfunction takeValue(value) {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\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(one, two, level = 0, objects) {\n let result;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n }\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 }\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 }\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 for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n }\n else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n }\n else {\n const obj1 = result[key];\n const obj2 = twoValue;\n if (wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)) {\n delete result[key];\n }\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 result[key] = mergeTwoObjects(result[key], twoValue, level, objects);\n }\n }\n }\n }\n else {\n result = two;\n }\n }\n return result;\n}\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(obj, key, objects) {\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}\nfunction isArray(value) {\n return Array.isArray(value);\n}\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isObject(value) {\n return (!isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object');\n}\nfunction isPrimitive(value) {\n return (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}\nfunction shouldMerge(one, two) {\n if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) {\n return false;\n }\n return true;\n}\n//# sourceMappingURL=merge.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.callWithTimeout = exports.TimeoutError = void 0;\n/**\n * Error that is thrown on timeouts.\n */\nclass TimeoutError extends Error {\n constructor(message) {\n super(message);\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}\nexports.TimeoutError = TimeoutError;\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 */\nfunction callWithTimeout(promise, timeout) {\n let timeoutHandle;\n const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n return Promise.race([promise, timeoutPromise]).then(result => {\n clearTimeout(timeoutHandle);\n return result;\n }, reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n });\n}\nexports.callWithTimeout = callWithTimeout;\n//# sourceMappingURL=timeout.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isUrlIgnored = exports.urlMatches = void 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 */\nfunction urlMatches(url, urlToMatch) {\n if (typeof urlToMatch === 'string') {\n return url === urlToMatch;\n }\n else {\n return !!url.match(urlToMatch);\n }\n}\nexports.urlMatches = urlMatches;\n/**\n * Check if {@param url} should be ignored when comparing against {@param ignoredUrls}\n * @param url\n * @param ignoredUrls\n */\nfunction isUrlIgnored(url, ignoredUrls) {\n if (!ignoredUrls) {\n return false;\n }\n for (const ignoreUrl of ignoredUrls) {\n if (urlMatches(url, ignoreUrl)) {\n return true;\n }\n }\n return false;\n}\nexports.isUrlIgnored = isUrlIgnored;\n//# sourceMappingURL=url.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isWrapped = void 0;\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nfunction isWrapped(func) {\n return (typeof func === 'function' &&\n typeof func.__original === 'function' &&\n typeof func.__unwrap === 'function' &&\n func.__wrapped === true);\n}\nexports.isWrapped = isWrapped;\n//# sourceMappingURL=wrap.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Deferred = void 0;\nclass Deferred {\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n get promise() {\n return this._promise;\n }\n resolve(val) {\n this._resolve(val);\n }\n reject(err) {\n this._reject(err);\n }\n}\nexports.Deferred = Deferred;\n//# sourceMappingURL=promise.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BindOnceFuture = void 0;\nconst promise_1 = require(\"./promise\");\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nclass BindOnceFuture {\n constructor(_callback, _that) {\n this._callback = _callback;\n this._that = _that;\n this._isCalled = false;\n this._deferred = new promise_1.Deferred();\n }\n get isCalled() {\n return this._isCalled;\n }\n get promise() {\n return this._deferred.promise;\n }\n call(...args) {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(val => this._deferred.resolve(val), err => this._deferred.reject(err));\n }\n catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\nexports.BindOnceFuture = BindOnceFuture;\n//# sourceMappingURL=callback.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports._export = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst suppress_tracing_1 = require(\"../trace/suppress-tracing\");\n/**\n * @internal\n * Shared functionality used by Exporters while exporting data, including suppresion of Traces.\n */\nfunction _export(exporter, arg) {\n return new Promise(resolve => {\n // prevent downstream exporter calls from generating spans\n api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {\n exporter.export(arg, (result) => {\n resolve(result);\n });\n });\n });\n}\nexports._export = _export;\n//# sourceMappingURL=exporter.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.internal = exports.baggageUtils = void 0;\n__exportStar(require(\"./baggage/propagation/W3CBaggagePropagator\"), exports);\n__exportStar(require(\"./common/anchored-clock\"), exports);\n__exportStar(require(\"./common/attributes\"), exports);\n__exportStar(require(\"./common/global-error-handler\"), exports);\n__exportStar(require(\"./common/logging-error-handler\"), exports);\n__exportStar(require(\"./common/time\"), exports);\n__exportStar(require(\"./common/types\"), exports);\n__exportStar(require(\"./ExportResult\"), exports);\nexports.baggageUtils = require(\"./baggage/utils\");\n__exportStar(require(\"./platform\"), exports);\n__exportStar(require(\"./propagation/composite\"), exports);\n__exportStar(require(\"./trace/W3CTraceContextPropagator\"), exports);\n__exportStar(require(\"./trace/IdGenerator\"), exports);\n__exportStar(require(\"./trace/rpc-metadata\"), exports);\n__exportStar(require(\"./trace/sampler/AlwaysOffSampler\"), exports);\n__exportStar(require(\"./trace/sampler/AlwaysOnSampler\"), exports);\n__exportStar(require(\"./trace/sampler/ParentBasedSampler\"), exports);\n__exportStar(require(\"./trace/sampler/TraceIdRatioBasedSampler\"), exports);\n__exportStar(require(\"./trace/suppress-tracing\"), exports);\n__exportStar(require(\"./trace/TraceState\"), exports);\n__exportStar(require(\"./utils/environment\"), exports);\n__exportStar(require(\"./utils/merge\"), exports);\n__exportStar(require(\"./utils/sampling\"), exports);\n__exportStar(require(\"./utils/timeout\"), exports);\n__exportStar(require(\"./utils/url\"), exports);\n__exportStar(require(\"./utils/wrap\"), exports);\n__exportStar(require(\"./utils/callback\"), exports);\n__exportStar(require(\"./version\"), exports);\nconst exporter_1 = require(\"./internal/exporter\");\nexports.internal = {\n _export: exporter_1._export,\n};\n//# sourceMappingURL=index.js.map","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { SpanExporter, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { SpanKind as OtSpanKind } from \"@opentelemetry/api\";\nimport { JsonSchemaHelper, JsonSchema, JsonSchemaType } from \"./JsonSchemaHelper\";\nimport { TuskDriftMode } from \"../TuskDrift\";\nimport { CleanSpanData, MetadataObject, TdSpanAttributes } from \"../types\";\nimport { PackageType, StatusCode } from \"@use-tusk/drift-schemas/core/span\";\nimport { SpanExportServiceClient } from \"@use-tusk/drift-schemas/backend/span_export_service.client\";\nimport { ExportSpansRequest } from \"@use-tusk/drift-schemas/backend/span_export_service\";\nimport { TwirpFetchTransport } from \"@protobuf-ts/twirp-transport\";\nimport { Span } from \"@use-tusk/drift-schemas/core/span\";\nimport { logger, OriginalGlobalUtils, mapOtToPb, toStruct } from \"../utils\";\n\nexport interface TdTraceExporterConfig {\n baseDirectory: string;\n mode: TuskDriftMode;\n observableServiceId?: string;\n useRemoteExport: boolean;\n apiKey?: string;\n tuskBackendBaseUrl: string;\n environment: string;\n sdkVersion: string;\n sdkInstanceId: string;\n}\n\nconst DRIFT_API_PATH = \"/api/drift\";\n\n/**\n * If useRemoteExport is true, TdTraceExporter exports spans to a remote endpoint via protobuf.\n * If useRemoteExport is false, TdTraceExporter stores spans organized by trace ID in separate files.\n * - Each trace gets its own JSONL file: `{baseDirectory}/{timestamp}_trace_{traceId}.jsonl`.\n */\nexport class TdSpanExporter implements SpanExporter {\n private baseDirectory: string;\n private mode: TuskDriftMode;\n private traceFileMap: Map<string, string> = new Map();\n\n // Remote export properties\n private useRemoteExport: boolean;\n private spanExportClient: SpanExportServiceClient;\n private observableServiceId?: string;\n private tuskBackendBaseUrl: string;\n private apiKey?: string;\n private environment: string;\n private sdkVersion: string;\n private sdkInstanceId: string;\n\n constructor(config: TdTraceExporterConfig) {\n this.baseDirectory = config.baseDirectory;\n this.mode = config.mode;\n this.useRemoteExport = config.useRemoteExport;\n this.observableServiceId = config.observableServiceId;\n this.apiKey = config.apiKey;\n this.tuskBackendBaseUrl = config.tuskBackendBaseUrl;\n this.environment = config.environment;\n this.sdkVersion = config.sdkVersion;\n this.sdkInstanceId = config.sdkInstanceId;\n\n // Initialize file system for local development\n if (!fs.existsSync(this.baseDirectory)) {\n fs.mkdirSync(this.baseDirectory, { recursive: true });\n }\n\n // Initialize protobuf client for remote export\n if (this.useRemoteExport && this.apiKey) {\n const transport = new TwirpFetchTransport({\n baseUrl: `${this.tuskBackendBaseUrl}${DRIFT_API_PATH}`,\n meta: {\n \"x-api-key\": this.apiKey,\n \"x-td-skip-instrumentation\": \"true\",\n },\n });\n this.spanExportClient = new SpanExportServiceClient(transport);\n }\n\n logger.debug(\n `TdTraceExporter initialized - ${this.useRemoteExport ? \"remote export enabled\" : \"local file export only\"}`,\n );\n }\n\n /**\n * Export spans to trace-specific files and optionally to remote endpoint\n */\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n logger.debug(`TdTraceExporter.export() called with ${spans.length} span(s)`);\n\n if (this.mode !== TuskDriftMode.RECORD) {\n logger.debug(`Not recording spans in tuskDriftMode: ${this.mode}`);\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n\n // Additionally export to remote endpoint if configured\n if (this.useRemoteExport) {\n if (this.spanExportClient) {\n this.exportToRemote(spans)\n .then(() => {\n logger.debug(`Successfully exported ${spans.length} spans to remote endpoint`);\n resultCallback({ code: ExportResultCode.SUCCESS });\n })\n .catch((error) => {\n logger.error(`Failed to export spans to remote:`, error);\n resultCallback({\n code: ExportResultCode.FAILED,\n error: error instanceof Error ? error : new Error(\"Remote export failed\"),\n });\n });\n } else {\n logger.error(\"Remote export client not initialized, likely because apiKey is not provided\");\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error(\n \"Remote export client not initialized, likely because apiKey is not provided\",\n ),\n });\n }\n } else {\n this.exportToLocalFiles(spans);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n }\n\n /**\n * Export spans to remote endpoint via protobuf\n */\n private async exportToRemote(spans: ReadableSpan[]): Promise<void> {\n if (!this.spanExportClient) {\n throw new Error(\"Remote export client not initialized\");\n }\n\n if (!this.observableServiceId) {\n throw new Error(\"Observable service ID not provided in config\");\n }\n\n // Transform spans to protobuf format\n const protoSpans: Span[] = spans.map((span) => this.transformSpanToProtobuf(span));\n\n const request: ExportSpansRequest = {\n observableServiceId: this.observableServiceId,\n environment: this.environment,\n sdkVersion: this.sdkVersion,\n sdkInstanceId: this.sdkInstanceId,\n spans: protoSpans,\n };\n\n const response = await this.spanExportClient.exportSpans(request);\n\n if (!response.response.success) {\n throw new Error(`Remote export failed: ${response.response.message}`);\n }\n }\n\n /**\n * Export spans to local files\n */\n private exportToLocalFiles(spans: ReadableSpan[]): void {\n try {\n for (const span of spans) {\n const traceId = span.spanContext().traceId;\n const spanData = this.transformSpanToCleanJSON(span);\n\n // Get or create file path for this trace ID\n let filePath = this.traceFileMap.get(traceId);\n\n if (!filePath) {\n const isoTimestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n filePath = path.join(this.baseDirectory, `${isoTimestamp}_trace_${traceId}.jsonl`);\n this.traceFileMap.set(traceId, filePath);\n }\n\n const jsonLine = JSON.stringify(spanData) + \"\\n\";\n fs.appendFileSync(filePath, jsonLine, \"utf8\");\n }\n\n logger.debug(\n `Exported ${spans.length} span(s) to trace-specific files in ${this.baseDirectory}`,\n );\n } catch (error) {\n logger.error(`Failed to export spans to local files:`, error);\n throw error;\n }\n }\n\n /**\n * Transform OpenTelemetry span to clean JSON format with compile-time type safety\n * Return type is derived from protobuf schema but uses clean JSON.\n * We use JSON because serialized protobuf is extremely verbose and not readable.\n */\n private transformSpanToCleanJSON(span: ReadableSpan): CleanSpanData {\n const isRootSpan = !span.parentSpanId || span.kind === OtSpanKind.SERVER;\n\n // Extract data from span attributes\n const attributes = span.attributes;\n const packageName = this.extractPackageName(attributes);\n const instrumentationName = this.extractInstrumentationName(span, attributes);\n const submoduleName = this.extractSubmoduleName(attributes);\n\n // Process input data\n const inputValueString = attributes[TdSpanAttributes.INPUT_VALUE] as string;\n const inputData = JSON.parse(inputValueString);\n\n // Extract input schema merges if they exist\n const inputSchemaMergesString = attributes[TdSpanAttributes.INPUT_SCHEMA_MERGES] as string;\n const inputSchemaMerges = inputSchemaMergesString\n ? JSON.parse(inputSchemaMergesString)\n : undefined;\n\n const { schema: inputSchema, decodedValueHash: inputValueHash } =\n JsonSchemaHelper.generateSchemaAndHash(inputData, inputSchemaMerges);\n\n // Process output data\n let outputData: any = {};\n let outputSchema: JsonSchema = { type: JsonSchemaType.OBJECT, properties: {} };\n let outputValueHash: string = \"\";\n\n if (attributes[TdSpanAttributes.OUTPUT_VALUE]) {\n const outputValueString = attributes[TdSpanAttributes.OUTPUT_VALUE] as string;\n outputData = JSON.parse(outputValueString);\n\n // Extract output schema merges if they exist\n const outputSchemaMergesString = attributes[TdSpanAttributes.OUTPUT_SCHEMA_MERGES] as string;\n const outputSchemaMerges = outputSchemaMergesString\n ? JSON.parse(outputSchemaMergesString)\n : undefined;\n\n ({ schema: outputSchema, decodedValueHash: outputValueHash } =\n JsonSchemaHelper.generateSchemaAndHash(outputData, outputSchemaMerges));\n } else {\n ({ schema: outputSchema, decodedSchemaHash: outputValueHash } =\n JsonSchemaHelper.generateSchemaAndHash(outputData));\n }\n\n let metadata: MetadataObject | undefined = undefined;\n if (attributes[TdSpanAttributes.METADATA]) {\n metadata = JSON.parse(attributes[TdSpanAttributes.METADATA] as string);\n }\n\n let transformMetadata;\n const transformMetadataString = attributes[TdSpanAttributes.TRANSFORM_METADATA] as\n | string\n | undefined;\n if (transformMetadataString) {\n try {\n transformMetadata = JSON.parse(transformMetadataString);\n } catch (error) {\n logger.warn(\"Failed to parse transform metadata\", error);\n }\n }\n\n const originalDate = OriginalGlobalUtils.getOriginalDate();\n\n return {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n parentSpanId: span.parentSpanId || \"\",\n\n name: attributes[TdSpanAttributes.NAME] as string,\n\n packageName,\n instrumentationName,\n submoduleName: submoduleName || \"\",\n\n packageType: (attributes[TdSpanAttributes.PACKAGE_TYPE] as PackageType) || undefined,\n\n inputValue: inputData,\n outputValue: outputData,\n inputSchema,\n outputSchema,\n\n inputSchemaHash: JsonSchemaHelper.generateDeterministicHash(inputSchema),\n outputSchemaHash: JsonSchemaHelper.generateDeterministicHash(outputSchema),\n inputValueHash,\n outputValueHash,\n\n kind: span.kind,\n\n status: {\n code: span.status.code === 1 ? StatusCode.OK : StatusCode.ERROR,\n message: span.status.message || \"\",\n },\n\n isPreAppStart: attributes[TdSpanAttributes.IS_PRE_APP_START] === true,\n\n timestamp: {\n seconds: Math.floor(originalDate.getTime() / 1000),\n nanos: (originalDate.getTime() % 1000) * 1000000,\n },\n duration: {\n seconds: span.duration[0],\n nanos: span.duration[1],\n },\n isRootSpan,\n metadata,\n transformMetadata,\n } satisfies CleanSpanData;\n }\n\n /**\n * Transform OpenTelemetry span to protobuf format\n */\n private transformSpanToProtobuf(span: ReadableSpan): Span {\n // Convert CleanSpanData to protobuf Span format\n const cleanSpan = this.transformSpanToCleanJSON(span);\n\n return {\n traceId: cleanSpan.traceId,\n spanId: cleanSpan.spanId,\n parentSpanId: cleanSpan.parentSpanId,\n name: cleanSpan.name,\n packageName: cleanSpan.packageName,\n instrumentationName: cleanSpan.instrumentationName,\n submoduleName: cleanSpan.submoduleName,\n packageType: cleanSpan.packageType || PackageType.UNSPECIFIED,\n inputValue: toStruct(cleanSpan.inputValue),\n outputValue: toStruct(cleanSpan.outputValue),\n inputSchema: toStruct(cleanSpan.inputSchema),\n outputSchema: toStruct(cleanSpan.outputSchema),\n inputSchemaHash: cleanSpan.inputSchemaHash || \"\",\n outputSchemaHash: cleanSpan.outputSchemaHash || \"\",\n inputValueHash: cleanSpan.inputValueHash || \"\",\n outputValueHash: cleanSpan.outputValueHash || \"\",\n kind: mapOtToPb(span.kind as OtSpanKind),\n status: cleanSpan.status,\n isPreAppStart: cleanSpan.isPreAppStart,\n timestamp: { seconds: BigInt(cleanSpan.timestamp.seconds), nanos: cleanSpan.timestamp.nanos },\n duration: { seconds: BigInt(cleanSpan.duration.seconds), nanos: cleanSpan.duration.nanos },\n isRootSpan: cleanSpan.isRootSpan,\n metadata: toStruct(cleanSpan.metadata),\n };\n }\n\n /**\n * Extract package name from attributes or instrumentation library\n */\n private extractPackageName(attributes: any): string {\n // Check for explicit package name in attributes\n if (attributes[TdSpanAttributes.PACKAGE_NAME]) {\n return attributes[TdSpanAttributes.PACKAGE_NAME] as string;\n }\n\n return \"unknown\";\n }\n\n /**\n * Extract instrumentation name from span data\n */\n private extractInstrumentationName(span: ReadableSpan, attributes: any): string {\n // Check for explicit instrumentation name in attributes\n if (attributes[TdSpanAttributes.INSTRUMENTATION_NAME]) {\n return attributes[TdSpanAttributes.INSTRUMENTATION_NAME] as string;\n }\n\n // Generate from library name or type\n if (span.instrumentationLibrary?.name) {\n return `tusk-instrumentation-${span.instrumentationLibrary.name}`;\n }\n\n // Generate from detected package\n const packageName = this.extractPackageName(attributes);\n return `tusk-instrumentation-${packageName}`;\n }\n\n /**\n * Extract submodule name from attributes\n */\n private extractSubmoduleName(attributes: any): string | undefined {\n // Check for explicit submodule in attributes\n if (attributes[TdSpanAttributes.SUBMODULE_NAME]) {\n return attributes[TdSpanAttributes.SUBMODULE_NAME] as string;\n }\n\n return undefined;\n }\n\n /**\n * Shutdown the exporter\n */\n async shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Force flush any pending spans\n */\n async forceFlush(): Promise<void> {\n // File-based exporter writes immediately, so nothing to flush\n return Promise.resolve();\n }\n}\n","import net from \"net\";\nimport { MIN_CLI_VERSION, SDK_VERSION } from \"../version\";\nimport { execSync } from \"child_process\";\nimport path from \"path\";\nimport os from \"os\";\nimport fs from \"fs\";\nimport {\n CLIMessage,\n MessageType,\n GetMockRequest,\n GetMockResponse,\n ConnectRequest,\n SDKMessage,\n SendInboundSpanForReplayRequest,\n} from \"@use-tusk/drift-schemas/core/communication\";\nimport { context, Context, SpanKind as OtSpanKind } from \"@opentelemetry/api\";\nimport { Value } from \"@use-tusk/drift-schemas/google/protobuf/struct\";\nimport { CleanSpanData, CALLING_LIBRARY_CONTEXT_KEY } from \"./types\";\nimport { Span } from \"@use-tusk/drift-schemas/core/span\";\nimport { logger, objectToProtobufStruct, toStruct, mapOtToPb, OriginalGlobalUtils } from \"./utils\";\n\nexport interface MockRequestInput {\n testId: string;\n outboundSpan: CleanSpanData;\n}\n\ninterface MockResponseOutput {\n found: boolean;\n response?: Record<string, unknown>;\n error?: string;\n}\n\nexport class ProtobufCommunicator {\n private client: net.Socket | null = null;\n private pendingRequests = new Map<\n string,\n {\n resolve: (response: MockResponseOutput) => void;\n reject: (error: Error) => void;\n }\n >();\n private incomingBuffer = Buffer.alloc(0);\n // Store the context when connecting and reuse it\n private protobufContext: Context | null = null;\n\n private makeConnection(socketPath: string, callback: () => void) {\n const currentContext = context.active();\n this.protobufContext = currentContext.setValue(\n CALLING_LIBRARY_CONTEXT_KEY,\n \"ProtobufCommunicator\",\n );\n\n // Create connection in context so TCP instrumentation knows to ignore these TCP calls\n return context.with(this.protobufContext, () => {\n // TCP operations here will have the context set\n this.client = net.createConnection(socketPath, callback);\n });\n }\n\n async connect(socketPath: string, serviceId: string): Promise<void> {\n return new Promise((resolve, reject) => {\n this.makeConnection(socketPath, () => {\n logger.debug(\"Connected to CLI via protobuf\");\n this.sendConnectMessage(serviceId).then(resolve).catch(reject);\n });\n\n this.client?.on(\"error\", (err) => {\n logger.error(\"Connection error:\", err);\n reject(err);\n });\n\n this.client?.on(\"data\", (data) => {\n this.handleIncomingData(data);\n });\n\n this.client?.on(\"timeout\", () => {\n logger.error(\"Connection timeout\");\n reject(new Error(\"Connection timeout\"));\n });\n\n this.client?.on(\"end\", () => {\n logger.debug(\"Connection to CLI ended\");\n });\n\n this.client?.on(\"close\", () => {\n logger.debug(\"Connection to CLI closed\");\n // Reject all pending requests\n for (const [requestId, { reject }] of this.pendingRequests) {\n reject(new Error(\"Connection closed before response received\"));\n }\n this.pendingRequests.clear();\n });\n });\n }\n\n private async sendConnectMessage(serviceId: string): Promise<void> {\n const connectRequest = ConnectRequest.create({\n serviceId,\n sdkVersion: SDK_VERSION,\n minCliVersion: MIN_CLI_VERSION,\n });\n\n const sdkMessage = SDKMessage.create({\n type: MessageType.SDK_CONNECT,\n requestId: this.generateRequestId(),\n payload: {\n oneofKind: \"connectRequest\",\n connectRequest,\n },\n });\n\n await this.sendProtobufMessage(sdkMessage);\n\n // SDK awaits CLI's decision\n // If CLI accepts -> connection proceeds\n // If CLI rejects -> CLI closes the connection and terminates the service.\n }\n\n private getStackTrace(): string {\n const s = new Error().stack || \"\";\n return s\n .split(\"\\n\")\n .slice(2)\n .filter((l) => !l.includes(\"ProtobufCommunicator\"))\n .join(\"\\n\");\n }\n\n async requestMockAsync(mockRequest: MockRequestInput): Promise<MockResponseOutput> {\n const requestId = this.generateRequestId();\n\n // Clean the input data to remove undefined values\n const cleanSpan = mockRequest.outboundSpan\n ? this.cleanSpan(mockRequest.outboundSpan)\n : undefined;\n\n // Convert inputValue to protobuf Struct format\n if (cleanSpan?.inputValue) {\n cleanSpan.inputValue = objectToProtobufStruct(cleanSpan.inputValue);\n }\n\n // Convert inputSchema to protobuf Struct format\n if (cleanSpan?.inputSchema) {\n cleanSpan.inputSchema = objectToProtobufStruct(cleanSpan.inputSchema);\n }\n\n // Convert kind to protobuf format\n if (cleanSpan?.kind) {\n cleanSpan.kind = mapOtToPb(cleanSpan.kind as OtSpanKind);\n }\n\n const protoMockRequest = GetMockRequest.create({\n ...mockRequest,\n requestId,\n tags: {},\n outboundSpan: cleanSpan,\n stackTrace: this.getStackTrace(),\n });\n\n const sdkMessage: SDKMessage = SDKMessage.create({\n type: MessageType.MOCK_REQUEST,\n requestId: requestId,\n payload: {\n oneofKind: \"getMockRequest\",\n getMockRequest: protoMockRequest,\n },\n });\n\n logger.debug(\n `[ProtobufCommunicator] Creating mock request with requestId: ${requestId}, testId: ${mockRequest.testId}`,\n );\n\n return new Promise((resolve, reject) => {\n this.pendingRequests.set(requestId, { resolve, reject });\n this.sendProtobufMessage(sdkMessage).catch(reject);\n });\n }\n\n /**\n * This function uses a Node.js script to communicate with the CLI over a socket.\n * The script is called using execSync, which will block the main thread until the child process exits. This makes requesting mocks from the CLI synchronous.\n *\n * Since this function blocks the main thread, there is a perfomance impact for using this. We should use requestMockAsync whenever possilbe and only use this function\n * for instrumentations that request fetching mocks synchronously.\n *\n * (9/10/2025) Currently not using this since for the only sync instrumentation (Date) we're not actually fetching mocks\n */\n requestMockSync(mockRequest: MockRequestInput): MockResponseOutput {\n const requestId = this.generateRequestId();\n\n // Clean the input data to remove undefined values\n const cleanSpan = mockRequest.outboundSpan\n ? this.cleanSpan(mockRequest.outboundSpan)\n : undefined;\n\n // Convert inputValue to protobuf Struct format\n if (cleanSpan?.inputValue) {\n cleanSpan.inputValue = objectToProtobufStruct(cleanSpan.inputValue);\n }\n\n // Convert inputSchema to protobuf Struct format\n if (cleanSpan?.inputSchema) {\n cleanSpan.inputSchema = objectToProtobufStruct(cleanSpan.inputSchema);\n }\n\n // Convert kind to protobuf format\n if (cleanSpan?.kind) {\n cleanSpan.kind = mapOtToPb(cleanSpan.kind as OtSpanKind);\n }\n\n const protoMockRequest = GetMockRequest.create({\n ...mockRequest,\n requestId,\n tags: {},\n outboundSpan: cleanSpan,\n stackTrace: this.getStackTrace(),\n });\n\n const sdkMessage = SDKMessage.create({\n type: MessageType.MOCK_REQUEST,\n requestId: requestId,\n payload: {\n oneofKind: \"getMockRequest\",\n getMockRequest: protoMockRequest,\n },\n });\n\n // Serialize the message to binary\n const messageBytes = SDKMessage.toBinary(sdkMessage);\n\n // Create temporary file paths\n const tempDir = os.tmpdir();\n const requestFile = path.join(tempDir, `tusk-request-${requestId}.bin`);\n const responseFile = path.join(tempDir, `tusk-response-${requestId}.bin`);\n\n try {\n // Write length prefix (4 bytes big-endian) + message to temp file\n const lengthBuffer = Buffer.allocUnsafe(4);\n lengthBuffer.writeUInt32BE(messageBytes.length, 0);\n const fullMessage = Buffer.concat([lengthBuffer, Buffer.from(messageBytes)]);\n\n fs.writeFileSync(requestFile, fullMessage);\n\n // Determine socket path\n const socketPath =\n OriginalGlobalUtils.getOriginalProcessEnvVar(\"TUSK_MOCK_SOCKET\") ||\n path.join(os.tmpdir(), \"tusk-connect.sock\");\n\n try {\n // Check if the socket file exists and is accessible\n if (!fs.existsSync(socketPath)) {\n throw new Error(`Socket file does not exist: ${socketPath}`);\n }\n\n execSync(`nc -U -w 10 \"${socketPath}\" < \"${requestFile}\" > \"${responseFile}\"`, {\n timeout: 10000,\n stdio: \"pipe\",\n });\n\n // Read the response from the file\n const responseBuffer = fs.readFileSync(responseFile);\n\n // Parse the response\n if (responseBuffer.length < 4) {\n throw new Error(\"Invalid response: too short\");\n }\n\n // Read length prefix\n const responseLength = responseBuffer.readUInt32BE(0);\n\n if (responseBuffer.length < 4 + responseLength) {\n throw new Error(\"Invalid response: incomplete message\");\n }\n\n const responseData = responseBuffer.slice(4, 4 + responseLength);\n\n const cliMessage = CLIMessage.fromBinary(responseData);\n\n if (cliMessage.payload.oneofKind !== \"getMockResponse\") {\n throw new Error(`Unexpected response type: ${cliMessage.type}`);\n }\n\n const mockResponse = cliMessage.payload.getMockResponse;\n if (!mockResponse) {\n throw new Error(\"No mock response received\");\n }\n\n if (mockResponse.found) {\n try {\n const responseData = this.extractResponseData(mockResponse);\n return {\n found: true,\n response: responseData,\n };\n } catch (error) {\n throw new Error(`Failed to extract response data: ${error}`);\n }\n } else {\n return {\n found: false,\n error: mockResponse.error || \"Mock not found\",\n };\n }\n } catch (error: any) {\n logger.error(\"[ProtobufCommunicator] error sending request to CLI:\", error);\n throw error;\n }\n } catch (error: any) {\n throw new Error(`Sync request failed: ${error.message}`);\n } finally {\n // Clean up temp files\n try {\n fs.unlinkSync(requestFile);\n } catch (e) {\n logger.error(\"[ProtobufCommunicator] error cleaning up request file:\", e);\n }\n try {\n fs.unlinkSync(responseFile);\n } catch (e) {\n logger.error(\"[ProtobufCommunicator] error cleaning up response file:\", e);\n }\n }\n }\n\n private async sendProtobufMessage(message: SDKMessage): Promise<void> {\n if (!this.client || !this.protobufContext) {\n throw new Error(\"Not connected to CLI\");\n }\n\n const messageBytes = SDKMessage.toBinary(message);\n const lengthBuffer = Buffer.allocUnsafe(4);\n lengthBuffer.writeUInt32BE(messageBytes.length, 0);\n\n // Send message in context so TCP instrumentation knows to ignore these TCP calls\n context.with(this.protobufContext, () => {\n this.client!.write(lengthBuffer);\n this.client!.write(Buffer.from(messageBytes));\n });\n }\n\n async sendInboundSpanForReplay(span: CleanSpanData): Promise<void> {\n if (!this.client) return;\n\n const pbSpan = Span.create({\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId || \"\",\n name: span.name || \"\",\n packageName: span.packageName,\n instrumentationName: span.instrumentationName,\n submoduleName: span.submoduleName || \"\",\n inputValue: toStruct(span.inputValue),\n outputValue: toStruct(span.outputValue),\n inputSchema: toStruct(span.inputSchema),\n outputSchema: toStruct(span.outputSchema),\n inputSchemaHash: span.inputSchemaHash || \"\",\n outputSchemaHash: span.outputSchemaHash || \"\",\n inputValueHash: span.inputValueHash || \"\",\n outputValueHash: span.outputValueHash || \"\",\n kind: mapOtToPb(span.kind as OtSpanKind),\n status: { code: span.status.code, message: span.status.message || \"\" },\n timestamp: span.timestamp\n ? { seconds: BigInt(span.timestamp.seconds), nanos: span.timestamp.nanos }\n : undefined,\n isRootSpan: span.isRootSpan ?? false,\n metadata: toStruct(span.metadata),\n packageType: span.packageType,\n });\n\n const req = SendInboundSpanForReplayRequest.create({ span: pbSpan });\n\n const sdkMessage = SDKMessage.create({\n type: MessageType.INBOUND_SPAN,\n requestId: this.generateRequestId(),\n payload: {\n oneofKind: \"sendInboundSpanForReplayRequest\",\n sendInboundSpanForReplayRequest: req,\n },\n });\n\n await this.sendProtobufMessage(sdkMessage);\n }\n\n private handleIncomingData(data: Buffer): void {\n this.incomingBuffer = Buffer.concat([this.incomingBuffer, data]);\n logger.debug(`[ProtobufCommunicator] Processing buffer, length: ${this.incomingBuffer.length}`);\n\n while (this.incomingBuffer.length >= 4) {\n const messageLength = this.incomingBuffer.readUInt32BE(0);\n logger.debug(\n `[ProtobufCommunicator] Message length from prefix: ${messageLength}, buffer has: ${this.incomingBuffer.length - 4}`,\n );\n\n if (this.incomingBuffer.length < 4 + messageLength) {\n logger.debug(\n `[ProtobufCommunicator] Incomplete message, waiting for more data. Need ${4 + messageLength}, have ${this.incomingBuffer.length}`,\n );\n break;\n }\n\n const messageData = this.incomingBuffer.slice(4, 4 + messageLength);\n this.incomingBuffer = this.incomingBuffer.slice(4 + messageLength);\n\n try {\n const cliMessage = CLIMessage.fromBinary(messageData);\n logger.debug(\n `[ProtobufCommunicator] Parsed CLI message type: ${cliMessage.type}, requestId: ${cliMessage.requestId}`,\n );\n this.handleCLIMessage(cliMessage);\n } catch (error) {\n logger.error(\"[ProtobufCommunicator] failed to parse CLI message:\", error);\n }\n }\n }\n\n private handleCLIMessage(message: CLIMessage): void {\n const requestId = message.requestId;\n\n logger.debug(\n `[ProtobufCommunicator] Received CLI message for requestId: ${requestId}, pending requests:`,\n Array.from(this.pendingRequests.keys()),\n );\n\n if (message.payload.oneofKind === \"connectResponse\") {\n const connectResponse = message.payload.connectResponse;\n if (connectResponse?.success) {\n logger.debug(\"[ProtobufCommunicator] CLI acknowledged connection\");\n } else {\n logger.error(\"[ProtobufCommunicator] CLI rejected connection:\", connectResponse?.error);\n }\n return;\n }\n\n if (message.payload.oneofKind === \"getMockResponse\") {\n const mockResponse = message.payload.getMockResponse;\n logger.debug(\n `[ProtobufCommunicator] Received mock response for requestId: ${requestId}, pending requests:`,\n Array.from(this.pendingRequests.keys()),\n );\n const pendingRequest = this.pendingRequests.get(requestId);\n\n if (!pendingRequest) {\n logger.warn(\n \"[ProtobufCommunicator] received response for unknown request:\",\n requestId,\n \"Available pending requests:\",\n Array.from(this.pendingRequests.keys()),\n );\n return;\n }\n\n this.pendingRequests.delete(requestId);\n\n if (!mockResponse) {\n pendingRequest.reject(new Error(\"No mock response received\"));\n return;\n }\n\n if (mockResponse.found) {\n try {\n const responseData = this.extractResponseData(mockResponse);\n pendingRequest.resolve({\n found: true,\n response: responseData,\n });\n } catch (error) {\n pendingRequest.reject(new Error(`Failed to extract response data: ${error}`));\n }\n } else {\n pendingRequest.resolve({\n found: false,\n error: mockResponse.error || \"Mock not found\",\n });\n }\n }\n }\n\n /**\n * Extract response data from MockResponse\n */\n private extractResponseData(mockResponse: GetMockResponse): Record<string, unknown> {\n if (!mockResponse.responseData) {\n return {};\n }\n\n try {\n const struct = mockResponse.responseData;\n\n logger.debug(\"[ProtobufCommunicator] extracting response data directly from protobuf\");\n\n if (struct.fields && struct.fields[\"response\"]) {\n const responseValue = Value.toJson(struct.fields[\"response\"]);\n if (responseValue) {\n logger.debug(\n \"[ProtobufCommunicator] Extracted response data:\",\n JSON.stringify(responseValue, null, 2),\n );\n return responseValue as Record<string, unknown>;\n }\n }\n\n return {};\n } catch (error) {\n logger.error(\"[ProtobufCommunicator] failed to extract response data:\", error);\n throw error;\n }\n }\n\n private generateRequestId(): string {\n return Math.random().toString(36).slice(2, 11);\n }\n\n private cleanSpan(data: any): any {\n if (data === null || data === undefined) {\n return null;\n }\n\n if (Array.isArray(data)) {\n return data.map((item) => this.cleanSpan(item)).filter((item) => item !== undefined);\n }\n\n if (typeof data === \"object\") {\n const cleaned: any = {};\n for (const [key, value] of Object.entries(data)) {\n if (value !== undefined) {\n cleaned[key] = this.cleanSpan(value);\n }\n }\n return cleaned;\n }\n\n return data;\n }\n\n disconnect(): void {\n if (this.client) {\n this.client.destroy();\n this.client = null;\n }\n }\n}\n","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AbstractAsyncHooksContextManager = void 0;\nconst events_1 = require(\"events\");\nconst ADD_LISTENER_METHODS = [\n 'addListener',\n 'on',\n 'once',\n 'prependListener',\n 'prependOnceListener',\n];\nclass AbstractAsyncHooksContextManager {\n constructor() {\n this._kOtListeners = Symbol('OtListeners');\n this._wrapped = false;\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(context, target) {\n if (target instanceof events_1.EventEmitter) {\n return this._bindEventEmitter(context, target);\n }\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n _bindFunction(context, target) {\n const manager = this;\n const contextWrapper = function (...args) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n /**\n * It isn't possible to tell Typescript that contextWrapper is the same as T\n * so we forced to cast as any here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return contextWrapper;\n }\n /**\n * By default, EventEmitter call their callback with their context, which we do\n * not want, instead we will bind a specific context to all callbacks that\n * go through it.\n * @param context the context we want to bind\n * @param ee EventEmitter an instance of EventEmitter to patch\n */\n _bindEventEmitter(context, ee) {\n const map = this._getPatchMap(ee);\n if (map !== undefined)\n return ee;\n this._createPatchMap(ee);\n // patch methods that add a listener to propagate context\n ADD_LISTENER_METHODS.forEach(methodName => {\n if (ee[methodName] === undefined)\n return;\n ee[methodName] = this._patchAddListener(ee, ee[methodName], context);\n });\n // patch methods that remove a listener\n if (typeof ee.removeListener === 'function') {\n ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);\n }\n if (typeof ee.off === 'function') {\n ee.off = this._patchRemoveListener(ee, ee.off);\n }\n // patch method that remove all listeners\n if (typeof ee.removeAllListeners === 'function') {\n ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners);\n }\n return ee;\n }\n /**\n * Patch methods that remove a given listener so that we match the \"patched\"\n * version of that listener (the one that propagate context).\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n _patchRemoveListener(ee, original) {\n const contextManager = this;\n return function (event, listener) {\n var _a;\n const events = (_a = contextManager._getPatchMap(ee)) === null || _a === void 0 ? void 0 : _a[event];\n if (events === undefined) {\n return original.call(this, event, listener);\n }\n const patchedListener = events.get(listener);\n return original.call(this, event, patchedListener || listener);\n };\n }\n /**\n * Patch methods that remove all listeners so we remove our\n * internal references for a given event.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n _patchRemoveAllListeners(ee, original) {\n const contextManager = this;\n return function (event) {\n const map = contextManager._getPatchMap(ee);\n if (map !== undefined) {\n if (arguments.length === 0) {\n contextManager._createPatchMap(ee);\n }\n else if (map[event] !== undefined) {\n delete map[event];\n }\n }\n return original.apply(this, arguments);\n };\n }\n /**\n * Patch methods on an event emitter instance that can add listeners so we\n * can force them to propagate a given context.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n * @param [context] context to propagate when calling listeners\n */\n _patchAddListener(ee, original, context) {\n const contextManager = this;\n return function (event, listener) {\n /**\n * This check is required to prevent double-wrapping the listener.\n * The implementation for ee.once wraps the listener and calls ee.on.\n * Without this check, we would wrap that wrapped listener.\n * This causes an issue because ee.removeListener depends on the onceWrapper\n * to properly remove the listener. If we wrap their wrapper, we break\n * that detection.\n */\n if (contextManager._wrapped) {\n return original.call(this, event, listener);\n }\n let map = contextManager._getPatchMap(ee);\n if (map === undefined) {\n map = contextManager._createPatchMap(ee);\n }\n let listeners = map[event];\n if (listeners === undefined) {\n listeners = new WeakMap();\n map[event] = listeners;\n }\n const patchedListener = contextManager.bind(context, listener);\n // store a weak reference of the user listener to ours\n listeners.set(listener, patchedListener);\n /**\n * See comment at the start of this function for the explanation of this property.\n */\n contextManager._wrapped = true;\n try {\n return original.call(this, event, patchedListener);\n }\n finally {\n contextManager._wrapped = false;\n }\n };\n }\n _createPatchMap(ee) {\n const map = Object.create(null);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ee[this._kOtListeners] = map;\n return map;\n }\n _getPatchMap(ee) {\n return ee[this._kOtListeners];\n }\n}\nexports.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager;\n//# sourceMappingURL=AbstractAsyncHooksContextManager.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AsyncHooksContextManager = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst asyncHooks = require(\"async_hooks\");\nconst AbstractAsyncHooksContextManager_1 = require(\"./AbstractAsyncHooksContextManager\");\nclass AsyncHooksContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {\n constructor() {\n super();\n this._contexts = new Map();\n this._stack = [];\n this._asyncHook = asyncHooks.createHook({\n init: this._init.bind(this),\n before: this._before.bind(this),\n after: this._after.bind(this),\n destroy: this._destroy.bind(this),\n promiseResolve: this._destroy.bind(this),\n });\n }\n active() {\n var _a;\n return (_a = this._stack[this._stack.length - 1]) !== null && _a !== void 0 ? _a : api_1.ROOT_CONTEXT;\n }\n with(context, fn, thisArg, ...args) {\n this._enterContext(context);\n try {\n return fn.call(thisArg, ...args);\n }\n finally {\n this._exitContext();\n }\n }\n enable() {\n this._asyncHook.enable();\n return this;\n }\n disable() {\n this._asyncHook.disable();\n this._contexts.clear();\n this._stack = [];\n return this;\n }\n /**\n * Init hook will be called when userland create a async context, setting the\n * context as the current one if it exist.\n * @param uid id of the async context\n * @param type the resource type\n */\n _init(uid, type) {\n // ignore TIMERWRAP as they combine timers with same timeout which can lead to\n // false context propagation. TIMERWRAP has been removed in node 11\n // every timer has it's own `Timeout` resource anyway which is used to propagete\n // context.\n if (type === 'TIMERWRAP')\n return;\n const context = this._stack[this._stack.length - 1];\n if (context !== undefined) {\n this._contexts.set(uid, context);\n }\n }\n /**\n * Destroy hook will be called when a given context is no longer used so we can\n * remove its attached context.\n * @param uid uid of the async context\n */\n _destroy(uid) {\n this._contexts.delete(uid);\n }\n /**\n * Before hook is called just before executing a async context.\n * @param uid uid of the async context\n */\n _before(uid) {\n const context = this._contexts.get(uid);\n if (context !== undefined) {\n this._enterContext(context);\n }\n }\n /**\n * After hook is called just after completing the execution of a async context.\n */\n _after() {\n this._exitContext();\n }\n /**\n * Set the given context as active\n */\n _enterContext(context) {\n this._stack.push(context);\n }\n /**\n * Remove the context at the root of the stack\n */\n _exitContext() {\n this._stack.pop();\n }\n}\nexports.AsyncHooksContextManager = AsyncHooksContextManager;\n//# sourceMappingURL=AsyncHooksContextManager.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AsyncLocalStorageContextManager = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst async_hooks_1 = require(\"async_hooks\");\nconst AbstractAsyncHooksContextManager_1 = require(\"./AbstractAsyncHooksContextManager\");\nclass AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {\n constructor() {\n super();\n this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();\n }\n active() {\n var _a;\n return (_a = this._asyncLocalStorage.getStore()) !== null && _a !== void 0 ? _a : api_1.ROOT_CONTEXT;\n }\n with(context, fn, thisArg, ...args) {\n const cb = thisArg == null ? fn : fn.bind(thisArg);\n return this._asyncLocalStorage.run(context, cb, ...args);\n }\n enable() {\n return this;\n }\n disable() {\n this._asyncLocalStorage.disable();\n return this;\n }\n}\nexports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager;\n//# sourceMappingURL=AsyncLocalStorageContextManager.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./AsyncHooksContextManager\"), exports);\n__exportStar(require(\"./AsyncLocalStorageContextManager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.B3_DEBUG_FLAG_KEY = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\n/** shared context for storing an extracted b3 debug flag */\nexports.B3_DEBUG_FLAG_KEY = (0, api_1.createContextKey)('OpenTelemetry Context Key B3 Debug Flag');\n//# sourceMappingURL=common.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.X_B3_FLAGS = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_SAMPLED = exports.X_B3_SPAN_ID = exports.X_B3_TRACE_ID = exports.B3_CONTEXT_HEADER = void 0;\n/** B3 single-header key */\nexports.B3_CONTEXT_HEADER = 'b3';\n/* b3 multi-header keys */\nexports.X_B3_TRACE_ID = 'x-b3-traceid';\nexports.X_B3_SPAN_ID = 'x-b3-spanid';\nexports.X_B3_SAMPLED = 'x-b3-sampled';\nexports.X_B3_PARENT_SPAN_ID = 'x-b3-parentspanid';\nexports.X_B3_FLAGS = 'x-b3-flags';\n//# sourceMappingURL=constants.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.B3MultiPropagator = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst common_1 = require(\"./common\");\nconst constants_1 = require(\"./constants\");\nconst VALID_SAMPLED_VALUES = new Set([true, 'true', 'True', '1', 1]);\nconst VALID_UNSAMPLED_VALUES = new Set([false, 'false', 'False', '0', 0]);\nfunction isValidSampledValue(sampled) {\n return sampled === api_1.TraceFlags.SAMPLED || sampled === api_1.TraceFlags.NONE;\n}\nfunction parseHeader(header) {\n return Array.isArray(header) ? header[0] : header;\n}\nfunction getHeaderValue(carrier, getter, key) {\n const header = getter.get(carrier, key);\n return parseHeader(header);\n}\nfunction getTraceId(carrier, getter) {\n const traceId = getHeaderValue(carrier, getter, constants_1.X_B3_TRACE_ID);\n if (typeof traceId === 'string') {\n return traceId.padStart(32, '0');\n }\n return '';\n}\nfunction getSpanId(carrier, getter) {\n const spanId = getHeaderValue(carrier, getter, constants_1.X_B3_SPAN_ID);\n if (typeof spanId === 'string') {\n return spanId;\n }\n return '';\n}\nfunction getDebug(carrier, getter) {\n const debug = getHeaderValue(carrier, getter, constants_1.X_B3_FLAGS);\n return debug === '1' ? '1' : undefined;\n}\nfunction getTraceFlags(carrier, getter) {\n const traceFlags = getHeaderValue(carrier, getter, constants_1.X_B3_SAMPLED);\n const debug = getDebug(carrier, getter);\n if (debug === '1' || VALID_SAMPLED_VALUES.has(traceFlags)) {\n return api_1.TraceFlags.SAMPLED;\n }\n if (traceFlags === undefined || VALID_UNSAMPLED_VALUES.has(traceFlags)) {\n return api_1.TraceFlags.NONE;\n }\n // This indicates to isValidSampledValue that this is not valid\n return;\n}\n/**\n * Propagator for the B3 multiple-header HTTP format.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nclass B3MultiPropagator {\n inject(context, carrier, setter) {\n const spanContext = api_1.trace.getSpanContext(context);\n if (!spanContext ||\n !(0, api_1.isSpanContextValid)(spanContext) ||\n (0, core_1.isTracingSuppressed)(context))\n return;\n const debug = context.getValue(common_1.B3_DEBUG_FLAG_KEY);\n setter.set(carrier, constants_1.X_B3_TRACE_ID, spanContext.traceId);\n setter.set(carrier, constants_1.X_B3_SPAN_ID, spanContext.spanId);\n // According to the B3 spec, if the debug flag is set,\n // the sampled flag shouldn't be propagated as well.\n if (debug === '1') {\n setter.set(carrier, constants_1.X_B3_FLAGS, debug);\n }\n else if (spanContext.traceFlags !== undefined) {\n // We set the header only if there is an existing sampling decision.\n // Otherwise we will omit it => Absent.\n setter.set(carrier, constants_1.X_B3_SAMPLED, (api_1.TraceFlags.SAMPLED & spanContext.traceFlags) === api_1.TraceFlags.SAMPLED\n ? '1'\n : '0');\n }\n }\n extract(context, carrier, getter) {\n const traceId = getTraceId(carrier, getter);\n const spanId = getSpanId(carrier, getter);\n const traceFlags = getTraceFlags(carrier, getter);\n const debug = getDebug(carrier, getter);\n if ((0, api_1.isValidTraceId)(traceId) &&\n (0, api_1.isValidSpanId)(spanId) &&\n isValidSampledValue(traceFlags)) {\n context = context.setValue(common_1.B3_DEBUG_FLAG_KEY, debug);\n return api_1.trace.setSpanContext(context, {\n traceId,\n spanId,\n isRemote: true,\n traceFlags,\n });\n }\n return context;\n }\n fields() {\n return [\n constants_1.X_B3_TRACE_ID,\n constants_1.X_B3_SPAN_ID,\n constants_1.X_B3_FLAGS,\n constants_1.X_B3_SAMPLED,\n constants_1.X_B3_PARENT_SPAN_ID,\n ];\n }\n}\nexports.B3MultiPropagator = B3MultiPropagator;\n//# sourceMappingURL=B3MultiPropagator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.B3SinglePropagator = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst common_1 = require(\"./common\");\nconst constants_1 = require(\"./constants\");\nconst B3_CONTEXT_REGEX = /((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/;\nconst PADDING = '0'.repeat(16);\nconst SAMPLED_VALUES = new Set(['d', '1']);\nconst DEBUG_STATE = 'd';\nfunction convertToTraceId128(traceId) {\n return traceId.length === 32 ? traceId : `${PADDING}${traceId}`;\n}\nfunction convertToTraceFlags(samplingState) {\n if (samplingState && SAMPLED_VALUES.has(samplingState)) {\n return api_1.TraceFlags.SAMPLED;\n }\n return api_1.TraceFlags.NONE;\n}\n/**\n * Propagator for the B3 single-header HTTP format.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nclass B3SinglePropagator {\n inject(context, carrier, setter) {\n const spanContext = api_1.trace.getSpanContext(context);\n if (!spanContext ||\n !(0, api_1.isSpanContextValid)(spanContext) ||\n (0, core_1.isTracingSuppressed)(context))\n return;\n const samplingState = context.getValue(common_1.B3_DEBUG_FLAG_KEY) || spanContext.traceFlags & 0x1;\n const value = `${spanContext.traceId}-${spanContext.spanId}-${samplingState}`;\n setter.set(carrier, constants_1.B3_CONTEXT_HEADER, value);\n }\n extract(context, carrier, getter) {\n const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);\n const b3Context = Array.isArray(header) ? header[0] : header;\n if (typeof b3Context !== 'string')\n return context;\n const match = b3Context.match(B3_CONTEXT_REGEX);\n if (!match)\n return context;\n const [, extractedTraceId, spanId, samplingState] = match;\n const traceId = convertToTraceId128(extractedTraceId);\n if (!(0, api_1.isValidTraceId)(traceId) || !(0, api_1.isValidSpanId)(spanId))\n return context;\n const traceFlags = convertToTraceFlags(samplingState);\n if (samplingState === DEBUG_STATE) {\n context = context.setValue(common_1.B3_DEBUG_FLAG_KEY, samplingState);\n }\n return api_1.trace.setSpanContext(context, {\n traceId,\n spanId,\n isRemote: true,\n traceFlags,\n });\n }\n fields() {\n return [constants_1.B3_CONTEXT_HEADER];\n }\n}\nexports.B3SinglePropagator = B3SinglePropagator;\n//# sourceMappingURL=B3SinglePropagator.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.B3InjectEncoding = void 0;\n/** Enumeration of B3 inject encodings */\nvar B3InjectEncoding;\n(function (B3InjectEncoding) {\n B3InjectEncoding[B3InjectEncoding[\"SINGLE_HEADER\"] = 0] = \"SINGLE_HEADER\";\n B3InjectEncoding[B3InjectEncoding[\"MULTI_HEADER\"] = 1] = \"MULTI_HEADER\";\n})(B3InjectEncoding = exports.B3InjectEncoding || (exports.B3InjectEncoding = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.B3Propagator = void 0;\nconst core_1 = require(\"@opentelemetry/core\");\nconst B3MultiPropagator_1 = require(\"./B3MultiPropagator\");\nconst B3SinglePropagator_1 = require(\"./B3SinglePropagator\");\nconst constants_1 = require(\"./constants\");\nconst types_1 = require(\"./types\");\n/**\n * Propagator that extracts B3 context in both single and multi-header variants,\n * with configurable injection format defaulting to B3 single-header. Due to\n * the asymmetry in injection and extraction formats this is not suitable to\n * be implemented as a composite propagator.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nclass B3Propagator {\n constructor(config = {}) {\n this._b3MultiPropagator = new B3MultiPropagator_1.B3MultiPropagator();\n this._b3SinglePropagator = new B3SinglePropagator_1.B3SinglePropagator();\n if (config.injectEncoding === types_1.B3InjectEncoding.MULTI_HEADER) {\n this._inject = this._b3MultiPropagator.inject;\n this._fields = this._b3MultiPropagator.fields();\n }\n else {\n this._inject = this._b3SinglePropagator.inject;\n this._fields = this._b3SinglePropagator.fields();\n }\n }\n inject(context, carrier, setter) {\n if ((0, core_1.isTracingSuppressed)(context)) {\n return;\n }\n this._inject(context, carrier, setter);\n }\n extract(context, carrier, getter) {\n const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);\n const b3Context = Array.isArray(header) ? header[0] : header;\n if (b3Context) {\n return this._b3SinglePropagator.extract(context, carrier, getter);\n }\n else {\n return this._b3MultiPropagator.extract(context, carrier, getter);\n }\n }\n fields() {\n return this._fields;\n }\n}\nexports.B3Propagator = B3Propagator;\n//# sourceMappingURL=B3Propagator.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./B3Propagator\"), exports);\n__exportStar(require(\"./constants\"), exports);\n__exportStar(require(\"./types\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExceptionEventName = void 0;\n// Event name definitions\nexports.ExceptionEventName = 'exception';\n//# sourceMappingURL=enums.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Span = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst enums_1 = require(\"./enums\");\n/**\n * This class represents a span.\n */\nclass Span {\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(parentTracer, context, spanName, spanContext, kind, parentSpanId, links = [], startTime, _deprecatedClock // keeping this argument even though it is unused to ensure backwards compatibility\n ) {\n this.attributes = {};\n this.links = [];\n this.events = [];\n this._droppedAttributesCount = 0;\n this._droppedEventsCount = 0;\n this._droppedLinksCount = 0;\n this.status = {\n code: api_1.SpanStatusCode.UNSET,\n };\n this.endTime = [0, 0];\n this._ended = false;\n this._duration = [-1, -1];\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n const now = Date.now();\n this._performanceStartTime = core_1.otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + (0, core_1.getTimeOrigin)());\n this._startTimeProvided = startTime != null;\n this.startTime = this._getTime(startTime !== null && startTime !== void 0 ? startTime : now);\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n }\n spanContext() {\n return this._spanContext;\n }\n setAttribute(key, value) {\n if (value == null || this._isSpanEnded())\n return this;\n if (key.length === 0) {\n api_1.diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!(0, core_1.isAttributeValue)(value)) {\n api_1.diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n if (Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n setAttributes(attributes) {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\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(name, attributesOrStartTime, timeStamp) {\n if (this._isSpanEnded())\n return this;\n if (this._spanLimits.eventCountLimit === 0) {\n api_1.diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit) {\n api_1.diag.warn('Dropping extra events.');\n this.events.shift();\n this._droppedEventsCount++;\n }\n if ((0, core_1.isTimeInput)(attributesOrStartTime)) {\n if (!(0, core_1.isTimeInput)(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime);\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n setStatus(status) {\n if (this._isSpanEnded())\n return this;\n this.status = status;\n return this;\n }\n updateName(name) {\n if (this._isSpanEnded())\n return this;\n this.name = name;\n return this;\n }\n end(endTime) {\n if (this._isSpanEnded()) {\n api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);\n return;\n }\n this._ended = true;\n this.endTime = this._getTime(endTime);\n this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime);\n if (this._duration[0] < 0) {\n api_1.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);\n this.endTime = this.startTime.slice();\n this._duration = [0, 0];\n }\n this._spanProcessor.onEnd(this);\n }\n _getTime(inp) {\n if (typeof inp === 'number' && inp < core_1.otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return (0, core_1.hrTime)(inp + this._performanceOffset);\n }\n if (typeof inp === 'number') {\n return (0, core_1.millisToHrTime)(inp);\n }\n if (inp instanceof Date) {\n return (0, core_1.millisToHrTime)(inp.getTime());\n }\n if ((0, core_1.isTimeInputHrTime)(inp)) {\n return inp;\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 (0, core_1.millisToHrTime)(Date.now());\n }\n const msDuration = core_1.otperformance.now() - this._performanceStartTime;\n return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration));\n }\n isRecording() {\n return this._ended === false;\n }\n recordException(exception, time) {\n const attributes = {};\n if (typeof exception === 'string') {\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n }\n else if (exception) {\n if (exception.code) {\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n }\n else if (exception.name) {\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n // these are minimum requirements from spec\n if (attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE]) {\n this.addEvent(enums_1.ExceptionEventName, attributes, time);\n }\n else {\n api_1.diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n get duration() {\n return this._duration;\n }\n get ended() {\n return this._ended;\n }\n get droppedAttributesCount() {\n return this._droppedAttributesCount;\n }\n get droppedEventsCount() {\n return this._droppedEventsCount;\n }\n get droppedLinksCount() {\n return this._droppedLinksCount;\n }\n _isSpanEnded() {\n if (this._ended) {\n api_1.diag.warn(`Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);\n }\n return this._ended;\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 _truncateToLimitUtil(value, limit) {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\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 trucated 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 _truncateToSize(value) {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n // Array of strings\n if (Array.isArray(value)) {\n return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);\n }\n // Other types, no need to apply value length limit\n return value;\n }\n}\nexports.Span = Span;\n//# sourceMappingURL=Span.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SamplingDecision = void 0;\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nvar SamplingDecision;\n(function (SamplingDecision) {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n SamplingDecision[SamplingDecision[\"NOT_RECORD\"] = 0] = \"NOT_RECORD\";\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD\"] = 1] = \"RECORD\";\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD_AND_SAMPLED\"] = 2] = \"RECORD_AND_SAMPLED\";\n})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));\n//# sourceMappingURL=Sampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AlwaysOffSampler = void 0;\nconst Sampler_1 = require(\"../Sampler\");\n/** Sampler that samples no traces. */\nclass AlwaysOffSampler {\n shouldSample() {\n return {\n decision: Sampler_1.SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return 'AlwaysOffSampler';\n }\n}\nexports.AlwaysOffSampler = AlwaysOffSampler;\n//# sourceMappingURL=AlwaysOffSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AlwaysOnSampler = void 0;\nconst Sampler_1 = require(\"../Sampler\");\n/** Sampler that samples all traces. */\nclass AlwaysOnSampler {\n shouldSample() {\n return {\n decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n toString() {\n return 'AlwaysOnSampler';\n }\n}\nexports.AlwaysOnSampler = AlwaysOnSampler;\n//# sourceMappingURL=AlwaysOnSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ParentBasedSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst AlwaysOffSampler_1 = require(\"./AlwaysOffSampler\");\nconst AlwaysOnSampler_1 = require(\"./AlwaysOnSampler\");\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nclass ParentBasedSampler {\n constructor(config) {\n var _a, _b, _c, _d;\n this._root = config.root;\n if (!this._root) {\n (0, core_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured'));\n this._root = new AlwaysOnSampler_1.AlwaysOnSampler();\n }\n this._remoteParentSampled =\n (_a = config.remoteParentSampled) !== null && _a !== void 0 ? _a : new AlwaysOnSampler_1.AlwaysOnSampler();\n this._remoteParentNotSampled =\n (_b = config.remoteParentNotSampled) !== null && _b !== void 0 ? _b : new AlwaysOffSampler_1.AlwaysOffSampler();\n this._localParentSampled =\n (_c = config.localParentSampled) !== null && _c !== void 0 ? _c : new AlwaysOnSampler_1.AlwaysOnSampler();\n this._localParentNotSampled =\n (_d = config.localParentNotSampled) !== null && _d !== void 0 ? _d : new AlwaysOffSampler_1.AlwaysOffSampler();\n }\n shouldSample(context, traceId, spanName, spanKind, attributes, links) {\n const parentContext = api_1.trace.getSpanContext(context);\n if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {\n return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n toString() {\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}\nexports.ParentBasedSampler = ParentBasedSampler;\n//# sourceMappingURL=ParentBasedSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TraceIdRatioBasedSampler = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst Sampler_1 = require(\"../Sampler\");\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nclass TraceIdRatioBasedSampler {\n constructor(_ratio = 0) {\n this._ratio = _ratio;\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n shouldSample(context, traceId) {\n return {\n decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound\n ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED\n : Sampler_1.SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n _normalize(ratio) {\n if (typeof ratio !== 'number' || isNaN(ratio))\n return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n _accumulate(traceId) {\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}\nexports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;\n//# sourceMappingURL=TraceIdRatioBasedSampler.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst AlwaysOffSampler_1 = require(\"./sampler/AlwaysOffSampler\");\nconst AlwaysOnSampler_1 = require(\"./sampler/AlwaysOnSampler\");\nconst ParentBasedSampler_1 = require(\"./sampler/ParentBasedSampler\");\nconst TraceIdRatioBasedSampler_1 = require(\"./sampler/TraceIdRatioBasedSampler\");\nconst env = (0, core_1.getEnv)();\nconst FALLBACK_OTEL_TRACES_SAMPLER = core_1.TracesSamplerValues.AlwaysOn;\nconst DEFAULT_RATIO = 1;\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// 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\nfunction loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(env),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit: (0, core_1.getEnv)().OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: (0, core_1.getEnv)().OTEL_ATTRIBUTE_COUNT_LIMIT,\n },\n spanLimits: {\n attributeValueLengthLimit: (0, core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: (0, core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,\n linkCountLimit: (0, core_1.getEnv)().OTEL_SPAN_LINK_COUNT_LIMIT,\n eventCountLimit: (0, core_1.getEnv)().OTEL_SPAN_EVENT_COUNT_LIMIT,\n attributePerEventCountLimit: (0, core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n attributePerLinkCountLimit: (0, core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n },\n };\n}\nexports.loadDefaultConfig = loadDefaultConfig;\n/**\n * Based on environment, builds a sampler, complies with specification.\n * @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment\n */\nfunction buildSamplerFromEnv(environment = (0, core_1.getEnv)()) {\n switch (environment.OTEL_TRACES_SAMPLER) {\n case core_1.TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler_1.AlwaysOnSampler();\n case core_1.TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler_1.AlwaysOffSampler();\n case core_1.TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler_1.ParentBasedSampler({\n root: new AlwaysOnSampler_1.AlwaysOnSampler(),\n });\n case core_1.TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler_1.ParentBasedSampler({\n root: new AlwaysOffSampler_1.AlwaysOffSampler(),\n });\n case core_1.TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment));\n case core_1.TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler_1.ParentBasedSampler({\n root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment)),\n });\n default:\n api_1.diag.error(`OTEL_TRACES_SAMPLER value \"${environment.OTEL_TRACES_SAMPLER} invalid, defaulting to ${FALLBACK_OTEL_TRACES_SAMPLER}\".`);\n return new AlwaysOnSampler_1.AlwaysOnSampler();\n }\n}\nexports.buildSamplerFromEnv = buildSamplerFromEnv;\nfunction getSamplerProbabilityFromEnv(environment) {\n if (environment.OTEL_TRACES_SAMPLER_ARG === undefined ||\n environment.OTEL_TRACES_SAMPLER_ARG === '') {\n api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);\n return DEFAULT_RATIO;\n }\n const probability = Number(environment.OTEL_TRACES_SAMPLER_ARG);\n if (isNaN(probability)) {\n api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${DEFAULT_RATIO}.`);\n return DEFAULT_RATIO;\n }\n if (probability < 0 || probability > 1) {\n api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);\n return DEFAULT_RATIO;\n }\n return probability;\n}\n//# sourceMappingURL=config.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reconfigureLimits = exports.mergeConfig = void 0;\nconst config_1 = require(\"./config\");\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nfunction mergeConfig(userConfig) {\n const perInstanceDefaults = {\n sampler: (0, config_1.buildSamplerFromEnv)(),\n };\n const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)();\n const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);\n target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});\n target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});\n return target;\n}\nexports.mergeConfig = mergeConfig;\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 */\nfunction reconfigureLimits(userConfig) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n const parsedEnvConfig = (0, core_1.getEnvWithoutDefaults)();\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 (_f = (_e = (_d = (_b = (_a = userConfig.spanLimits) === null || _a === void 0 ? void 0 : _a.attributeCountLimit) !== null && _b !== void 0 ? _b : (_c = userConfig.generalLimits) === null || _c === void 0 ? void 0 : _c.attributeCountLimit) !== null && _d !== void 0 ? _d : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) !== null && _e !== void 0 ? _e : parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT) !== null && _f !== void 0 ? _f : core_1.DEFAULT_ATTRIBUTE_COUNT_LIMIT;\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 (_m = (_l = (_k = (_h = (_g = userConfig.spanLimits) === null || _g === void 0 ? void 0 : _g.attributeValueLengthLimit) !== null && _h !== void 0 ? _h : (_j = userConfig.generalLimits) === null || _j === void 0 ? void 0 : _j.attributeValueLengthLimit) !== null && _k !== void 0 ? _k : parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _l !== void 0 ? _l : parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT) !== null && _m !== void 0 ? _m : core_1.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n return Object.assign({}, userConfig, { spanLimits });\n}\nexports.reconfigureLimits = reconfigureLimits;\n//# sourceMappingURL=utility.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BatchSpanProcessorBase = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nclass BatchSpanProcessorBase {\n constructor(_exporter, config) {\n this._exporter = _exporter;\n this._isExporting = false;\n this._finishedSpans = [];\n this._droppedSpansCount = 0;\n const env = (0, core_1.getEnv)();\n this._maxExportBatchSize =\n typeof (config === null || config === void 0 ? void 0 : config.maxExportBatchSize) === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof (config === null || config === void 0 ? void 0 : config.maxQueueSize) === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof (config === null || config === void 0 ? void 0 : config.scheduledDelayMillis) === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof (config === null || config === void 0 ? void 0 : config.exportTimeoutMillis) === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);\n if (this._maxExportBatchSize > this._maxQueueSize) {\n api_1.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n forceFlush() {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n // does nothing.\n onStart(_span, _parentContext) { }\n onEnd(span) {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {\n return;\n }\n this._addToBuffer(span);\n }\n shutdown() {\n return this._shutdownOnce.call();\n }\n _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 /** Add a span in the buffer. */\n _addToBuffer(span) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n if (this._droppedSpansCount === 0) {\n api_1.diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n return;\n }\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);\n this._droppedSpansCount = 0;\n }\n this._finishedSpans.push(span);\n this._maybeStartTimer();\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 _flushAll() {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);\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 _flushOneBatch() {\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 api_1.context.with((0, core_1.suppressTracing)(api_1.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 const spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n const doExport = () => this._exporter.export(spans, result => {\n var _a;\n clearTimeout(timer);\n if (result.code === core_1.ExportResultCode.SUCCESS) {\n resolve();\n }\n else {\n reject((_a = result.error) !== null && _a !== void 0 ? _a : new Error('BatchSpanProcessor: span export failed'));\n }\n });\n const pendingResources = spans\n .map(span => span.resource)\n .filter(resource => resource.asyncAttributesPending);\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources.length === 0) {\n doExport();\n }\n else {\n Promise.all(pendingResources.map(resource => { var _a; return (_a = resource.waitForAsyncAttributes) === null || _a === void 0 ? void 0 : _a.call(resource); })).then(doExport, err => {\n (0, core_1.globalErrorHandler)(err);\n reject(err);\n });\n }\n });\n });\n }\n _maybeStartTimer() {\n if (this._isExporting)\n return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .then(() => {\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 (0, core_1.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)\n return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n (0, core_1.unrefTimer)(this._timer);\n }\n _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n}\nexports.BatchSpanProcessorBase = BatchSpanProcessorBase;\n//# sourceMappingURL=BatchSpanProcessorBase.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BatchSpanProcessor = void 0;\nconst BatchSpanProcessorBase_1 = require(\"../../../export/BatchSpanProcessorBase\");\nclass BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {\n onShutdown() { }\n}\nexports.BatchSpanProcessor = BatchSpanProcessor;\n//# sourceMappingURL=BatchSpanProcessor.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RandomIdGenerator = void 0;\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\nclass RandomIdGenerator {\n constructor() {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n this.generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n this.generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n }\n}\nexports.RandomIdGenerator = RandomIdGenerator;\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes) {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n }\n else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n//# sourceMappingURL=RandomIdGenerator.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./export/BatchSpanProcessor\"), exports);\n__exportStar(require(\"./RandomIdGenerator\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./node\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Tracer = void 0;\nconst api = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst Span_1 = require(\"./Span\");\nconst utility_1 = require(\"./utility\");\nconst platform_1 = require(\"./platform\");\n/**\n * This class represents a basic tracer.\n */\nclass Tracer {\n /**\n * Constructs a new Tracer instance.\n */\n constructor(instrumentationLibrary, config, _tracerProvider) {\n this._tracerProvider = _tracerProvider;\n const localConfig = (0, utility_1.mergeConfig)(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator();\n this.resource = _tracerProvider.resource;\n this.instrumentationLibrary = instrumentationLibrary;\n }\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(name, options = {}, context = api.context.active()) {\n var _a, _b, _c;\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 if ((0, core_1.isTracingSuppressed)(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);\n return nonRecordingSpan;\n }\n const parentSpanContext = parentSpan === null || parentSpan === void 0 ? void 0 : parentSpan.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let traceId;\n let traceState;\n let parentSpanId;\n if (!parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n }\n else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n parentSpanId = parentSpanContext.spanId;\n }\n const spanKind = (_a = options.kind) !== null && _a !== void 0 ? _a : api.SpanKind.INTERNAL;\n const links = ((_b = options.links) !== null && _b !== void 0 ? _b : []).map(link => {\n return {\n context: link.context,\n attributes: (0, core_1.sanitizeAttributes)(link.attributes),\n };\n });\n const attributes = (0, core_1.sanitizeAttributes)(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);\n traceState = (_c = samplingResult.traceState) !== null && _c !== void 0 ? _c : traceState;\n const traceFlags = 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('Recording is off, propagating context in a non-recording span');\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n const span = new Span_1.Span(this, context, name, spanContext, spanKind, parentSpanId, links, options.startTime);\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 = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes));\n span.setAttributes(initAttributes);\n return span;\n }\n startActiveSpan(name, arg2, arg3, arg4) {\n let opts;\n let ctx;\n let fn;\n if (arguments.length < 2) {\n return;\n }\n else if (arguments.length === 2) {\n fn = arg2;\n }\n else if (arguments.length === 3) {\n opts = arg2;\n fn = arg3;\n }\n else {\n opts = arg2;\n ctx = arg3;\n fn = arg4;\n }\n const parentContext = ctx !== null && ctx !== void 0 ? ctx : api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits() {\n return this._generalLimits;\n }\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits() {\n return this._spanLimits;\n }\n getActiveSpanProcessor() {\n return this._tracerProvider.getActiveSpanProcessor();\n }\n}\nexports.Tracer = Tracer;\n//# sourceMappingURL=Tracer.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultServiceName = void 0;\nfunction defaultServiceName() {\n return `unknown_service:${process.argv0}`;\n}\nexports.defaultServiceName = defaultServiceName;\n//# sourceMappingURL=default-service-name.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.normalizeType = exports.normalizeArch = void 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 */\nconst normalizeArch = (nodeArchString) => {\n // Maps from https://nodejs.org/api/os.html#osarch to arch values in spec:\n // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/host.md\n switch (nodeArchString) {\n case 'arm':\n return 'arm32';\n case 'ppc':\n return 'ppc32';\n case 'x64':\n return 'amd64';\n default:\n return nodeArchString;\n }\n};\nexports.normalizeArch = normalizeArch;\nconst normalizeType = (nodePlatform) => {\n // Maps from https://nodejs.org/api/os.html#osplatform to arch values in spec:\n // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/os.md\n switch (nodePlatform) {\n case 'sunos':\n return 'solaris';\n case 'win32':\n return 'windows';\n default:\n return nodePlatform;\n }\n};\nexports.normalizeType = normalizeType;\n//# sourceMappingURL=utils.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.execAsync = void 0;\nconst child_process = require(\"child_process\");\nconst util = require(\"util\");\nexports.execAsync = util.promisify(child_process.exec);\n//# sourceMappingURL=execAsync.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 0;\nconst execAsync_1 = require(\"./execAsync\");\nconst api_1 = require(\"@opentelemetry/api\");\nasync function getMachineId() {\n try {\n const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c \"IOPlatformExpertDevice\"');\n const idLine = result.stdout\n .split('\\n')\n .find(line => line.includes('IOPlatformUUID'));\n if (!idLine) {\n return '';\n }\n const parts = idLine.split('\" = \"');\n if (parts.length === 2) {\n return parts[1].slice(0, -1);\n }\n }\n catch (e) {\n api_1.diag.debug(`error reading machine id: ${e}`);\n }\n return '';\n}\nexports.getMachineId = getMachineId;\n//# sourceMappingURL=getMachineId-darwin.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 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 */\nconst fs_1 = require(\"fs\");\nconst api_1 = require(\"@opentelemetry/api\");\nasync function getMachineId() {\n const paths = ['/etc/machine-id', '/var/lib/dbus/machine-id'];\n for (const path of paths) {\n try {\n const result = await fs_1.promises.readFile(path, { encoding: 'utf8' });\n return result.trim();\n }\n catch (e) {\n api_1.diag.debug(`error reading machine id: ${e}`);\n }\n }\n return '';\n}\nexports.getMachineId = getMachineId;\n//# sourceMappingURL=getMachineId-linux.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 0;\nconst fs_1 = require(\"fs\");\nconst execAsync_1 = require(\"./execAsync\");\nconst api_1 = require(\"@opentelemetry/api\");\nasync function getMachineId() {\n try {\n const result = await fs_1.promises.readFile('/etc/hostid', { encoding: 'utf8' });\n return result.trim();\n }\n catch (e) {\n api_1.diag.debug(`error reading machine id: ${e}`);\n }\n try {\n const result = await (0, execAsync_1.execAsync)('kenv -q smbios.system.uuid');\n return result.stdout.trim();\n }\n catch (e) {\n api_1.diag.debug(`error reading machine id: ${e}`);\n }\n return '';\n}\nexports.getMachineId = getMachineId;\n//# sourceMappingURL=getMachineId-bsd.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 0;\nconst process = require(\"process\");\nconst execAsync_1 = require(\"./execAsync\");\nconst api_1 = require(\"@opentelemetry/api\");\nasync function getMachineId() {\n const args = 'QUERY HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Cryptography /v MachineGuid';\n let command = '%windir%\\\\System32\\\\REG.exe';\n if (process.arch === 'ia32' && 'PROCESSOR_ARCHITEW6432' in process.env) {\n command = '%windir%\\\\sysnative\\\\cmd.exe /c ' + command;\n }\n try {\n const result = await (0, execAsync_1.execAsync)(`${command} ${args}`);\n const parts = result.stdout.split('REG_SZ');\n if (parts.length === 2) {\n return parts[1].trim();\n }\n }\n catch (e) {\n api_1.diag.debug(`error reading machine id: ${e}`);\n }\n return '';\n}\nexports.getMachineId = getMachineId;\n//# sourceMappingURL=getMachineId-win.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nasync function getMachineId() {\n api_1.diag.debug('could not read machine-id: unsupported platform');\n return '';\n}\nexports.getMachineId = getMachineId;\n//# sourceMappingURL=getMachineId-unsupported.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMachineId = void 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 */\nconst process = require(\"process\");\nlet getMachineId;\nexports.getMachineId = getMachineId;\nswitch (process.platform) {\n case 'darwin':\n (exports.getMachineId = getMachineId = require('./getMachineId-darwin').getMachineId);\n break;\n case 'linux':\n (exports.getMachineId = getMachineId = require('./getMachineId-linux').getMachineId);\n break;\n case 'freebsd':\n (exports.getMachineId = getMachineId = require('./getMachineId-bsd').getMachineId);\n break;\n case 'win32':\n (exports.getMachineId = getMachineId = require('./getMachineId-win').getMachineId);\n break;\n default:\n (exports.getMachineId = getMachineId = require('./getMachineId-unsupported').getMachineId);\n}\n//# sourceMappingURL=getMachineId.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hostDetectorSync = void 0;\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst Resource_1 = require(\"../../Resource\");\nconst os_1 = require(\"os\");\nconst utils_1 = require(\"./utils\");\nconst getMachineId_1 = require(\"./machine-id/getMachineId\");\n/**\n * HostDetectorSync detects the resources related to the host current process is\n * running on. Currently only non-cloud-based attributes are included.\n */\nclass HostDetectorSync {\n detect(_config) {\n const attributes = {\n [semantic_conventions_1.SemanticResourceAttributes.HOST_NAME]: (0, os_1.hostname)(),\n [semantic_conventions_1.SemanticResourceAttributes.HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()),\n };\n return new Resource_1.Resource(attributes, this._getAsyncAttributes());\n }\n _getAsyncAttributes() {\n return (0, getMachineId_1.getMachineId)().then(machineId => {\n const attributes = {};\n if (machineId) {\n attributes[semantic_conventions_1.SemanticResourceAttributes.HOST_ID] = machineId;\n }\n return attributes;\n });\n }\n}\nexports.hostDetectorSync = new HostDetectorSync();\n//# sourceMappingURL=HostDetectorSync.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hostDetector = void 0;\nconst HostDetectorSync_1 = require(\"./HostDetectorSync\");\n/**\n * HostDetector detects the resources related to the host current process is\n * running on. Currently only non-cloud-based attributes are included.\n */\nclass HostDetector {\n detect(_config) {\n return Promise.resolve(HostDetectorSync_1.hostDetectorSync.detect(_config));\n }\n}\nexports.hostDetector = new HostDetector();\n//# sourceMappingURL=HostDetector.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.osDetectorSync = void 0;\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst Resource_1 = require(\"../../Resource\");\nconst os_1 = require(\"os\");\nconst utils_1 = require(\"./utils\");\n/**\n * OSDetectorSync detects the resources related to the operating system (OS) on\n * which the process represented by this resource is running.\n */\nclass OSDetectorSync {\n detect(_config) {\n const attributes = {\n [semantic_conventions_1.SemanticResourceAttributes.OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()),\n [semantic_conventions_1.SemanticResourceAttributes.OS_VERSION]: (0, os_1.release)(),\n };\n return new Resource_1.Resource(attributes);\n }\n}\nexports.osDetectorSync = new OSDetectorSync();\n//# sourceMappingURL=OSDetectorSync.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.osDetector = void 0;\nconst OSDetectorSync_1 = require(\"./OSDetectorSync\");\n/**\n * OSDetector detects the resources related to the operating system (OS) on\n * which the process represented by this resource is running.\n */\nclass OSDetector {\n detect(_config) {\n return Promise.resolve(OSDetectorSync_1.osDetectorSync.detect(_config));\n }\n}\nexports.osDetector = new OSDetector();\n//# sourceMappingURL=OSDetector.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.processDetectorSync = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst Resource_1 = require(\"../../Resource\");\nconst os = require(\"os\");\n/**\n * ProcessDetectorSync will be used to detect the resources related current process running\n * and being instrumented from the NodeJS Process module.\n */\nclass ProcessDetectorSync {\n detect(_config) {\n const attributes = {\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_PID]: process.pid,\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_EXECUTABLE_NAME]: process.title,\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_EXECUTABLE_PATH]: process.execPath,\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND_ARGS]: [\n process.argv[0],\n ...process.execArgv,\n ...process.argv.slice(1),\n ],\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]: process.versions.node,\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'nodejs',\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]: 'Node.js',\n };\n if (process.argv.length > 1) {\n attributes[semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND] = process.argv[1];\n }\n try {\n const userInfo = os.userInfo();\n attributes[semantic_conventions_1.SemanticResourceAttributes.PROCESS_OWNER] = userInfo.username;\n }\n catch (e) {\n api_1.diag.debug(`error obtaining process owner: ${e}`);\n }\n return new Resource_1.Resource(attributes);\n }\n}\nexports.processDetectorSync = new ProcessDetectorSync();\n//# sourceMappingURL=ProcessDetectorSync.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.processDetector = void 0;\nconst ProcessDetectorSync_1 = require(\"./ProcessDetectorSync\");\n/**\n * ProcessDetector will be used to detect the resources related current process running\n * and being instrumented from the NodeJS Process module.\n */\nclass ProcessDetector {\n detect(config) {\n return Promise.resolve(ProcessDetectorSync_1.processDetectorSync.detect(config));\n }\n}\nexports.processDetector = new ProcessDetector();\n//# sourceMappingURL=ProcessDetector.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./default-service-name\"), exports);\n__exportStar(require(\"./HostDetector\"), exports);\n__exportStar(require(\"./OSDetector\"), exports);\n__exportStar(require(\"./HostDetectorSync\"), exports);\n__exportStar(require(\"./OSDetectorSync\"), exports);\n__exportStar(require(\"./ProcessDetector\"), exports);\n__exportStar(require(\"./ProcessDetectorSync\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./node\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Resource = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst platform_1 = require(\"./platform\");\n/**\n * A Resource describes the entity for which a signals (metrics or trace) are\n * collected.\n */\nclass Resource {\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 attributes, asyncAttributesPromise) {\n var _a;\n this._attributes = attributes;\n this.asyncAttributesPending = asyncAttributesPromise != null;\n this._syncAttributes = (_a = this._attributes) !== null && _a !== void 0 ? _a : {};\n this._asyncAttributesPromise = asyncAttributesPromise === null || asyncAttributesPromise === void 0 ? void 0 : asyncAttributesPromise.then(asyncAttributes => {\n this._attributes = Object.assign({}, this._attributes, asyncAttributes);\n this.asyncAttributesPending = false;\n return asyncAttributes;\n }, err => {\n api_1.diag.debug(\"a resource's async attributes promise rejected: %s\", err);\n this.asyncAttributesPending = false;\n return {};\n });\n }\n /**\n * Returns an empty Resource\n */\n static empty() {\n return Resource.EMPTY;\n }\n /**\n * Returns a Resource that identifies the SDK in use.\n */\n static default() {\n return new Resource({\n [semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME]: (0, platform_1.defaultServiceName)(),\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE],\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME],\n [semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION],\n });\n }\n get attributes() {\n var _a;\n if (this.asyncAttributesPending) {\n api_1.diag.error('Accessing resource attributes before async attributes settled');\n }\n return (_a = this._attributes) !== null && _a !== void 0 ? _a : {};\n }\n /**\n * Returns a promise that will never be rejected. Resolves when all async attributes have finished being added to\n * this Resource's attributes. This is useful in exporters to block until resource detection\n * has finished.\n */\n async waitForAsyncAttributes() {\n if (this.asyncAttributesPending) {\n await this._asyncAttributesPromise;\n }\n }\n /**\n * Returns a new, merged {@link Resource} by merging the current Resource\n * with the other Resource. In case of a collision, other Resource takes\n * precedence.\n *\n * @param other the Resource that will be merged with this.\n * @returns the newly merged Resource.\n */\n merge(other) {\n var _a;\n if (!other)\n return this;\n // SpanAttributes from other resource overwrite attributes from this resource.\n const mergedSyncAttributes = Object.assign(Object.assign({}, this._syncAttributes), ((_a = other._syncAttributes) !== null && _a !== void 0 ? _a : other.attributes));\n if (!this._asyncAttributesPromise &&\n !other._asyncAttributesPromise) {\n return new Resource(mergedSyncAttributes);\n }\n const mergedAttributesPromise = Promise.all([\n this._asyncAttributesPromise,\n other._asyncAttributesPromise,\n ]).then(([thisAsyncAttributes, otherAsyncAttributes]) => {\n var _a;\n return Object.assign(Object.assign(Object.assign(Object.assign({}, this._syncAttributes), thisAsyncAttributes), ((_a = other._syncAttributes) !== null && _a !== void 0 ? _a : other.attributes)), otherAsyncAttributes);\n });\n return new Resource(mergedSyncAttributes, mergedAttributesPromise);\n }\n}\nexports.Resource = Resource;\nResource.EMPTY = new Resource({});\n//# sourceMappingURL=Resource.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=IResource.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=config.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.browserDetector = void 0;\nconst __1 = require(\"..\");\n/**\n * BrowserDetector will be used to detect the resources related to browser.\n */\nclass BrowserDetector {\n detect(config) {\n return Promise.resolve(__1.browserDetectorSync.detect(config));\n }\n}\nexports.browserDetector = new BrowserDetector();\n//# sourceMappingURL=BrowserDetector.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.envDetectorSync = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst Resource_1 = require(\"../Resource\");\n/**\n * EnvDetectorSync can be used to detect the presence of and create a Resource\n * from the OTEL_RESOURCE_ATTRIBUTES environment variable.\n */\nclass EnvDetectorSync {\n constructor() {\n // Type, attribute keys, and attribute values should not exceed 256 characters.\n this._MAX_LENGTH = 255;\n // OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes.\n this._COMMA_SEPARATOR = ',';\n // OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='.\n this._LABEL_KEY_VALUE_SPLITTER = '=';\n this._ERROR_MESSAGE_INVALID_CHARS = 'should be a ASCII string with a length greater than 0 and not exceed ' +\n this._MAX_LENGTH +\n ' characters.';\n this._ERROR_MESSAGE_INVALID_VALUE = 'should be a ASCII string with a length not exceed ' +\n this._MAX_LENGTH +\n ' characters.';\n }\n /**\n * Returns a {@link Resource} populated with attributes from the\n * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async\n * function to conform to the Detector interface.\n *\n * @param config The resource detection config\n */\n detect(_config) {\n const attributes = {};\n const env = (0, core_1.getEnv)();\n const rawAttributes = env.OTEL_RESOURCE_ATTRIBUTES;\n const serviceName = env.OTEL_SERVICE_NAME;\n if (rawAttributes) {\n try {\n const parsedAttributes = this._parseResourceAttributes(rawAttributes);\n Object.assign(attributes, parsedAttributes);\n }\n catch (e) {\n api_1.diag.debug(`EnvDetector failed: ${e.message}`);\n }\n }\n if (serviceName) {\n attributes[semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME] = serviceName;\n }\n return new Resource_1.Resource(attributes);\n }\n /**\n * Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment\n * variable.\n *\n * OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing\n * the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and\n * paths are accepted as attribute keys. Values may be quoted or unquoted in\n * general. If a value contains whitespaces, =, or \" characters, it must\n * always be quoted.\n *\n * @param rawEnvAttributes The resource attributes as a comma-seperated list\n * of key/value pairs.\n * @returns The sanitized resource attributes.\n */\n _parseResourceAttributes(rawEnvAttributes) {\n if (!rawEnvAttributes)\n return {};\n const attributes = {};\n const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR, -1);\n for (const rawAttribute of rawAttributes) {\n const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER, -1);\n if (keyValuePair.length !== 2) {\n continue;\n }\n let [key, value] = keyValuePair;\n // Leading and trailing whitespaces are trimmed.\n key = key.trim();\n value = value.trim().split(/^\"|\"$/).join('');\n if (!this._isValidAndNotEmpty(key)) {\n throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);\n }\n if (!this._isValid(value)) {\n throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);\n }\n attributes[key] = decodeURIComponent(value);\n }\n return attributes;\n }\n /**\n * Determines whether the given String is a valid printable ASCII string with\n * a length not exceed _MAX_LENGTH characters.\n *\n * @param str The String to be validated.\n * @returns Whether the String is valid.\n */\n _isValid(name) {\n return name.length <= this._MAX_LENGTH && this._isBaggageOctetString(name);\n }\n // https://www.w3.org/TR/baggage/#definition\n _isBaggageOctetString(str) {\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n if (ch < 0x21 || ch === 0x2c || ch === 0x3b || ch === 0x5c || ch > 0x7e) {\n return false;\n }\n }\n return true;\n }\n /**\n * Determines whether the given String is a valid printable ASCII string with\n * a length greater than 0 and not exceed _MAX_LENGTH characters.\n *\n * @param str The String to be validated.\n * @returns Whether the String is valid and not empty.\n */\n _isValidAndNotEmpty(str) {\n return str.length > 0 && this._isValid(str);\n }\n}\nexports.envDetectorSync = new EnvDetectorSync();\n//# sourceMappingURL=EnvDetectorSync.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.envDetector = void 0;\nconst EnvDetectorSync_1 = require(\"./EnvDetectorSync\");\n/**\n * EnvDetector can be used to detect the presence of and create a Resource\n * from the OTEL_RESOURCE_ATTRIBUTES environment variable.\n */\nclass EnvDetector {\n /**\n * Returns a {@link Resource} populated with attributes from the\n * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async\n * function to conform to the Detector interface.\n *\n * @param config The resource detection config\n */\n detect(config) {\n return Promise.resolve(EnvDetectorSync_1.envDetectorSync.detect(config));\n }\n}\nexports.envDetector = new EnvDetector();\n//# sourceMappingURL=EnvDetector.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.browserDetectorSync = void 0;\nconst semantic_conventions_1 = require(\"@opentelemetry/semantic-conventions\");\nconst __1 = require(\"..\");\nconst api_1 = require(\"@opentelemetry/api\");\n/**\n * BrowserDetectorSync will be used to detect the resources related to browser.\n */\nclass BrowserDetectorSync {\n detect(config) {\n const isBrowser = typeof navigator !== 'undefined';\n if (!isBrowser) {\n return __1.Resource.empty();\n }\n const browserResource = {\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'browser',\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]: 'Web Browser',\n [semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]: navigator.userAgent,\n };\n return this._getResourceAttributes(browserResource, config);\n }\n /**\n * Validates process resource attribute map from process variables\n *\n * @param browserResource The un-sanitized resource attributes from process as key/value pairs.\n * @param config: Config\n * @returns The sanitized resource attributes.\n */\n _getResourceAttributes(browserResource, _config) {\n if (browserResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION] === '') {\n api_1.diag.debug('BrowserDetector failed: Unable to find required browser resources. ');\n return __1.Resource.empty();\n }\n else {\n return new __1.Resource(Object.assign({}, browserResource));\n }\n }\n}\nexports.browserDetectorSync = new BrowserDetectorSync();\n//# sourceMappingURL=BrowserDetectorSync.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./BrowserDetector\"), exports);\n__exportStar(require(\"./EnvDetector\"), exports);\n__exportStar(require(\"./BrowserDetectorSync\"), exports);\n__exportStar(require(\"./EnvDetectorSync\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isPromiseLike = void 0;\nconst isPromiseLike = (val) => {\n return (val !== null && typeof val === 'object' && typeof val.then === 'function');\n};\nexports.isPromiseLike = isPromiseLike;\n//# sourceMappingURL=utils.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.detectResourcesSync = exports.detectResources = void 0;\nconst Resource_1 = require(\"./Resource\");\nconst api_1 = require(\"@opentelemetry/api\");\nconst utils_1 = require(\"./utils\");\n/**\n * Runs all resource detectors and returns the results merged into a single Resource. Promise\n * does not resolve until all the underlying detectors have resolved, unlike\n * detectResourcesSync.\n *\n * @deprecated use detectResourcesSync() instead.\n * @param config Configuration for resource detection\n */\nconst detectResources = async (config = {}) => {\n const resources = await Promise.all((config.detectors || []).map(async (d) => {\n try {\n const resource = await d.detect(config);\n api_1.diag.debug(`${d.constructor.name} found resource.`, resource);\n return resource;\n }\n catch (e) {\n api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`);\n return Resource_1.Resource.empty();\n }\n }));\n // Future check if verbose logging is enabled issue #1903\n logResources(resources);\n return resources.reduce((acc, resource) => acc.merge(resource), Resource_1.Resource.empty());\n};\nexports.detectResources = detectResources;\n/**\n * Runs all resource detectors synchronously, merging their results. In case of attribute collision later resources will take precedence.\n *\n * @param config Configuration for resource detection\n */\nconst detectResourcesSync = (config = {}) => {\n var _a;\n const resources = ((_a = config.detectors) !== null && _a !== void 0 ? _a : []).map((d) => {\n try {\n const resourceOrPromise = d.detect(config);\n let resource;\n if ((0, utils_1.isPromiseLike)(resourceOrPromise)) {\n const createPromise = async () => {\n const resolvedResource = await resourceOrPromise;\n return resolvedResource.attributes;\n };\n resource = new Resource_1.Resource({}, createPromise());\n }\n else {\n resource = resourceOrPromise;\n }\n if (resource.waitForAsyncAttributes) {\n void resource\n .waitForAsyncAttributes()\n .then(() => api_1.diag.debug(`${d.constructor.name} found resource.`, resource));\n }\n else {\n api_1.diag.debug(`${d.constructor.name} found resource.`, resource);\n }\n return resource;\n }\n catch (e) {\n api_1.diag.error(`${d.constructor.name} failed: ${e.message}`);\n return Resource_1.Resource.empty();\n }\n });\n const mergedResources = resources.reduce((acc, resource) => acc.merge(resource), Resource_1.Resource.empty());\n if (mergedResources.waitForAsyncAttributes) {\n void mergedResources.waitForAsyncAttributes().then(() => {\n // Future check if verbose logging is enabled issue #1903\n logResources(resources);\n });\n }\n return mergedResources;\n};\nexports.detectResourcesSync = detectResourcesSync;\n/**\n * Writes debug information about the detected resources to the logger defined in the resource detection config, if one is provided.\n *\n * @param resources The array of {@link Resource} that should be logged. Empty entries will be ignored.\n */\nconst logResources = (resources) => {\n resources.forEach(resource => {\n // Print only populated resources\n if (Object.keys(resource.attributes).length > 0) {\n const resourceDebugString = JSON.stringify(resource.attributes, null, 4);\n api_1.diag.verbose(resourceDebugString);\n }\n });\n};\n//# sourceMappingURL=detect-resources.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./Resource\"), exports);\n__exportStar(require(\"./IResource\"), exports);\n__exportStar(require(\"./platform\"), exports);\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./config\"), exports);\n__exportStar(require(\"./detectors\"), exports);\n__exportStar(require(\"./detect-resources\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MultiSpanProcessor = void 0;\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nclass MultiSpanProcessor {\n constructor(_spanProcessors) {\n this._spanProcessors = _spanProcessors;\n }\n forceFlush() {\n const promises = [];\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 (0, core_1.globalErrorHandler)(error || new Error('MultiSpanProcessor: forceFlush failed'));\n resolve();\n });\n });\n }\n onStart(span, context) {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n onEnd(span) {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n shutdown() {\n const promises = [];\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}\nexports.MultiSpanProcessor = MultiSpanProcessor;\n//# sourceMappingURL=MultiSpanProcessor.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NoopSpanProcessor = void 0;\n/** No-op implementation of SpanProcessor */\nclass NoopSpanProcessor {\n onStart(_span, _context) { }\n onEnd(_span) { }\n shutdown() {\n return Promise.resolve();\n }\n forceFlush() {\n return Promise.resolve();\n }\n}\nexports.NoopSpanProcessor = NoopSpanProcessor;\n//# sourceMappingURL=NoopSpanProcessor.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BasicTracerProvider = exports.ForceFlushState = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nconst resources_1 = require(\"@opentelemetry/resources\");\nconst _1 = require(\".\");\nconst config_1 = require(\"./config\");\nconst MultiSpanProcessor_1 = require(\"./MultiSpanProcessor\");\nconst NoopSpanProcessor_1 = require(\"./export/NoopSpanProcessor\");\nconst platform_1 = require(\"./platform\");\nconst utility_1 = require(\"./utility\");\nvar ForceFlushState;\n(function (ForceFlushState) {\n ForceFlushState[ForceFlushState[\"resolved\"] = 0] = \"resolved\";\n ForceFlushState[ForceFlushState[\"timeout\"] = 1] = \"timeout\";\n ForceFlushState[ForceFlushState[\"error\"] = 2] = \"error\";\n ForceFlushState[ForceFlushState[\"unresolved\"] = 3] = \"unresolved\";\n})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {}));\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nclass BasicTracerProvider {\n constructor(config = {}) {\n var _a;\n this._registeredSpanProcessors = [];\n this._tracers = new Map();\n const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));\n this.resource = (_a = mergedConfig.resource) !== null && _a !== void 0 ? _a : resources_1.Resource.empty();\n this.resource = resources_1.Resource.default().merge(this.resource);\n this._config = Object.assign({}, mergedConfig, {\n resource: this.resource,\n });\n const defaultExporter = this._buildExporterFromEnv();\n if (defaultExporter !== undefined) {\n const batchProcessor = new platform_1.BatchSpanProcessor(defaultExporter);\n this.activeSpanProcessor = batchProcessor;\n }\n else {\n this.activeSpanProcessor = new NoopSpanProcessor_1.NoopSpanProcessor();\n }\n }\n getTracer(name, version, options) {\n const key = `${name}@${version || ''}:${(options === null || options === void 0 ? void 0 : options.schemaUrl) || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(key, new _1.Tracer({ name, version, schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl }, this._config, this));\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key);\n }\n /**\n * Adds a new {@link SpanProcessor} to this tracer.\n * @param spanProcessor the new SpanProcessor to be added.\n */\n addSpanProcessor(spanProcessor) {\n if (this._registeredSpanProcessors.length === 0) {\n // since we might have enabled by default a batchProcessor, we disable it\n // before adding the new one\n this.activeSpanProcessor\n .shutdown()\n .catch(err => api_1.diag.error('Error while trying to shutdown current span processor', err));\n }\n this._registeredSpanProcessors.push(spanProcessor);\n this.activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(this._registeredSpanProcessors);\n }\n getActiveSpanProcessor() {\n return this.activeSpanProcessor;\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 = {}) {\n api_1.trace.setGlobalTracerProvider(this);\n if (config.propagator === undefined) {\n config.propagator = this._buildPropagatorFromEnv();\n }\n if (config.contextManager) {\n api_1.context.setGlobalContextManager(config.contextManager);\n }\n if (config.propagator) {\n api_1.propagation.setGlobalPropagator(config.propagator);\n }\n }\n forceFlush() {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._registeredSpanProcessors.map((spanProcessor) => {\n return new Promise(resolve => {\n let state;\n const timeoutInterval = setTimeout(() => {\n resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));\n state = ForceFlushState.timeout;\n }, timeout);\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 return new Promise((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(result => result !== ForceFlushState.resolved);\n if (errors.length > 0) {\n reject(errors);\n }\n else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n shutdown() {\n return this.activeSpanProcessor.shutdown();\n }\n /**\n * TS cannot yet infer the type of this.constructor:\n * https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146\n * There is no need to override either of the getters in your child class.\n * The type of the registered component maps should be the same across all\n * classes in the inheritance tree.\n */\n _getPropagator(name) {\n var _a;\n return (_a = this.constructor._registeredPropagators.get(name)) === null || _a === void 0 ? void 0 : _a();\n }\n _getSpanExporter(name) {\n var _a;\n return (_a = this.constructor._registeredExporters.get(name)) === null || _a === void 0 ? void 0 : _a();\n }\n _buildPropagatorFromEnv() {\n // per spec, propagators from env must be deduplicated\n const uniquePropagatorNames = Array.from(new Set((0, core_1.getEnv)().OTEL_PROPAGATORS));\n const propagators = uniquePropagatorNames.map(name => {\n const propagator = this._getPropagator(name);\n if (!propagator) {\n api_1.diag.warn(`Propagator \"${name}\" requested through environment variable is unavailable.`);\n }\n return propagator;\n });\n const validPropagators = propagators.reduce((list, item) => {\n if (item) {\n list.push(item);\n }\n return list;\n }, []);\n if (validPropagators.length === 0) {\n return;\n }\n else if (uniquePropagatorNames.length === 1) {\n return validPropagators[0];\n }\n else {\n return new core_1.CompositePropagator({\n propagators: validPropagators,\n });\n }\n }\n _buildExporterFromEnv() {\n const exporterName = (0, core_1.getEnv)().OTEL_TRACES_EXPORTER;\n if (exporterName === 'none' || exporterName === '')\n return;\n const exporter = this._getSpanExporter(exporterName);\n if (!exporter) {\n api_1.diag.error(`Exporter \"${exporterName}\" requested through environment variable is unavailable.`);\n }\n return exporter;\n }\n}\nexports.BasicTracerProvider = BasicTracerProvider;\nBasicTracerProvider._registeredPropagators = new Map([\n ['tracecontext', () => new core_1.W3CTraceContextPropagator()],\n ['baggage', () => new core_1.W3CBaggagePropagator()],\n]);\nBasicTracerProvider._registeredExporters = new Map();\n//# sourceMappingURL=BasicTracerProvider.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConsoleSpanExporter = void 0;\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n */\n/* eslint-disable no-console */\nclass ConsoleSpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(spans, resultCallback) {\n return this._sendSpans(spans, resultCallback);\n }\n /**\n * Shutdown the exporter.\n */\n shutdown() {\n this._sendSpans([]);\n return this.forceFlush();\n }\n /**\n * Exports any pending spans in exporter\n */\n forceFlush() {\n return Promise.resolve();\n }\n /**\n * converts span info into more readable format\n * @param span\n */\n _exportInfo(span) {\n var _a;\n return {\n traceId: span.spanContext().traceId,\n parentId: span.parentSpanId,\n traceState: (_a = span.spanContext().traceState) === null || _a === void 0 ? void 0 : _a.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),\n duration: (0, core_1.hrTimeToMicroseconds)(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n _sendSpans(spans, done) {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: core_1.ExportResultCode.SUCCESS });\n }\n }\n}\nexports.ConsoleSpanExporter = ConsoleSpanExporter;\n//# sourceMappingURL=ConsoleSpanExporter.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InMemorySpanExporter = void 0;\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nclass InMemorySpanExporter {\n constructor() {\n this._finishedSpans = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n this._stopped = false;\n }\n export(spans, resultCallback) {\n if (this._stopped)\n return resultCallback({\n code: core_1.ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0);\n }\n shutdown() {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush() {\n return Promise.resolve();\n }\n reset() {\n this._finishedSpans = [];\n }\n getFinishedSpans() {\n return this._finishedSpans;\n }\n}\nexports.InMemorySpanExporter = InMemorySpanExporter;\n//# sourceMappingURL=InMemorySpanExporter.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=ReadableSpan.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SimpleSpanProcessor = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n */\nclass SimpleSpanProcessor {\n constructor(_exporter) {\n this._exporter = _exporter;\n this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);\n this._unresolvedExports = new Set();\n }\n async forceFlush() {\n // await unresolved resources before resolving\n await Promise.all(Array.from(this._unresolvedExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n onStart(_span, _parentContext) { }\n onEnd(span) {\n var _a, _b;\n if (this._shutdownOnce.isCalled) {\n return;\n }\n if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {\n return;\n }\n const doExport = () => core_1.internal\n ._export(this._exporter, [span])\n .then((result) => {\n var _a;\n if (result.code !== core_1.ExportResultCode.SUCCESS) {\n (0, core_1.globalErrorHandler)((_a = result.error) !== null && _a !== void 0 ? _a : new Error(`SimpleSpanProcessor: span export failed (status ${result})`));\n }\n })\n .catch(error => {\n (0, core_1.globalErrorHandler)(error);\n });\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (span.resource.asyncAttributesPending) {\n const exportPromise = (_b = (_a = span.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a).then(() => {\n if (exportPromise != null) {\n this._unresolvedExports.delete(exportPromise);\n }\n return doExport();\n }, err => (0, core_1.globalErrorHandler)(err));\n // store the unresolved exports\n if (exportPromise != null) {\n this._unresolvedExports.add(exportPromise);\n }\n }\n else {\n void doExport();\n }\n }\n shutdown() {\n return this._shutdownOnce.call();\n }\n _shutdown() {\n return this._exporter.shutdown();\n }\n}\nexports.SimpleSpanProcessor = SimpleSpanProcessor;\n//# sourceMappingURL=SimpleSpanProcessor.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=SpanExporter.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=SpanProcessor.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=TimedEvent.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=IdGenerator.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./Tracer\"), exports);\n__exportStar(require(\"./BasicTracerProvider\"), exports);\n__exportStar(require(\"./platform\"), exports);\n__exportStar(require(\"./export/ConsoleSpanExporter\"), exports);\n__exportStar(require(\"./export/InMemorySpanExporter\"), exports);\n__exportStar(require(\"./export/ReadableSpan\"), exports);\n__exportStar(require(\"./export/SimpleSpanProcessor\"), exports);\n__exportStar(require(\"./export/SpanExporter\"), exports);\n__exportStar(require(\"./export/NoopSpanProcessor\"), exports);\n__exportStar(require(\"./sampler/AlwaysOffSampler\"), exports);\n__exportStar(require(\"./sampler/AlwaysOnSampler\"), exports);\n__exportStar(require(\"./sampler/ParentBasedSampler\"), exports);\n__exportStar(require(\"./sampler/TraceIdRatioBasedSampler\"), exports);\n__exportStar(require(\"./Sampler\"), exports);\n__exportStar(require(\"./Span\"), exports);\n__exportStar(require(\"./SpanProcessor\"), exports);\n__exportStar(require(\"./TimedEvent\"), exports);\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./IdGenerator\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JaegerPropagator = exports.UBER_BAGGAGE_HEADER_PREFIX = exports.UBER_TRACE_ID_HEADER = void 0;\nconst api_1 = require(\"@opentelemetry/api\");\nconst core_1 = require(\"@opentelemetry/core\");\nexports.UBER_TRACE_ID_HEADER = 'uber-trace-id';\nexports.UBER_BAGGAGE_HEADER_PREFIX = 'uberctx';\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n * {trace-id}:{span-id}:{parent-span-id}:{flags}\n * {trace-id}\n * 64-bit or 128-bit random number in base16 format.\n * Can be variable length, shorter values are 0-padded on the left.\n * Value of 0 is invalid.\n * {span-id}\n * 64-bit random number in base16 format.\n * {parent-span-id}\n * Set to 0 because this field is deprecated.\n * {flags}\n * One byte bitmap, as two hex digits.\n * Inspired by jaeger-client-node project.\n */\nclass JaegerPropagator {\n constructor(config) {\n if (typeof config === 'string') {\n this._jaegerTraceHeader = config;\n this._jaegerBaggageHeaderPrefix = exports.UBER_BAGGAGE_HEADER_PREFIX;\n }\n else {\n this._jaegerTraceHeader =\n (config === null || config === void 0 ? void 0 : config.customTraceHeader) || exports.UBER_TRACE_ID_HEADER;\n this._jaegerBaggageHeaderPrefix =\n (config === null || config === void 0 ? void 0 : config.customBaggageHeaderPrefix) || exports.UBER_BAGGAGE_HEADER_PREFIX;\n }\n }\n inject(context, carrier, setter) {\n const spanContext = api_1.trace.getSpanContext(context);\n const baggage = api_1.propagation.getBaggage(context);\n if (spanContext && (0, core_1.isTracingSuppressed)(context) === false) {\n const traceFlags = `0${(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;\n setter.set(carrier, this._jaegerTraceHeader, `${spanContext.traceId}:${spanContext.spanId}:0:${traceFlags}`);\n }\n if (baggage) {\n for (const [key, entry] of baggage.getAllEntries()) {\n setter.set(carrier, `${this._jaegerBaggageHeaderPrefix}-${key}`, encodeURIComponent(entry.value));\n }\n }\n }\n extract(context, carrier, getter) {\n var _a;\n const uberTraceIdHeader = getter.get(carrier, this._jaegerTraceHeader);\n const uberTraceId = Array.isArray(uberTraceIdHeader)\n ? uberTraceIdHeader[0]\n : uberTraceIdHeader;\n const baggageValues = getter\n .keys(carrier)\n .filter(key => key.startsWith(`${this._jaegerBaggageHeaderPrefix}-`))\n .map(key => {\n const value = getter.get(carrier, key);\n return {\n key: key.substring(this._jaegerBaggageHeaderPrefix.length + 1),\n value: Array.isArray(value) ? value[0] : value,\n };\n });\n let newContext = context;\n // if the trace id header is present and valid, inject it into the context\n if (typeof uberTraceId === 'string') {\n const spanContext = deserializeSpanContext(uberTraceId);\n if (spanContext) {\n newContext = api_1.trace.setSpanContext(newContext, spanContext);\n }\n }\n if (baggageValues.length === 0)\n return newContext;\n // if baggage values are present, inject it into the current baggage\n let currentBaggage = (_a = api_1.propagation.getBaggage(context)) !== null && _a !== void 0 ? _a : api_1.propagation.createBaggage();\n for (const baggageEntry of baggageValues) {\n if (baggageEntry.value === undefined)\n continue;\n currentBaggage = currentBaggage.setEntry(baggageEntry.key, {\n value: decodeURIComponent(baggageEntry.value),\n });\n }\n newContext = api_1.propagation.setBaggage(newContext, currentBaggage);\n return newContext;\n }\n fields() {\n return [this._jaegerTraceHeader];\n }\n}\nexports.JaegerPropagator = JaegerPropagator;\nconst VALID_HEX_RE = /^[0-9a-f]{1,2}$/i;\n/**\n * @param {string} serializedString - a serialized span context.\n * @return {SpanContext} - returns a span context represented by the serializedString.\n **/\nfunction deserializeSpanContext(serializedString) {\n const headers = decodeURIComponent(serializedString).split(':');\n if (headers.length !== 4) {\n return null;\n }\n const [_traceId, _spanId, , flags] = headers;\n const traceId = _traceId.padStart(32, '0');\n const spanId = _spanId.padStart(16, '0');\n const traceFlags = VALID_HEX_RE.test(flags) ? parseInt(flags, 16) & 1 : 1;\n return { traceId, spanId, isRemote: true, traceFlags };\n}\n//# sourceMappingURL=JaegerPropagator.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./JaegerPropagator\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeTracerProvider = void 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 */\nconst context_async_hooks_1 = require(\"@opentelemetry/context-async-hooks\");\nconst propagator_b3_1 = require(\"@opentelemetry/propagator-b3\");\nconst sdk_trace_base_1 = require(\"@opentelemetry/sdk-trace-base\");\nconst semver = require(\"semver\");\nconst propagator_jaeger_1 = require(\"@opentelemetry/propagator-jaeger\");\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 */\nclass NodeTracerProvider extends sdk_trace_base_1.BasicTracerProvider {\n constructor(config = {}) {\n super(config);\n }\n register(config = {}) {\n if (config.contextManager === undefined) {\n const ContextManager = semver.gte(process.version, '14.8.0')\n ? context_async_hooks_1.AsyncLocalStorageContextManager\n : context_async_hooks_1.AsyncHooksContextManager;\n config.contextManager = new ContextManager();\n config.contextManager.enable();\n }\n super.register(config);\n }\n}\nexports.NodeTracerProvider = NodeTracerProvider;\nNodeTracerProvider._registeredPropagators = new Map([\n ...sdk_trace_base_1.BasicTracerProvider._registeredPropagators,\n [\n 'b3',\n () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.SINGLE_HEADER }),\n ],\n [\n 'b3multi',\n () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER }),\n ],\n ['jaeger', () => new propagator_jaeger_1.JaegerPropagator()],\n]);\n//# sourceMappingURL=NodeTracerProvider.js.map","\"use strict\";\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 */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./NodeTracerProvider\"), exports);\n__exportStar(require(\"@opentelemetry/sdk-trace-base\"), exports);\n//# sourceMappingURL=index.js.map","import { CleanSpanData } from \"./types\";\nimport { memoryStore } from \"./MemoryStore\";\nimport { JsonSchema, JsonSchemaHelper } from \"./tracing/JsonSchemaHelper\";\nimport { logger } from \"./utils/logger\";\n\ninterface MockMatcherRequestData {\n inputValue: any;\n inputValueHash: string;\n inputSchema: JsonSchema;\n inputSchemaHash: string;\n}\n\n// Idealy CLI should always return a mock or cancel the inbound request\n/**\n * Abstract mock matching service for finding appropriate mocks based on request data\n * This will be used across all instrumentations to match incoming requests with recorded mocks\n */\nexport class MockMatcher {\n /**\n * Find the best matching mock for a given request from available mocks\n * Implements priority-based matching:\n * 1. Unused mock by input value hash\n * 2. Used mock by input value hash\n * 3. Unused mock by input value hash with headers removed\n * 4. Used mock by input value hash with headers removed\n * 5. Unused mock by input schema hash\n * 6. Used mock by input schema hash\n *\n * If multiple mocks match at any level, picks the one recorded first.\n *\n * @param requestData - The request data representing the current request\n * @param availableMocks - Array of recorded mock span data for the trace\n * @param stackTrace - The stack trace of the current request (just kept here since we will pass this to the CLI)\n * @returns The matching mock span data, or null if no suitable match is found\n */\n static findBestMatch({\n outboundSpan,\n replayTraceId,\n stackTrace,\n }: {\n outboundSpan: CleanSpanData;\n replayTraceId: string;\n stackTrace?: string;\n }): CleanSpanData | null {\n const {\n schema: inputSchema,\n decodedValueHash: inputValueHash,\n decodedSchemaHash: inputSchemaHash,\n } = JsonSchemaHelper.generateSchemaAndHash(outboundSpan.inputValue);\n\n const requestData = {\n inputValue: outboundSpan.inputValue,\n inputValueHash,\n inputSchema,\n inputSchemaHash,\n };\n\n const availableMocks = memoryStore.getRequestReplayMocks(replayTraceId);\n if (!availableMocks) {\n logger.debug(\"MockMatcher no available mocks found for replay trace id:\", replayTraceId);\n return null;\n }\n\n logger.debug(\"MockMatcher finding best match for request:\", {\n availableMocksCount: availableMocks.length,\n });\n\n // Sort all mocks by timestamp to ensure \"recorded first\" ordering for tie-breaking\n const sortedMocks = [...availableMocks].sort(\n (a, b) => new Date(a.timestamp.seconds).getTime() - new Date(b.timestamp.seconds).getTime(),\n );\n\n // Priority 1: Unused mock by input value hash\n let match = this.findUnusedMockByInputValueHash(requestData, sortedMocks);\n if (match) {\n logger.debug(\"MockMatcher found unused mock by input value hash:\", match.name);\n this.markMockAsUsed(match);\n return match;\n }\n\n // Priority 2: Used mock by input value hash\n match = this.findUsedMockByInputValueHash(requestData, sortedMocks);\n if (match) {\n logger.debug(\"MockMatcher found used mock by input value hash:\", match.name);\n return match;\n }\n\n // Priority 3: Unused mock by input value hash with headers removed\n match = this.findUnusedMockByInputValueHashWithoutHeaders(requestData, sortedMocks);\n if (match) {\n logger.debug(\n \"MockMatcher Found unused mock by input value hash without headers:\",\n match.name,\n );\n this.markMockAsUsed(match);\n return match;\n }\n\n // Priority 4: Used mock by input value hash with headers removed\n match = this.findUsedMockByInputValueHashWithoutHeaders(requestData, sortedMocks);\n if (match) {\n logger.debug(\"MockMatcher found used mock by input value hash without headers:\", match.name);\n return match;\n }\n\n // Priority 5: Unused mock by input schema hash\n match = this.findUnusedMockByInputSchemaHash(requestData, sortedMocks);\n if (match) {\n logger.debug(\"MockMatcher found unused mock by input schema hash:\", match.name);\n this.markMockAsUsed(match);\n return match;\n }\n\n // Priority 6: Used mock by input schema hash\n match = this.findUsedMockByInputSchemaHash(requestData, sortedMocks);\n if (match) {\n logger.debug(\"MockMatcher found used mock by input schema hash:\", match.name);\n return match;\n }\n\n logger.error(\"MockMatcher no matching mock found with any strategy\", requestData);\n return null;\n }\n\n /**\n * Mark a mock as used to track usage in priority matching\n */\n private static markMockAsUsed(mock: CleanSpanData): void {\n mock.isUsed = true;\n }\n\n /**\n * Check if a mock is unused\n */\n private static isUnused(mock: CleanSpanData): boolean {\n return !mock.isUsed;\n }\n\n /**\n * Check if a mock is used\n */\n private static isUsed(mock: CleanSpanData): boolean {\n return !!mock.isUsed;\n }\n\n /**\n * Find unused mock by exact input value hash match\n */\n private static findUnusedMockByInputValueHash(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n return (\n sortedMocks.find(\n (mock) => this.isUnused(mock) && mock.inputValueHash === requestData.inputValueHash,\n ) || null\n );\n }\n\n /**\n * Find used mock by exact input value hash match\n */\n private static findUsedMockByInputValueHash(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n return (\n sortedMocks.find(\n (mock) => this.isUsed(mock) && mock.inputValueHash === requestData.inputValueHash,\n ) || null\n );\n }\n\n /**\n * Find unused mock by input value hash with headers removed\n */\n private static findUnusedMockByInputValueHashWithoutHeaders(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n const requestInputWithoutHeaders = this.removeHeadersFromInputValue(requestData.inputValue);\n const requestHashWithoutHeaders = JsonSchemaHelper.generateDeterministicHash(\n requestInputWithoutHeaders,\n );\n\n return (\n sortedMocks.find((mock) => {\n if (!this.isUnused(mock)) return false;\n\n const mockInputWithoutHeaders = this.removeHeadersFromInputValue(mock.inputValue);\n const mockHashWithoutHeaders =\n JsonSchemaHelper.generateDeterministicHash(mockInputWithoutHeaders);\n\n return mockHashWithoutHeaders === requestHashWithoutHeaders;\n }) || null\n );\n }\n\n /**\n * Find used mock by input value hash with headers removed\n */\n private static findUsedMockByInputValueHashWithoutHeaders(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n const requestInputWithoutHeaders = this.removeHeadersFromInputValue(requestData.inputValue);\n const requestHashWithoutHeaders = JsonSchemaHelper.generateDeterministicHash(\n requestInputWithoutHeaders,\n );\n\n return (\n sortedMocks.find((mock) => {\n if (!this.isUsed(mock)) return false;\n\n const mockInputWithoutHeaders = this.removeHeadersFromInputValue(mock.inputValue);\n const mockHashWithoutHeaders =\n JsonSchemaHelper.generateDeterministicHash(mockInputWithoutHeaders);\n\n return mockHashWithoutHeaders === requestHashWithoutHeaders;\n }) || null\n );\n }\n\n /**\n * Find unused mock by input schema hash match\n */\n private static findUnusedMockByInputSchemaHash(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n return (\n sortedMocks.find(\n (mock) => this.isUnused(mock) && mock.inputSchemaHash === requestData.inputSchemaHash,\n ) || null\n );\n }\n\n /**\n * Find used mock by input schema hash match\n */\n private static findUsedMockByInputSchemaHash(\n requestData: MockMatcherRequestData,\n sortedMocks: CleanSpanData[],\n ): CleanSpanData | null {\n return (\n sortedMocks.find(\n (mock) => this.isUsed(mock) && mock.inputSchemaHash === requestData.inputSchemaHash,\n ) || null\n );\n }\n\n /**\n * Remove headers property from input value for header-agnostic matching\n */\n private static removeHeadersFromInputValue(inputValue: any): any {\n if (!inputValue || typeof inputValue !== \"object\") {\n return inputValue;\n }\n\n const { headers, ...inputWithoutHeaders } = inputValue;\n return inputWithoutHeaders;\n }\n}\n","export const TuskDriftInstrumentationModuleNames = [\n \"http\",\n \"https\",\n \"pg\",\n \"postgres\",\n \"node-fetch\",\n \"graphql\",\n \"jsonwebtoken\",\n \"jwks-rsa\",\n];\n","import fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport {\n HttpInstrumentation,\n PgInstrumentation,\n FetchInstrumentation,\n TcpInstrumentation,\n GraphqlInstrumentation,\n JsonwebtokenInstrumentation,\n DateInstrumentation,\n JwksRsaInstrumentation,\n EnvInstrumentation,\n PostgresInstrumentation,\n} from \"../instrumentation/libraries\";\nimport { TdSpanExporter } from \"./tracing/TdSpanExporter\";\nimport { MemoryStore, memoryStore } from \"./MemoryStore\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport { trace, Tracer } from \"@opentelemetry/api\";\nimport { ProtobufCommunicator, MockRequestInput } from \"./ProtobufCommunicator\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-node\";\nimport { MockMatcher } from \"./MockMatcher\";\nimport { CleanSpanData } from \"./types\";\nimport { TuskDriftInstrumentationModuleNames } from \"./TuskDriftInstrumentationModuleNames\";\nimport { SDK_VERSION } from \"../version\";\nimport {\n LogLevel,\n initializeGlobalLogger,\n logger,\n loadTuskConfig,\n TuskConfig,\n OriginalGlobalUtils,\n} from \"./utils\";\nimport { TransformConfigs } from \"../instrumentation/libraries/http/HttpTransformEngine\";\n\nexport interface InitParams {\n apiKey?: string;\n env: string;\n logLevel?: LogLevel;\n transforms?: TransformConfigs;\n}\n\nexport enum TuskDriftMode {\n DISABLED = \"DISABLED\",\n RECORD = \"RECORD\",\n REPLAY = \"REPLAY\",\n}\n\n/**\n * The core class for Tusk Drift.\n * This class is responsible for initializing the Tusk Drift SDK and managing the Tusk Drift instance.\n */\nexport class TuskDriftCore {\n private static instance: TuskDriftCore;\n private initialized = false;\n private appReady = false;\n private mode: TuskDriftMode;\n private sdk?: NodeSDK;\n private initParams: InitParams;\n private config: TuskConfig;\n private memoryStore: MemoryStore;\n private communicator?: ProtobufCommunicator | undefined;\n private samplingRate: number;\n private cliConnectionPromise: Promise<void> | null;\n // Add a flag to track connection status\n private isConnectedWithCLI = false;\n\n constructor() {\n this.mode = this.detectMode();\n this.memoryStore = memoryStore;\n this.config = loadTuskConfig() || {};\n }\n\n private isCommonJS(): boolean {\n return (\n typeof module !== \"undefined\" &&\n \"exports\" in module &&\n typeof require !== \"undefined\" &&\n typeof require.cache !== \"undefined\"\n );\n }\n\n private getPackageName(modulePath: string): string | null {\n let dir = path.dirname(modulePath);\n while (dir) {\n const packageJsonPath = path.join(dir, \"package.json\");\n if (fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n return packageJson.name || null;\n } catch (err) {\n logger.error(`Error reading package.json in ${packageJsonPath}:`, err);\n return null;\n }\n }\n const parentDir = path.dirname(dir);\n if (parentDir === dir || !parentDir.includes(\"node_modules\")) {\n break;\n }\n dir = parentDir;\n }\n return null;\n }\n\n private alreadyRequiredModules(): Set<string> {\n const alreadyRequiredModuleNames = new Set<string>();\n\n if (this.isCommonJS()) {\n const requireCache = Object.keys(require.cache);\n for (const modulePath of requireCache) {\n if (modulePath.includes(\"node_modules\")) {\n const packageName = this.getPackageName(modulePath);\n if (packageName && TuskDriftInstrumentationModuleNames.includes(packageName)) {\n alreadyRequiredModuleNames.add(packageName);\n }\n }\n }\n } else {\n // ESM or other module systems - no reliable detection possible\n logger.warn(\"Running in ES Module mode. Cannot detect pre-loaded instrumentation modules.\");\n }\n\n return alreadyRequiredModuleNames;\n }\n\n static getInstance(): TuskDriftCore {\n if (!TuskDriftCore.instance) {\n TuskDriftCore.instance = new TuskDriftCore();\n }\n return TuskDriftCore.instance;\n }\n\n private isRunningIntegrationTest(): boolean {\n return OriginalGlobalUtils.getOriginalProcessEnvVar(\"TUSK_DRIFT_INTEGRATION_TEST\") === \"TRUE\";\n }\n\n private detectMode(): TuskDriftMode {\n const modeEnv = OriginalGlobalUtils.getOriginalProcessEnvVar(\"TUSK_DRIFT_MODE\");\n\n switch (modeEnv?.toUpperCase()) {\n case \"RECORD\":\n return TuskDriftMode.RECORD;\n case \"REPLAY\":\n return TuskDriftMode.REPLAY;\n case \"DISABLED\":\n case \"DISABLE\":\n return TuskDriftMode.DISABLED;\n default:\n // If no mode specified, default to disabled\n return TuskDriftMode.DISABLED;\n }\n }\n\n private initializeMemoryStore({ baseDirectory }: { baseDirectory: string }): void {\n if (this.isRunningIntegrationTest()) {\n logger.debug(`Initializing memory store with base directory: ${baseDirectory}`);\n this.memoryStore.initialize(baseDirectory);\n } else {\n logger.debug(\"Not running integration test, skipping memory store initialization\");\n }\n }\n\n private registerDefaultInstrumentations(): void {\n // Just creating the instrumentations registers them with the sdk\n // All these instrumentations extend TdInstrumentationBase\n // TdInstrumentationBase constructor calls enable() which sets up the require-in-the-middle hooks to patch the modules\n // when the modules are required\n const transforms = this.config.transforms ?? this.initParams.transforms;\n\n new HttpInstrumentation({\n enabled: true,\n mode: this.mode,\n transforms,\n });\n\n new PgInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new FetchInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new TcpInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new GraphqlInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new JsonwebtokenInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new DateInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new JwksRsaInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n\n new EnvInstrumentation({\n enabled: this.config.recording?.enable_env_var_recording || false,\n mode: this.mode,\n });\n\n new PostgresInstrumentation({\n enabled: true,\n mode: this.mode,\n });\n }\n\n private initializeTracing({ baseDirectory }: { baseDirectory: string }): void {\n const serviceName = this.config.service?.name || \"unknown\";\n\n logger.debug(`Initializing OpenTelemetry tracing for service: ${serviceName}`);\n\n const traceExporter = new TdSpanExporter({\n baseDirectory,\n mode: this.mode,\n useRemoteExport: this.config.recording?.export_spans || false,\n observableServiceId: this.config.service?.id,\n apiKey: this.initParams.apiKey,\n tuskBackendBaseUrl: this.config.tusk_api?.url || \"https://api.usetusk.ai\",\n environment: this.initParams.env,\n sdkVersion: SDK_VERSION,\n sdkInstanceId: this.generateSdkInstanceId(),\n });\n\n // Create NodeSDK with custom trace exporter, handled by opentelemetry\n this.sdk = new NodeSDK({\n serviceName,\n spanProcessor: new BatchSpanProcessor(traceExporter, {\n // Maximum queue size before spans are dropped, default 2048\n maxQueueSize: 2048,\n // Maximum batch size per export, default 512\n maxExportBatchSize: 512,\n // Interval between exports, default 5s\n scheduledDelayMillis: 2000,\n // Max time for export before timeout, default 30s\n exportTimeoutMillis: 30000,\n }),\n // Disable auto-instrumentations since we handle them manually\n instrumentations: [],\n });\n\n this.sdk.start();\n logger.debug(`OpenTelemetry tracing initialized`);\n }\n\n private generateSdkInstanceId(): string {\n const originalDate = OriginalGlobalUtils.getOriginalDate();\n return `sdk-${originalDate.getTime()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n initialize(initParams: InitParams): void {\n this.samplingRate = this.config.recording?.sampling_rate ?? 1;\n this.initParams = initParams;\n\n // Initialize logging with provided level or default to 'warn'\n initializeGlobalLogger({\n logLevel: initParams.logLevel || \"info\",\n prefix: \"TuskDrift\",\n });\n\n if (this.initialized) {\n logger.debug(\"Already initialized, skipping...\");\n return;\n }\n\n if (\n this.mode === TuskDriftMode.RECORD &&\n this.config.recording?.export_spans &&\n !this.initParams.apiKey\n ) {\n logger.error(\n \"In record mode and export_spans is true, but API key not provided. API key is required to export spans to Tusk backend. Please provide an API key in the initialization parameters.\",\n );\n return;\n }\n\n if (!this.initParams.env) {\n logger.error(\n \"Environment not provided. Please provide an environment in the initialization parameters.\",\n );\n return;\n }\n\n // Need to have observable service id if exporting spans to Tusk backend\n if (this.config.recording?.export_spans && !this.config.service?.id) {\n logger.error(\n \"Observable service ID not provided. Please provide an observable service ID in the configuration file.\",\n );\n return;\n }\n\n if (this.mode === TuskDriftMode.DISABLED) {\n logger.debug(\"SDK disabled via environment variable\");\n return;\n }\n\n logger.debug(`Initializing in ${this.mode} mode`);\n\n if (this.mode === TuskDriftMode.REPLAY) {\n // Disable Sentry in replay mode\n process.env.SENTRY_DSN = \"\";\n }\n\n // Initialize ProtobufCommunicator early\n this.communicator = new ProtobufCommunicator();\n\n if (this.mode === TuskDriftMode.REPLAY && !this.isRunningIntegrationTest()) {\n const socketPath =\n OriginalGlobalUtils.getOriginalProcessEnvVar(\"TUSK_MOCK_SOCKET\") ||\n path.join(os.tmpdir(), \"tusk-connect.sock\");\n\n // Check if socket exists and is ready\n try {\n fs.accessSync(socketPath, fs.constants.F_OK);\n const stats = fs.statSync(socketPath);\n if (!stats.isSocket()) {\n throw new Error(`Path exists but is not a socket: ${socketPath}`);\n }\n logger.debug(\"Socket found and verified at\", socketPath);\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n throw new Error(`Socket not found at ${socketPath}. Make sure Tusk CLI is running.`);\n }\n throw new Error(\n `Socket check failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Start connection early for replay mode (runs in parallel with other initialization)\n // This will be awaited when the first requestAsyncMock is called\n this.cliConnectionPromise = this.communicator\n .connect(socketPath, this.config.service?.id || \"unknown\")\n .then(() => {\n this.isConnectedWithCLI = true;\n logger.debug(\"SDK successfully connected to CLI\");\n });\n }\n\n // Check if any instrumentation modules are already required\n const packageNames = this.alreadyRequiredModules();\n if (packageNames.size > 0) {\n const moduleList = [...packageNames].join(\", \");\n const message = `TuskDrift must be initialized before any other modules are required. This ensures TuskDrift is able to instrument the required modules. ${moduleList} ${packageNames.size > 1 ? \"are\" : \"is\"} already required.`;\n\n if (this.mode === TuskDriftMode.RECORD) {\n logger.warn(`${message} TuskDrift is now disabled and will continue in disabled mode.`);\n this.mode = TuskDriftMode.DISABLED;\n return;\n } else if (this.mode === TuskDriftMode.REPLAY) {\n logger.error(`${message} TuskDrift will not run in replay mode. Stopping the app.`);\n process.exit(1);\n }\n }\n\n // Only used when storing spans locally\n const baseDirectory = this.config.traces?.dir || path.join(process.cwd(), \".tusk/traces\");\n\n logger.debug(`Config: ${JSON.stringify(this.config)}`);\n logger.debug(`Base directory: ${baseDirectory}`);\n\n const transforms = this.config.transforms ?? this.initParams.transforms;\n\n // Initialize OpenTelemetry tracing (runs in parallel with connection)\n this.initializeTracing({ baseDirectory });\n\n // Only initialized for integration tests\n this.initializeMemoryStore({ baseDirectory });\n\n // Register instrumentations\n this.registerDefaultInstrumentations();\n\n this.initialized = true;\n logger.info(\"SDK initialized successfully\");\n }\n\n markAppAsReady(): void {\n if (!this.initialized) {\n if (this.mode !== TuskDriftMode.DISABLED) {\n logger.error(\"markAppAsReady() called before initialize(). Call initialize() first.\");\n }\n return;\n }\n\n this.appReady = true;\n logger.debug(\"Application marked as ready\");\n\n if (this.mode === TuskDriftMode.REPLAY) {\n logger.info(\"Replay mode active - ready to serve mocked responses\");\n } else if (this.mode === TuskDriftMode.RECORD) {\n logger.info(\"Record mode active - capturing requests and responses\");\n }\n }\n\n async sendInboundSpanForReplay(span: CleanSpanData): Promise<void> {\n try {\n if (this.communicator) {\n await this.communicator.sendInboundSpanForReplay(span);\n }\n } catch (e) {\n logger.error(\"Failed to send inbound replay span:\", e);\n }\n }\n\n private timestampToISOString({ seconds, nanos }: { seconds: bigint; nanos: number }): string {\n // Convert seconds (bigint) to milliseconds and add nanoseconds converted to milliseconds\n const milliseconds = Number(seconds) * 1000 + Math.floor(nanos / 1_000_000);\n return new Date(milliseconds).toISOString();\n }\n\n /**\n * Checks if we are running an integration test\n * If we are, use the memory store to find the best match since CLI isn't running\n */\n private createMockRequestCore(\n mockRequest: MockRequestInput,\n ): { found: boolean; response?: any; error?: string } | null {\n if (this.isRunningIntegrationTest()) {\n // Don't have the CLI running, so we need to find the best match from the memory store\n const mock = MockMatcher.findBestMatch({\n outboundSpan: mockRequest.outboundSpan,\n replayTraceId: mockRequest.testId,\n stackTrace: new Error().stack,\n });\n return mock\n ? {\n found: true,\n response: {\n response: { body: mock.outputValue },\n timestamp: this.timestampToISOString({\n seconds: BigInt(mock.timestamp.seconds),\n nanos: mock.timestamp.nanos,\n }),\n },\n }\n : { found: false, error: \"No mock found\" };\n }\n\n if (!this.communicator || this.mode !== TuskDriftMode.REPLAY) {\n logger.error(\n \"Cannot request mock: not in replay mode or no CLI connection\",\n this.mode,\n this.communicator,\n );\n return { found: false, error: \"Not in replay mode or no CLI connection\" };\n }\n\n return null; // Indicates we should proceed with CLI request\n }\n\n async requestMockAsync(\n mockRequest: MockRequestInput,\n ): Promise<{ found: boolean; response?: any; error?: string }> {\n if (this.cliConnectionPromise && !this.isConnectedWithCLI) {\n logger.debug(\"Waiting for CLI connection to be established\");\n await this.cliConnectionPromise;\n }\n\n const mockRequestCore = this.createMockRequestCore(mockRequest);\n if (mockRequestCore) {\n return mockRequestCore;\n }\n return this.requestMockFromCLIAsync(mockRequest);\n }\n\n private async requestMockFromCLIAsync(\n mockRequest: MockRequestInput,\n ): Promise<{ found: boolean; response?: any; error?: string }> {\n if (!this.communicator || this.mode !== TuskDriftMode.REPLAY) {\n logger.error(\"Cannot request mock: not in replay mode or no CLI connection\");\n return { found: false, error: \"Not in replay mode or no CLI connection\" };\n }\n\n try {\n logger.debug(\"Sending protobuf request to CLI (async)\", JSON.stringify(mockRequest, null, 2));\n\n const response = await this.communicator.requestMockAsync({\n testId: mockRequest.testId,\n outboundSpan: mockRequest.outboundSpan,\n });\n\n logger.debug(\"Received protobuf response from CLI\", JSON.stringify(response, null, 2));\n return response;\n } catch (error) {\n logger.error(\"Error sending protobuf request to CLI:\", error);\n return {\n found: false,\n error: `Error sending request: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n };\n }\n }\n\n // NOTE: this isn't being used anywhere right now\n // When we do need to use it, we need to add a check for isConnectedWithCLI similar to requestMockAsync\n requestMockSync(mockRequest: MockRequestInput): {\n found: boolean;\n response?: any;\n error?: string;\n } {\n const mockRequestCore = this.createMockRequestCore(mockRequest);\n if (mockRequestCore) {\n return mockRequestCore;\n }\n return this.requestMockFromCLISync(mockRequest);\n }\n\n private requestMockFromCLISync(mockRequest: MockRequestInput): {\n found: boolean;\n response?: any;\n error?: string;\n } {\n if (!this.communicator || this.mode !== TuskDriftMode.REPLAY) {\n logger.error(\n \"Cannot request mock: not in replay mode or no CLI connection\",\n this.mode,\n this.communicator,\n );\n return { found: false, error: \"Not in replay mode or no CLI connection\" };\n }\n\n try {\n logger.debug(\"Sending protobuf request to CLI (sync)\", mockRequest);\n\n const response = this.communicator.requestMockSync({\n testId: mockRequest.testId,\n outboundSpan: mockRequest.outboundSpan,\n });\n\n logger.debug(\"Received protobuf response from CLI\", response);\n return response;\n } catch (error) {\n logger.error(\"Error sending protobuf request to CLI:\", error);\n return {\n found: false,\n error: `Error sending request: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n };\n }\n }\n\n getMode(): TuskDriftMode {\n return this.mode;\n }\n\n getSamplingRate(): number {\n return this.samplingRate;\n }\n\n isInitialized(): boolean {\n return this.initialized;\n }\n\n isAppReady(): boolean {\n return this.appReady;\n }\n\n getConfig(): TuskConfig {\n return this.config;\n }\n\n getInitParams(): InitParams {\n return this.initParams;\n }\n\n getTracer(): Tracer {\n return trace.getTracer(\"tusk-drift-sdk\", \"1.0.0\");\n }\n\n /**\n * Get the memory store instance\n */\n getMemoryStore(): MemoryStore {\n return this.memoryStore;\n }\n\n /**\n * Create replay mappings for a specific trace ID\n * This should be called when an inbound request comes in with a trace ID\n */\n createReplayMappingsForTrace(traceId: string): void {\n if (!this.memoryStore.isInitialized()) {\n // Only initialized for integration tests\n logger.error(\"Memory store not initialized. Cannot create replay mappings.\");\n return;\n }\n\n logger.debug(`Creating replay mappings for trace: ${traceId}`);\n this.memoryStore.createRequestReplayMockMap(traceId);\n }\n}\n\n// These JSDoc comments are exposed in the type definitions\ninterface TuskDriftPublicAPI {\n /**\n * Initialize the TuskDrift SDK instance\n *\n * This is the main initialization function for TuskDrift that must be called before importing/requiring any other modules.\n *\n * @param initParams - The initialization parameters object containing:\n * - apiKey: string - Your TuskDrift API key (required)\n * - env: string - The environment name (e.g., 'development', 'staging', 'production') (required)\n * - logLevel?: LogLevel - Optional logging level ('silent' | 'error' | 'warn' | 'info' | 'debug'), defaults to 'info'\n *\n * @returns void - Initializes the SDK\n *\n * @example\n * ```typescript\n * import { TuskDrift } from 'tusk-drift-sdk';\n *\n * TuskDrift.initialize({\n * apiKey: 'your-api-key',\n * env: 'production',\n * logLevel: 'debug'\n * });\n *\n * ```\n */\n initialize(initParams: InitParams): void;\n\n /**\n * Mark the application as ready for recording/replay\n *\n * This should be called after the application has completed initialization and is ready to serve requests.\n *\n * @returns void\n */\n markAppAsReady(): void;\n}\n\nclass TuskDriftSDK implements TuskDriftPublicAPI {\n private tuskDrift = TuskDriftCore.getInstance();\n\n initialize(initParams: InitParams): void {\n return this.tuskDrift.initialize(initParams);\n }\n\n markAppAsReady(): void {\n return this.tuskDrift.markAppAsReady();\n }\n}\n\n// Export singleton instance with restricted API\nexport const TuskDrift: TuskDriftPublicAPI = new TuskDriftSDK();\n"],"x_google_ignoreList":[42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAsB,4BAAtB,MAAgD;CAI9C,YAAY,qBAA6B,SAAkC,EAAE,EAAE;AAC7E,OAAK,sBAAsB;AAC3B,OAAK,UAAU;GACb,SAAS;GACT,GAAG;GACJ;;CAGH,YAAqC;AACnC,SAAO,KAAK;;CAGd,UAAU,SAAk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