@glasstrace/sdk 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/session.ts","../src/fetch-classifier.ts","../src/span-processor.ts","../src/enriching-exporter.ts","../src/discovery-endpoint.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts","../../../node_modules/@opentelemetry/core/src/semconv.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/@opentelemetry/resources/src/default-service-name.ts","../../../node_modules/@opentelemetry/resources/src/utils.ts","../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/version.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../src/lifecycle.ts","../src/coexistence.ts","../src/otel-config.ts","../src/context-manager.ts","../src/heartbeat.ts","../src/runtime-state.ts","../src/register.ts","../src/config-wrapper.ts","../src/capture-error.ts","../src/correlation-id.ts"],"sourcesContent":["import type { SdkDiagnosticCode } from \"@glasstrace/protocol\";\n\n/**\n * Internal SDK error class with a typed diagnostic code.\n * Caught at the boundary and converted to a log message + diagnostic entry.\n * Never thrown to the developer.\n */\nexport class SdkError extends Error {\n readonly code: SdkDiagnosticCode;\n\n constructor(code: SdkDiagnosticCode, message: string, cause?: Error) {\n super(message, { cause });\n this.name = \"SdkError\";\n this.code = code;\n }\n}\n","import { SessionIdSchema } from \"@glasstrace/protocol\";\nimport type { SessionId } from \"@glasstrace/protocol\";\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\n\n/**\n * Lazy-loaded hash function. Uses Node.js `node:crypto` when available,\n * falling back to a deterministic non-cryptographic hash (FNV-1a) in\n * environments where `node:crypto` cannot be resolved (Edge Runtime,\n * browser bundles).\n *\n * Session IDs are identifiers, not security-sensitive values, so a\n * non-cryptographic hash is acceptable as a fallback.\n */\nlet hashFn: ((input: string) => string) | null = null;\n\n/**\n * FNV-1a hash producing an 8-character hex string.\n * Used as a fallback when `node:crypto` is unavailable.\n * Not cryptographically secure, but deterministic and fast.\n */\nfunction fnv1aHash(input: string): string {\n let hash = 0x811c9dc5; // FNV offset basis (32-bit)\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193); // FNV prime\n hash >>>= 0; // keep unsigned 32-bit\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n/**\n * Returns a hash function, resolving `node:crypto` on first call.\n * Thread-safe: worst case two calls both resolve — same result either way.\n */\nfunction getHashFn(): (input: string) => string {\n if (hashFn) return hashFn;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { createHash } = require(\"node:crypto\") as typeof import(\"node:crypto\");\n hashFn = (input: string) =>\n createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 16);\n } catch {\n // node:crypto unavailable — use FNV-1a fallback.\n // Pad to 16 chars by double-hashing the first and second halves.\n hashFn = (input: string) => {\n const h1 = fnv1aHash(input);\n const h2 = fnv1aHash(input + \"\\0\");\n return (h1 + h2).slice(0, 16);\n };\n }\n\n return hashFn;\n}\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedGlasstraceEnv: string | undefined = process.env.GLASSTRACE_ENV;\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Resets the lazy-loaded hash function. For testing only.\n * @internal\n */\nexport function _resetHashFnForTesting(): void {\n hashFn = null;\n}\n\n/**\n * Forces the fallback (FNV-1a) hash function. For testing only.\n * @internal\n */\nexport function _useFallbackHashForTesting(): void {\n hashFn = (input: string) => {\n const h1 = fnv1aHash(input);\n const h2 = fnv1aHash(input + \"\\0\");\n return (h1 + h2).slice(0, 16);\n };\n}\n\n/**\n * Derives a deterministic session ID from the given inputs.\n * Uses SHA-256 (truncated to 16 hex chars) when `node:crypto` is available,\n * or a deterministic FNV-1a hash as a fallback in non-Node environments.\n *\n * @param apiKey - The project's API key (or anonymous placeholder).\n * @param origin - The origin string identifying the deployment environment.\n * @param date - UTC date as YYYY-MM-DD.\n * @param windowIndex - Zero-based index of the 4-hour activity window within the day.\n * @returns A 16-character hex SessionId.\n */\nexport function deriveSessionId(\n apiKey: string,\n origin: string,\n date: string,\n windowIndex: number,\n): SessionId {\n const input = JSON.stringify([apiKey, origin, date, windowIndex]);\n const hash = getHashFn()(input);\n return SessionIdSchema.parse(hash);\n}\n\n/**\n * Returns the origin string for the current process.\n * If GLASSTRACE_ENV is set, returns that value.\n * Otherwise returns `localhost:{PORT}` (PORT defaults to 3000).\n *\n * @returns The origin string used as a session derivation input.\n */\nexport function getOrigin(): string {\n if (cachedGlasstraceEnv) {\n return cachedGlasstraceEnv;\n }\n return `localhost:${cachedPort}`;\n}\n\n/**\n * Returns the current UTC date as a YYYY-MM-DD string.\n *\n * @returns The UTC date formatted as \"YYYY-MM-DD\".\n */\nexport function getDateString(): string {\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(now.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n\n/**\n * Tracks the current session state with 4-hour window tracking.\n * Instantiated once by the orchestrator.\n */\nexport class SessionManager {\n private windowIndex: number = 0;\n private lastActivityTimestamp: number = 0;\n private lastDate: string = \"\";\n private lastApiKey: string = \"\";\n private currentSessionId: SessionId | null = null;\n\n /**\n * Returns the current session ID, deriving a new one if:\n * - More than 4 hours have elapsed since last activity\n * - The UTC date has changed (resets window index to 0)\n * - The API key has changed (e.g., deferred anonymous key swap)\n * - This is the first call\n *\n * @param apiKey - The project's API key used in session derivation.\n * @returns The current or newly derived SessionId.\n */\n getSessionId(apiKey: string): SessionId {\n const now = Date.now();\n const currentDate = getDateString();\n const origin = getOrigin();\n\n const elapsed = now - this.lastActivityTimestamp;\n const dateChanged = currentDate !== this.lastDate;\n const apiKeyChanged = apiKey !== this.lastApiKey;\n\n if (dateChanged) {\n // New UTC day: reset window index\n this.windowIndex = 0;\n this.lastDate = currentDate;\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (apiKeyChanged) {\n // API key changed (e.g., anonymous key resolved): re-derive with same window\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {\n // First call or gap exceeding 4 hours: increment window\n if (this.currentSessionId !== null) {\n this.windowIndex++;\n }\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n this.lastDate = currentDate;\n }\n\n this.lastActivityTimestamp = now;\n return this.currentSessionId;\n }\n}\n","/**\n * The set of recognized fetch target categories.\n */\nexport type FetchTarget = \"supabase\" | \"stripe\" | \"internal\" | \"unknown\";\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Classifies an outbound fetch target URL into a known category.\n * Classification is case-insensitive and based on the URL hostname.\n * Uses dot-boundary matching to avoid false positives (e.g. evilstripe.com).\n *\n * Returns one of: 'supabase', 'stripe', 'internal', or 'unknown'.\n */\nexport function classifyFetchTarget(url: string): FetchTarget {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return \"unknown\";\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n if (\n hostname === \"supabase.co\" ||\n hostname.endsWith(\".supabase.co\") ||\n hostname === \"supabase.in\" ||\n hostname.endsWith(\".supabase.in\")\n ) {\n return \"supabase\";\n }\n\n if (hostname === \"stripe.com\" || hostname.endsWith(\".stripe.com\")) {\n return \"stripe\";\n }\n\n const internalOrigin = `localhost:${cachedPort}`;\n const parsedPort = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n const urlOrigin = `${hostname}:${parsedPort}`;\n\n if (urlOrigin === internalOrigin) {\n return \"internal\";\n }\n\n return \"unknown\";\n}\n","import type { SpanProcessor, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport type { Span } from \"@opentelemetry/sdk-trace-base\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\n\n/**\n * Lightweight SpanProcessor that delegates to a wrapped processor.\n *\n * All glasstrace.* attribute enrichment has been moved to {@link GlasstraceExporter}\n * (see enriching-exporter.ts), which enriches spans at export time. This resolves:\n * - Cold-start spans are buffered in the exporter, not dropped\n * - Vercel's CompositeSpanProcessor skips onEnding(); the exporter doesn't need it\n * - Session ID is computed at export time with the resolved API key\n *\n * This class is retained for backward compatibility. New code should use\n * GlasstraceExporter directly.\n *\n * @deprecated Use GlasstraceExporter for span enrichment. This processor is now a pass-through.\n */\nexport class GlasstraceSpanProcessor implements SpanProcessor {\n private readonly wrappedProcessor: SpanProcessor;\n\n /* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */\n constructor(\n wrappedProcessor: SpanProcessor,\n _sessionManager?: SessionManager,\n _apiKey?: string | (() => string),\n _getConfig?: () => CaptureConfig,\n _environment?: string,\n ) {\n /* eslint-enable @typescript-eslint/no-unused-vars */\n this.wrappedProcessor = wrappedProcessor;\n }\n\n onStart(span: Span, parentContext: Parameters<SpanProcessor[\"onStart\"]>[1]): void {\n this.wrappedProcessor.onStart(span, parentContext);\n }\n\n onEnd(readableSpan: ReadableSpan): void {\n this.wrappedProcessor.onEnd(readableSpan);\n }\n\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n}\n","import { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport type { ExportResult } from \"@opentelemetry/core\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\nimport { classifyFetchTarget } from \"./fetch-classifier.js\";\nimport { recordSpansExported, recordSpansDropped } from \"./health-collector.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { maybeShowServerActionNudge } from \"./nudge/error-nudge.js\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\n\n/**\n * Sentinel value indicating the API key has not yet been resolved.\n */\nexport const API_KEY_PENDING = \"pending\" as const;\n\n/**\n * Maximum number of spans to buffer while waiting for key resolution.\n * Prevents unbounded memory growth if the key never resolves.\n */\nconst MAX_PENDING_SPANS = 1024;\n\n\n/**\n * Options for constructing a {@link GlasstraceExporter}.\n */\nexport interface GlasstraceExporterOptions {\n getApiKey: () => string;\n sessionManager: SessionManager;\n getConfig: () => CaptureConfig;\n environment: string | undefined;\n endpointUrl: string;\n createDelegate: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n /** When true, logs diagnostic details about enrichment decisions via sdkLog. */\n verbose?: boolean;\n}\n\ninterface PendingBatch {\n spans: ReadableSpan[];\n resultCallback: (result: ExportResult) => void;\n}\n\n/**\n * A SpanExporter that enriches spans with glasstrace.* attributes at export\n * time, then delegates to a real OTLP exporter.\n *\n * This design resolves three issues:\n * - Spans emitted before the API key resolves are buffered (not dropped)\n * and flushed once the key is available.\n * - Enrichment happens in the exporter (not onEnding), so it works\n * on Vercel where CompositeSpanProcessor does not forward onEnding().\n * - Session ID is computed at export time using the resolved API key,\n * not the \"pending\" placeholder.\n */\nexport class GlasstraceExporter implements SpanExporter {\n private readonly getApiKey: () => string;\n private readonly sessionManager: SessionManager;\n private readonly getConfig: () => CaptureConfig;\n private readonly environment: string | undefined;\n private readonly endpointUrl: string;\n private readonly createDelegateFn: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n private readonly verbose: boolean;\n\n private delegate: SpanExporter | null = null;\n private delegateKey: string | null = null;\n private pendingBatches: PendingBatch[] = [];\n private pendingSpanCount = 0;\n private overflowLogged = false;\n\n constructor(options: GlasstraceExporterOptions) {\n this.getApiKey = options.getApiKey;\n this.sessionManager = options.sessionManager;\n this.getConfig = options.getConfig;\n this.environment = options.environment;\n this.endpointUrl = options.endpointUrl;\n this.createDelegateFn = options.createDelegate;\n this.verbose = options.verbose ?? false;\n\n // Brand for coexistence detection — allows isGlasstraceProcessorPresent()\n // to detect our exporter across bundled copies via a global symbol registry.\n (this as unknown as Record<symbol, boolean>)[Symbol.for(\"glasstrace.exporter\")] = true;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) {\n // Buffer raw (unenriched) spans — enrichment deferred to flush time\n // so session IDs are computed with the resolved key, not \"pending\".\n this.bufferSpans(spans, resultCallback);\n return;\n }\n\n // Key is available — enrich and export\n const enrichedSpans = spans.map((span) => this.enrichSpan(span));\n const exporter = this.ensureDelegate();\n if (exporter) {\n exporter.export(enrichedSpans, (result) => {\n if (result.code !== 0) {\n sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n }\n resultCallback(result);\n });\n recordSpansExported(enrichedSpans.length);\n } else {\n // No delegate factory — spans are discarded, count as dropped\n recordSpansDropped(enrichedSpans.length);\n resultCallback({ code: 0 });\n }\n }\n\n /**\n * Called when the API key transitions from \"pending\" to a resolved value.\n * Creates the delegate exporter and flushes all buffered spans.\n */\n notifyKeyResolved(): void {\n this.flushPending();\n }\n\n async shutdown(): Promise<void> {\n const currentKey = this.getApiKey();\n if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n } else if (this.pendingBatches.length > 0) {\n console.warn(\n `[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans — API key never resolved, spans lost.`,\n );\n recordSpansDropped(this.pendingSpanCount);\n // Complete pending callbacks so pipeline doesn't hang\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n }\n\n if (this.delegate) {\n return this.delegate.shutdown();\n }\n }\n\n /**\n * Flushes any pending buffered spans (if the API key has resolved) and\n * delegates to the underlying exporter's forceFlush to drain its queue.\n */\n forceFlush(): Promise<void> {\n // Flush pending batches if the key has resolved but they haven't been\n // drained yet (e.g., key resolved between the last export and this flush).\n if (this.getApiKey() !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n }\n\n if (this.delegate?.forceFlush) {\n return this.delegate.forceFlush();\n }\n return Promise.resolve();\n }\n\n /**\n * Enriches a ReadableSpan with all glasstrace.* attributes.\n * Returns a new ReadableSpan wrapper; the original span is not mutated.\n *\n * Only {@link SessionManager.getSessionId} is individually guarded because\n * it calls into crypto and schema validation — a session ID failure should\n * not prevent the rest of enrichment. The other helper calls\n * ({@link deriveErrorCategory}, {@link deriveOrmProvider},\n * {@link classifyFetchTarget}) are pure functions on typed string inputs\n * and rely on the outer catch for any unexpected failure.\n *\n * On total failure, returns the original span unchanged.\n */\n private enrichSpan(span: ReadableSpan): ReadableSpan {\n try {\n const attrs = span.attributes ?? {};\n const name = span.name ?? \"\";\n const extra: Record<string, string | number | boolean> = {};\n\n // glasstrace.trace.type\n extra[ATTR.TRACE_TYPE] = \"server\";\n\n // glasstrace.session.id — calls external code (crypto, schema validation)\n try {\n const sessionId = this.sessionManager.getSessionId(this.getApiKey());\n extra[ATTR.SESSION_ID] = sessionId;\n } catch { /* session ID omitted */ }\n\n // glasstrace.environment\n const env = this.environment ?? process.env.GLASSTRACE_ENV;\n if (env) {\n extra[ATTR.ENVIRONMENT] = env;\n }\n\n // glasstrace.correlation.id\n const existingCid = attrs[\"glasstrace.correlation.id\"];\n if (typeof existingCid === \"string\") {\n extra[ATTR.CORRELATION_ID] = existingCid;\n }\n\n // glasstrace.route\n // OTel's AttributeValue allows non-string shapes (number, boolean,\n // array) on `http.route`. A custom instrumentation could set a\n // non-string there and blow up `.trim()` / `.startsWith()` calls\n // below; guard with typeof so malformed route attributes fall back\n // to `name` (always a string per OTel span contract) instead of\n // disabling all enrichment for the span.\n const rawRoute = attrs[\"http.route\"];\n const route = typeof rawRoute === \"string\" ? rawRoute : name;\n if (route) {\n extra[ATTR.ROUTE] = route;\n }\n\n // glasstrace.trpc.procedure\n // Extract tRPC procedure name from URL path (DISC-1215).\n // Pattern: /api/trpc/{procedure} where procedure is a single path segment\n // that may contain dots (polls.modify) or commas (batched: proc1,proc2).\n const rawUrl = attrs[\"http.url\"] ?? attrs[\"url.full\"] ?? attrs[\"http.target\"];\n const trpcUrl = typeof rawUrl === \"string\" ? rawUrl : undefined;\n if (trpcUrl) {\n const trpcMatch = trpcUrl.match(/\\/api\\/trpc\\/([^/?#]+)/);\n if (trpcMatch) {\n let procedure: string;\n try {\n procedure = decodeURIComponent(trpcMatch[1]);\n } catch {\n procedure = trpcMatch[1];\n }\n if (procedure) {\n extra[ATTR.TRPC_PROCEDURE] = procedure;\n }\n }\n }\n\n // glasstrace.http.method\n const method =\n (attrs[\"http.method\"] as string | undefined) ??\n (attrs[\"http.request.method\"] as string | undefined);\n if (method) {\n extra[ATTR.HTTP_METHOD] = method;\n }\n\n // glasstrace.next.action.detected — DISC-1253.\n // Heuristic: a POST to a page route (not /api/*, not /_next/*) is\n // almost always a Server Action in idiomatic Next.js App Router code.\n // We cannot identify the specific action without extra metadata —\n // DISC-1254 covers that path. Label \"detected\" not \"confirmed\" to\n // leave room for rare false-positive cases (legacy form POSTs,\n // hand-rolled page-route POST handlers).\n //\n // `route` may come from `http.route` (a bare path like \"/login\") or\n // fall back to `span.name` (which Next.js formats as \"POST /login\",\n // sometimes \"middleware POST\", etc.). We normalize to the leading\n // path segment before matching so a span named \"POST /api/auth\"\n // does not slip past the `/api/` guard and get falsely flagged.\n const actionRoute = extractLeadingPath(route);\n if (method === \"POST\" && actionRoute) {\n const isApiRoute = actionRoute === \"/api\" || actionRoute.startsWith(\"/api/\");\n const isInternalRoute = actionRoute.startsWith(\"/_next/\");\n if (!isApiRoute && !isInternalRoute) {\n extra[ATTR.NEXT_ACTION_DETECTED] = true;\n // Developer-facing nudge (once per process): when a Server Action\n // trace is detected but no glasstrace.correlation.id is present,\n // the Glasstrace browser extension is likely absent. Installing it\n // unlocks per-action identification via the Next-Action header\n // (DISC-1254 covers capture).\n if (typeof extra[ATTR.CORRELATION_ID] !== \"string\") {\n maybeShowServerActionNudge();\n }\n }\n }\n\n // glasstrace.http.status_code\n const statusCode =\n (attrs[\"http.status_code\"] as number | undefined) ??\n (attrs[\"http.response.status_code\"] as number | undefined);\n if (statusCode !== undefined) {\n extra[ATTR.HTTP_STATUS_CODE] = statusCode;\n }\n\n // Infer error status when Next.js timing race reports 200 on error spans.\n // Three signals indicate an error span:\n // 1. span.status.code === ERROR (explicit, most reliable)\n // 2. span.events contains an \"exception\" event (recordException fired)\n // 3. span attributes contain exception.type or exception.message\n // The timing race in Next.js dev server (DISC-1134) can cause span\n // export before closeSpanWithError runs, leaving status.code as UNSET.\n // Exception events from recordException may still be present (DISC-1204).\n // Does NOT trigger when status is explicitly OK (handler recovered).\n const isErrorByStatus = span.status?.code === SpanStatusCode.ERROR;\n const isErrorByEvent = hasExceptionEvent(span);\n const isErrorByAttrs = typeof attrs[\"exception.type\"] === \"string\"\n || typeof attrs[\"exception.message\"] === \"string\";\n const statusNotExplicitlyOK = span.status?.code !== SpanStatusCode.OK;\n\n if (this.verbose && method) {\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": status.code=${span.status?.code}, ` +\n `http.status_code=${statusCode}, isErrorByStatus=${isErrorByStatus}, ` +\n `isErrorByEvent=${isErrorByEvent}, isErrorByAttrs=${isErrorByAttrs}`,\n );\n }\n\n if (method && statusNotExplicitlyOK && (isErrorByStatus || isErrorByEvent || isErrorByAttrs)) {\n if (statusCode === undefined || statusCode === 0 || statusCode === 200) {\n const httpErrorType = attrs[\"error.type\"];\n if (typeof httpErrorType === \"string\") {\n const parsed = parseInt(httpErrorType, 10);\n if (!isNaN(parsed) && parsed >= 400 && parsed <= 599) {\n extra[ATTR.HTTP_STATUS_CODE] = parsed;\n } else {\n extra[ATTR.HTTP_STATUS_CODE] = 500;\n }\n } else {\n extra[ATTR.HTTP_STATUS_CODE] = 500;\n }\n\n if (this.verbose) {\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": inferred status_code=${extra[ATTR.HTTP_STATUS_CODE]} ` +\n `(was ${statusCode}), error.type=${attrs[\"error.type\"]}`,\n );\n }\n }\n // If statusCode is already >= 400, leave it alone (correct value)\n }\n\n // glasstrace.http.duration_ms\n if (span.startTime && span.endTime) {\n const [startSec, startNano] = span.startTime;\n const [endSec, endNano] = span.endTime;\n const durationMs =\n (endSec - startSec) * 1000 + (endNano - startNano) / 1_000_000;\n if (durationMs >= 0) {\n extra[ATTR.HTTP_DURATION_MS] = durationMs;\n }\n }\n\n // glasstrace.error.message + glasstrace.error.code + glasstrace.error.category\n // Primary source: span attributes. Fallback: exception event attributes.\n // OTel's recordException() stores exception info in events, not span\n // attributes, so the fallback is needed for most error spans (DISC-1204).\n // Event fallback is gated on statusNotExplicitlyOK to avoid labeling\n // recovered OK spans with error metadata from handled exceptions.\n const eventDetails = statusNotExplicitlyOK\n ? getExceptionEventDetails(span)\n : { type: undefined, message: undefined };\n\n const errorMessage = attrs[\"exception.message\"];\n if (typeof errorMessage === \"string\") {\n extra[ATTR.ERROR_MESSAGE] = errorMessage;\n } else if (eventDetails.message) {\n extra[ATTR.ERROR_MESSAGE] = eventDetails.message;\n }\n\n // Guard against non-string attribute values (OTel attributes can be\n // string | number | boolean | Array) to prevent toLowerCase() throws.\n const errorType = attrs[\"exception.type\"];\n if (typeof errorType === \"string\") {\n extra[ATTR.ERROR_CODE] = errorType;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(errorType);\n } else if (eventDetails.type) {\n extra[ATTR.ERROR_CODE] = eventDetails.type;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(eventDetails.type);\n }\n\n if (this.verbose && (extra[ATTR.ERROR_MESSAGE] || extra[ATTR.ERROR_CODE])) {\n const msgSource = typeof errorMessage === \"string\" ? \"attrs\"\n : eventDetails.message ? \"event\" : \"none\";\n const typeSource = typeof errorType === \"string\" ? \"attrs\"\n : eventDetails.type ? \"event\" : \"none\";\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": error.message source=${msgSource}, ` +\n `error.code source=${typeSource}`,\n );\n }\n\n // glasstrace.error.field\n const errorField = attrs[\"error.field\"];\n if (typeof errorField === \"string\") {\n extra[ATTR.ERROR_FIELD] = errorField;\n }\n\n // glasstrace.error.response_body (DISC-1216 Phase 1 — passthrough)\n // Adapters (e.g., future tRPC handler wrapper) should set error response\n // body data on `glasstrace.internal.response_body` — a Glasstrace-internal\n // attribute that is only promoted to the public namespace when the config\n // flag is enabled. This prevents response body leakage when disabled.\n if (this.getConfig().errorResponseBodies) {\n const responseBody = attrs[\"glasstrace.internal.response_body\"];\n if (typeof responseBody === \"string\") {\n extra[ATTR.ERROR_RESPONSE_BODY] = responseBody.slice(0, 500);\n }\n }\n\n // glasstrace.orm.*\n const spanAny = span as unknown as Record<string, { name?: string } | undefined>;\n const instrumentationName =\n (spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name) ?? \"\";\n const ormProvider = deriveOrmProvider(instrumentationName);\n if (ormProvider) {\n extra[ATTR.ORM_PROVIDER] = ormProvider;\n\n const table = attrs[\"db.sql.table\"];\n const prismaModel = attrs[\"db.prisma.model\"];\n const model = typeof table === \"string\" ? table\n : typeof prismaModel === \"string\" ? prismaModel\n : undefined;\n if (model) {\n extra[ATTR.ORM_MODEL] = model;\n }\n\n const operation = attrs[\"db.operation\"];\n if (typeof operation === \"string\") {\n extra[ATTR.ORM_OPERATION] = operation;\n }\n }\n\n // glasstrace.fetch.target\n const httpUrl = attrs[\"http.url\"];\n const fullUrl = attrs[\"url.full\"];\n const url = typeof httpUrl === \"string\" ? httpUrl\n : typeof fullUrl === \"string\" ? fullUrl\n : undefined;\n if (url && span.kind === SpanKind.CLIENT) {\n extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);\n }\n\n return createEnrichedSpan(span, extra);\n } catch {\n // Return original span unchanged so the export pipeline is never blocked\n return span;\n }\n }\n\n /**\n * Lazily creates the delegate OTLP exporter once the API key is resolved.\n * Recreates the delegate if the key has changed (e.g., after key rotation)\n * so the Authorization header stays current.\n */\n private ensureDelegate(): SpanExporter | null {\n if (!this.createDelegateFn) return null;\n\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) return null;\n\n // Recreate delegate if the key has changed since last creation\n if (this.delegate && this.delegateKey === currentKey) {\n return this.delegate;\n }\n\n // Shut down old delegate if key rotated. Catch errors to prevent\n // unhandled rejections from crashing the process during rotation.\n if (this.delegate) {\n void this.delegate.shutdown?.().catch(() => {});\n }\n\n this.delegate = this.createDelegateFn(this.endpointUrl, {\n Authorization: `Bearer ${currentKey}`,\n });\n this.delegateKey = currentKey;\n return this.delegate;\n }\n\n /**\n * Buffers raw (unenriched) spans while the API key is pending.\n * Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.\n * Re-checks the key after buffering to close the race window where\n * the key resolves between the caller's check and this buffer call.\n */\n private bufferSpans(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n this.pendingBatches.push({ spans, resultCallback });\n this.pendingSpanCount += spans.length;\n\n // Evict oldest batches if over limit\n while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {\n const evicted = this.pendingBatches.shift()!;\n this.pendingSpanCount -= evicted.spans.length;\n recordSpansDropped(evicted.spans.length);\n // Complete callback so pipeline doesn't hang\n evicted.resultCallback({ code: 0 });\n\n if (!this.overflowLogged) {\n this.overflowLogged = true;\n console.warn(\n \"[glasstrace] Pending span buffer overflow — oldest spans evicted. \" +\n \"This usually means the API key is taking too long to resolve.\",\n );\n }\n }\n\n // Re-check: if the key resolved between the caller's check and now,\n // flush immediately to avoid spans stuck in the buffer.\n if (this.getApiKey() !== API_KEY_PENDING) {\n this.flushPending();\n }\n }\n\n /**\n * Flushes all buffered spans through the delegate exporter.\n * Enriches spans at flush time (not buffer time) so that session IDs\n * are computed with the resolved API key instead of the \"pending\" sentinel.\n */\n private flushPending(): void {\n if (this.pendingBatches.length === 0) return;\n\n const exporter = this.ensureDelegate();\n if (!exporter) {\n // No delegate factory — complete callbacks and count as dropped\n let discardedCount = 0;\n for (const batch of this.pendingBatches) {\n discardedCount += batch.spans.length;\n batch.resultCallback({ code: 0 });\n }\n recordSpansDropped(discardedCount);\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n return;\n }\n\n const batches = this.pendingBatches;\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n\n for (const batch of batches) {\n // Enrich at flush time with the now-resolved key\n const enriched = batch.spans.map((span) => this.enrichSpan(span));\n exporter.export(enriched, (result) => {\n if (result.code !== 0) {\n sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n }\n batch.resultCallback(result);\n });\n recordSpansExported(enriched.length);\n }\n }\n\n}\n\n/**\n * Creates a ReadableSpan wrapper that inherits all properties from the\n * original span but overrides `attributes` to include additional entries.\n * The original span is not mutated.\n */\nfunction createEnrichedSpan(\n span: ReadableSpan,\n extra: Record<string, string | number | boolean>,\n): ReadableSpan {\n const enrichedAttributes = { ...span.attributes, ...extra };\n return Object.create(span, {\n attributes: {\n value: enrichedAttributes,\n enumerable: true,\n },\n }) as ReadableSpan;\n}\n\n/**\n * Returns true if the span has at least one \"exception\" event.\n * This signals that `span.recordException()` was called, even if\n * `span.setStatus(ERROR)` was not yet applied due to the timing race\n * in Next.js dev server (DISC-1204).\n */\nfunction hasExceptionEvent(span: ReadableSpan): boolean {\n return span.events?.some((e) => e.name === \"exception\") ?? false;\n}\n\n/**\n * Extracts exception.type and exception.message from the first \"exception\"\n * event on the span. Returns undefined values if not found.\n *\n * OTel's `recordException()` stores error details in event attributes, not\n * span attributes. The enrichment code needs this fallback to populate\n * glasstrace.error.message and glasstrace.error.code when the standard\n * span attributes are absent.\n */\nfunction getExceptionEventDetails(span: ReadableSpan): {\n type: string | undefined;\n message: string | undefined;\n} {\n const event = span.events?.find((e) => e.name === \"exception\");\n if (!event?.attributes) {\n return { type: undefined, message: undefined };\n }\n const type = event.attributes[\"exception.type\"];\n const message = event.attributes[\"exception.message\"];\n return {\n type: typeof type === \"string\" ? type : undefined,\n message: typeof message === \"string\" ? message : undefined,\n };\n}\n\n/**\n * Extracts the leading path from a route-or-span-name string so the\n * Server Action heuristic (DISC-1253) can match reliably regardless of\n * whether the value came from `http.route` (bare path, e.g. \"/login\")\n * or from `span.name` (Next.js-formatted, e.g. \"POST /login\" or\n * \"middleware POST /login\").\n *\n * Returns the first `/…`-prefixed token, or `undefined` if no such\n * token is present. Empty input yields `undefined` so callers can use\n * the result as a truthy guard.\n */\nexport function extractLeadingPath(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return undefined;\n\n // Fast path: already a bare path.\n if (trimmed.startsWith(\"/\")) {\n const firstSpace = trimmed.indexOf(\" \");\n return firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace);\n }\n\n // Fallback: scan for the first whitespace-separated token that looks\n // like a path. Handles \"POST /login\", \"middleware POST /login\", etc.\n for (const token of trimmed.split(/\\s+/)) {\n if (token.startsWith(\"/\")) {\n return token;\n }\n }\n\n return undefined;\n}\n\n/**\n * Derives ORM provider from the instrumentation library name.\n */\nexport function deriveOrmProvider(instrumentationName: string): string | null {\n const lower = instrumentationName.toLowerCase();\n if (lower.includes(\"prisma\")) {\n return \"prisma\";\n }\n if (lower.includes(\"drizzle\")) {\n return \"drizzle\";\n }\n return null;\n}\n\n/**\n * Derives error category from error type string.\n */\nexport function deriveErrorCategory(errorType: string): string {\n const lower = errorType.toLowerCase();\n if (lower.includes(\"validation\") || lower.includes(\"zod\")) {\n return \"validation\";\n }\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"fetch\") ||\n lower.includes(\"timeout\")\n ) {\n return \"network\";\n }\n if (lower.includes(\"auth\") || lower.includes(\"unauthorized\") || lower.includes(\"forbidden\")) {\n return \"auth\";\n }\n if (lower.includes(\"notfound\") || lower.includes(\"not_found\")) {\n return \"not-found\";\n }\n return \"internal\";\n}\n","import type { AnonApiKey, SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Checks whether the given Origin header is allowed for CORS access.\n *\n * Allowed origins:\n * - `chrome-extension://*` — any Chrome extension\n * - `moz-extension://*` — any Firefox extension\n * - `safari-web-extension://*` — any Safari extension\n * - Absent origin (same-origin / non-browser request)\n *\n * Replaced wildcard `*` to prevent arbitrary websites from\n * reading the anonymous API key from localhost.\n */\nfunction isAllowedOrigin(origin: string | null): boolean {\n if (origin === null) return true;\n if (origin.startsWith(\"chrome-extension://\")) return true;\n if (origin.startsWith(\"moz-extension://\")) return true;\n if (origin.startsWith(\"safari-web-extension://\")) return true;\n return false;\n}\n\n/**\n * Builds CORS headers for a given request origin.\n * Returns headers with `Access-Control-Allow-Origin` set to the origin\n * if allowed, otherwise omits that header entirely.\n */\nfunction buildCorsHeaders(origin: string | null): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Vary: \"Origin\",\n };\n\n if (origin && isAllowedOrigin(origin)) {\n headers[\"Access-Control-Allow-Origin\"] = origin;\n }\n\n return headers;\n}\n\n/**\n * Claim state returned by the `getClaimState` callback.\n *\n * - `claimed` — `true` when the anonymous key has been linked to an account.\n * - `accountHint` — optional masked identifier (e.g. `\"er***@example.com\"`)\n * for the browser extension to display to the user.\n */\nexport interface ClaimState {\n claimed: boolean;\n accountHint?: string;\n}\n\n/**\n * Creates a request handler for the `/__glasstrace/config` discovery endpoint.\n *\n * The returned handler checks if the request URL path is `/__glasstrace/config`.\n * If not, returns `null` (pass-through). If it matches, returns a `DiscoveryResponse`\n * with the anonymous key and current session ID.\n *\n * When `getClaimState` returns a non-null value with `claimed: true`, the\n * response includes `claimed` and (optionally) `accountHint` so the browser\n * extension can prompt the user to sign in.\n *\n * The triple guard (anonymous + dev + active) is enforced by the caller,\n * not by this module. If the handler is registered, it serves.\n */\nexport function createDiscoveryHandler(\n getAnonKey: () => Promise<AnonApiKey | null>,\n getSessionId: () => SessionId,\n getClaimState?: () => ClaimState | null,\n): (request: Request) => Promise<Response | null> {\n return async (request: Request): Promise<Response | null> => {\n // Check path match\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n\n if (url.pathname !== \"/__glasstrace/config\") {\n return null;\n }\n\n // Restrict CORS to known extension origins instead of wildcard\n const origin = request.headers.get(\"Origin\");\n const corsHeaders = buildCorsHeaders(origin);\n\n // Handle CORS preflight\n if (request.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n ...corsHeaders,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n },\n });\n }\n\n // Only allow GET requests\n if (request.method !== \"GET\") {\n return new Response(\n JSON.stringify({ error: \"method_not_allowed\" }),\n {\n status: 405,\n headers: corsHeaders,\n },\n );\n }\n\n try {\n // Get the anonymous key\n const anonKey = await getAnonKey();\n\n if (anonKey === null) {\n return new Response(\n JSON.stringify({ error: \"not_ready\" }),\n {\n status: 503,\n headers: corsHeaders,\n },\n );\n }\n\n // Get the current session ID\n const sessionId = getSessionId();\n\n // Build response body, conditionally including claim fields\n const responseBody: Record<string, unknown> = { key: anonKey, sessionId };\n const claimState = getClaimState?.();\n if (claimState?.claimed) {\n responseBody.claimed = true;\n if (claimState.accountHint) {\n responseBody.accountHint = claimState.accountHint;\n }\n }\n\n return new Response(\n JSON.stringify(responseBody),\n {\n status: 200,\n headers: corsHeaders,\n },\n );\n } catch {\n return new Response(\n JSON.stringify({ error: \"internal_error\" }),\n {\n status: 500,\n headers: corsHeaders,\n },\n );\n }\n };\n}\n\n// Exported for testing\nexport { isAllowedOrigin, buildCorsHeaders };\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n private _delegate: IOtlpExportDelegate<Internal>;\n constructor(delegate: IOtlpExportDelegate<Internal>) {\n this._delegate = delegate;\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._delegate.export(items, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n timeoutMillis: number;\n concurrencyLimit: number;\n compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n return timeoutMillis;\n }\n throw new Error(\n `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n );\n}\n\nexport function wrapStaticHeadersInFunction(\n headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n if (headers == null) {\n return undefined;\n }\n\n return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n return {\n timeoutMillis: validateTimeoutMillis(\n userProvidedConfiguration.timeoutMillis ??\n fallbackConfiguration.timeoutMillis ??\n defaultConfiguration.timeoutMillis\n ),\n concurrencyLimit:\n userProvidedConfiguration.concurrencyLimit ??\n fallbackConfiguration.concurrencyLimit ??\n defaultConfiguration.concurrencyLimit,\n compression:\n userProvidedConfiguration.compression ??\n fallbackConfiguration.compression ??\n defaultConfiguration.compression,\n };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n return {\n timeoutMillis: 10000,\n concurrencyLimit: 30,\n compression: 'none',\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n pushPromise(promise: Promise<void>): void;\n hasReachedLimit(): boolean;\n awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n private readonly _concurrencyLimit: number;\n private _sendingPromises: Promise<unknown>[] = [];\n\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit: number) {\n this._concurrencyLimit = concurrencyLimit;\n }\n\n public pushPromise(promise: Promise<void>): void {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n public hasReachedLimit(): boolean {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n\n public async awaitAll(): Promise<void> {\n await Promise.all(this._sendingPromises);\n }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n concurrencyLimit: number;\n}): IExportPromiseHandler {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Baggage, BaggageEntryMetadata } from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n if (!entry) return;\n const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n const keyPairPart =\n metadataSeparatorIndex === -1\n ? entry\n : entry.substring(0, metadataSeparatorIndex);\n\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n\n const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n if (!rawKey || !rawValue) return;\n let key: string;\n let value: string;\n try {\n key = decodeURIComponent(rawKey);\n value = decodeURIComponent(rawValue);\n } catch {\n return;\n }\n\n let metadata;\n if (\n metadataSeparatorIndex !== -1 &&\n metadataSeparatorIndex < entry.length - 1\n ) {\n const metadataString = entry.substring(metadataSeparatorIndex + 1);\n metadata = baggageEntryMetadataFromString(metadataString);\n }\n\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (typeof value === 'string' && value.length > 0) {\n value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n\n if (keyPair !== undefined && keyPair.value.length > 0) {\n result[keyPair.key] = keyPair.value;\n }\n });\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n const out: Attributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = (attributes as Record<string, unknown>)[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n const elementType = typeof element;\n\n if (elementType === type) {\n continue;\n }\n\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n );\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n } else if (raw === 'false') {\n return false;\n } else {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n );\n return false;\n }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n response: unknown\n): response is { partialSuccess: never } {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n T,\n>(): IOtlpResponseHandler<T> {\n return {\n handleResponse(response: T) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (\n response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0\n ) {\n return;\n }\n diag.warn(\n 'Received Partial Success response:',\n JSON.stringify(response.partialSuccess)\n );\n },\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { IExporterTransport } from './exporter-transport';\nimport type { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport type { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport type { DiagLogger } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n implements IOtlpExportDelegate<Internal>\n{\n private _diagLogger: DiagLogger;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<Internal, Response>;\n private _responseHandler: IOtlpResponseHandler<Response>;\n private _promiseQueue: IExportPromiseHandler;\n private _timeout: number;\n\n constructor(\n transport: IExporterTransport,\n serializer: ISerializer<Internal, Response>,\n responseHandler: IOtlpResponseHandler<Response>,\n promiseQueue: IExportPromiseHandler,\n timeout: number\n ) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n const serializedRequest = this._serializer.serializeRequest(\n internalRepresentation\n );\n\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n\n this._promiseQueue.pushPromise(\n this._transport.send(serializedRequest, this._timeout).then(\n response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(\n this._serializer.deserializeResponse(response.data)\n );\n } catch (e) {\n this._diagLogger.warn(\n 'Export succeeded but could not deserialize response - is the response specification compliant?',\n e,\n response.data\n );\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n } else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n } else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error:\n response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n } else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n },\n reason =>\n resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })\n )\n );\n }\n\n forceFlush(): Promise<void> {\n return this._promiseQueue.awaitAll();\n }\n\n async shutdown(): Promise<void> {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n components: {\n transport: IExporterTransport;\n serializer: ISerializer<Internal, Response>;\n promiseHandler: IExportPromiseHandler;\n },\n settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n return new OTLPExportDelegate(\n components.transport,\n components.serializer,\n createLoggingPartialSuccessResponseHandler(),\n components.promiseHandler,\n settings.timeout\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport type { Attributes } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\n\nexport function createResource(\n resource: ISdkResource,\n encoder: Encoder\n): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n return result;\n}\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(\n attributes: Attributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n\nexport function toKeyValue(\n key: string,\n value: unknown,\n encoder: Encoder\n): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values: IAnyValue[] = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values: IKeyValue[] = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n\n return {};\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return (\n BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes: Uint8Array): string => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\nimport type {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n encoder: Encoder\n): IExportTraceServiceRequest {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n record.instrumentationScope.version || ''\n }:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans: IResourceSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { ISerializer } from '../../i-serializer';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n const headers: Record<string, string> = {};\n Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n url: string;\n headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n userProvidedHeaders: HeadersFactory | undefined | null,\n fallbackHeaders: HeadersFactory | undefined | null,\n defaultHeaders: HeadersFactory\n): HeadersFactory {\n return async () => {\n const requiredHeaders = {\n ...(await defaultHeaders()),\n };\n const headers = {};\n\n // add fallback ones first\n if (fallbackHeaders != null) {\n Object.assign(headers, await fallbackHeaders());\n }\n\n // override with user-provided ones\n if (userProvidedHeaders != null) {\n Object.assign(\n headers,\n validateAndNormalizeHeaders(await userProvidedHeaders())\n );\n }\n\n // override required ones.\n return Object.assign(headers, requiredHeaders);\n };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n if (url == null) {\n return undefined;\n }\n try {\n // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n const base = globalThis.location?.href;\n return new URL(url, base).href;\n } catch {\n throw new Error(\n `Configuration: Could not parse user-provided export URL: '${url}'`\n );\n }\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n headers: mergeHeaders(\n userProvidedConfiguration.headers,\n fallbackConfiguration.headers,\n defaultConfiguration.headers\n ),\n url:\n validateUserProvidedUrl(userProvidedConfiguration.url) ??\n fallbackConfiguration.url ??\n defaultConfiguration.url,\n };\n}\n\nexport function getHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpHttpConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n headers: async () => requiredHeaders,\n url: 'http://localhost:4318/' + signalResourcePath,\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OtlpHttpConfiguration } from './otlp-http-configuration';\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n} from './otlp-http-configuration';\n\n// NOTE: do not change these imports to be actual imports, otherwise they WILL break `@opentelemetry/instrumentation-http`\nimport type * as http from 'http';\nimport type * as https from 'https';\n\nexport type HttpAgentFactory = (\n protocol: string\n) => http.Agent | https.Agent | Promise<http.Agent> | Promise<https.Agent>;\n\nexport interface OtlpNodeHttpConfiguration extends OtlpHttpConfiguration {\n /**\n * Factory function for creating agents.\n *\n * @remarks\n * Prefer using {@link httpAgentFactoryFromOptions} over manually writing a factory function wherever possible.\n * If using a factory function (`HttpAgentFactory`), **do not import `http.Agent` or `https.Agent`\n * statically at the top of the file**.\n * Instead, use dynamic `import()` or `require()` to load the module. This ensures that the `http` or `https`\n * module is not loaded before `@opentelemetry/instrumentation-http` can instrument it.\n */\n agentFactory: HttpAgentFactory;\n /**\n * User agent header string to be appended to the exporter's value as a prefix.\n * Availablie since v1.49.0 of the spec.\n * Ref: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#user-agent\n */\n userAgent?: string;\n}\n\nexport function httpAgentFactoryFromOptions(\n options: http.AgentOptions | https.AgentOptions\n): HttpAgentFactory {\n return async protocol => {\n const isInsecure = protocol === 'http:';\n const module = isInsecure ? import('http') : import('https');\n const { Agent } = await module;\n\n if (isInsecure) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n const { ca, cert, key, ...insecureOptions } =\n options as https.AgentOptions;\n return new Agent(insecureOptions);\n }\n return new Agent(options);\n };\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpNodeHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpNodeHttpConfiguration>,\n defaultConfiguration: OtlpNodeHttpConfiguration\n): OtlpNodeHttpConfiguration {\n return {\n ...mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n agentFactory:\n userProvidedConfiguration.agentFactory ??\n fallbackConfiguration.agentFactory ??\n defaultConfiguration.agentFactory,\n userAgent: userProvidedConfiguration.userAgent,\n };\n}\n\nexport function getNodeHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpNodeHttpConfiguration {\n return {\n ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport type { ExportResponse } from '../export-response';\nimport {\n isExportHTTPErrorRetryable,\n parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\n\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(\n request: typeof https.request | typeof http.request,\n url: string,\n headers: Record<string, string>,\n compression: 'gzip' | 'none',\n userAgent: string | undefined,\n agent: http.Agent | https.Agent,\n data: Uint8Array,\n timeoutMillis: number\n): Promise<ExportResponse> {\n return new Promise<ExportResponse>(resolve => {\n const parsedUrl = new URL(url);\n\n if (userAgent) {\n headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n } else {\n headers['User-Agent'] = DEFAULT_USER_AGENT;\n }\n\n const options: http.RequestOptions | https.RequestOptions = {\n hostname: parsedUrl.hostname,\n port: parsedUrl.port,\n path: parsedUrl.pathname,\n method: 'POST',\n headers,\n agent,\n };\n\n const req = request(options, (res: http.IncomingMessage) => {\n const responseData: Buffer[] = [];\n res.on('data', chunk => responseData.push(chunk));\n\n res.on('end', () => {\n if (res.statusCode && res.statusCode <= 299) {\n resolve({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n const error = new OTLPExporterError(\n res.statusMessage,\n res.statusCode,\n Buffer.concat(responseData).toString()\n );\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n res.on('error', (error: Error) => {\n // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n // the first call to resolve() will determine the final state.\n if (res.statusCode && res.statusCode <= 299) {\n // If the response is successful but an error occurs while reading the response,\n // we consider it a success since the data has been sent successfully.\n resolve({\n status: 'success',\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n error: error,\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n });\n\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n resolve({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n\n req.on('error', (error: Error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n resolve({\n status: 'retryable',\n error,\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n compressAndSend(req, compression, data, (error: Error) => {\n resolve({\n status: 'failure',\n error,\n });\n });\n });\n}\n\nexport function compressAndSend(\n req: http.ClientRequest,\n compression: 'gzip' | 'none',\n data: Uint8Array,\n onError: (error: Error) => void\n) {\n let dataStream = readableFromUint8Array(data);\n\n if (compression === 'gzip') {\n req.setHeader('Content-Encoding', 'gzip');\n dataStream = dataStream\n .on('error', onError)\n .pipe(zlib.createGzip())\n .on('error', onError);\n }\n\n dataStream.pipe(req).on('error', onError);\n}\n\nfunction readableFromUint8Array(buff: string | Uint8Array): Readable {\n const readable = new Readable();\n readable.push(buff);\n readable.push(null);\n\n return readable;\n}\n\nfunction isHttpTransportNetworkErrorRetryable(error: Error): boolean {\n const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]);\n\n if ('code' in error && typeof error.code === 'string') {\n return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n return (\n statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504\n );\n}\n\nexport function parseRetryAfterToMills(\n retryAfter?: string | undefined | null\n): number | undefined {\n if (retryAfter == null) {\n return undefined;\n }\n\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.214.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type * as https from 'https';\nimport type * as http from 'http';\nimport type { ExportResponse } from '../export-response';\nimport type { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport type { NodeHttpRequestParameters } from './node-http-transport-types';\n\ninterface Utils {\n agent: http.Agent | https.Agent;\n request: typeof http.request | typeof https.request;\n}\n\nclass HttpExporterTransport implements IExporterTransport {\n private _utils: Utils | null = null;\n private _parameters: NodeHttpRequestParameters;\n\n constructor(parameters: NodeHttpRequestParameters) {\n this._parameters = parameters;\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n const { agent, request } = await this._loadUtils();\n const headers = await this._parameters.headers();\n\n return sendWithHttp(\n request,\n this._parameters.url,\n headers,\n this._parameters.compression,\n this._parameters.userAgent,\n agent,\n data,\n timeoutMillis\n );\n }\n\n shutdown() {\n // intentionally left empty, nothing to do.\n }\n\n private async _loadUtils(): Promise<Utils> {\n let utils = this._utils;\n\n if (utils === null) {\n const protocol = new URL(this._parameters.url).protocol;\n const [agent, request] = await Promise.all([\n this._parameters.agentFactory(protocol),\n requestFunctionFactory(protocol),\n ]);\n utils = this._utils = { agent, request };\n }\n\n return utils;\n }\n}\n\nasync function requestFunctionFactory(\n protocol: string\n): Promise<typeof http.request | typeof https.request> {\n const module = protocol === 'http:' ? import('http') : import('https');\n const { request } = await module;\n return request;\n}\n\nexport function createHttpExporterTransport(\n parameters: NodeHttpRequestParameters\n): IExporterTransport {\n return new HttpExporterTransport(parameters);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from './exporter-transport';\nimport type { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n private _transport: IExporterTransport;\n\n constructor(transport: IExporterTransport) {\n this._transport = transport;\n }\n\n private retry(\n data: Uint8Array,\n timeoutMillis: number,\n inMillis: number\n ): Promise<ExportResponse> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(\n Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n 0\n );\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(\n `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n remainingTimeoutMillis\n )}ms, not retrying further.`\n );\n return result;\n }\n\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n\n if (result.status === 'success') {\n diag.verbose(\n `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n );\n } else if (result.status === 'retryable') {\n diag.info(\n `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n );\n } else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n\n return result;\n }\n\n shutdown() {\n return this._transport.shutdown();\n }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n // Underlying transport to wrap.\n transport: IExporterTransport;\n}): IExporterTransport {\n return new RetryingTransport(options.transport);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createOtlpExportDelegate } from './otlp-export-delegate';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nimport type { OtlpNodeHttpConfiguration } from './configuration/otlp-node-http-configuration';\n\nexport function createOtlpHttpExportDelegate<Internal, Response>(\n options: OtlpNodeHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpExportDelegate(\n {\n transport: createRetryingTransport({\n transport: createHttpExporterTransport(options),\n }),\n serializer: serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n },\n { timeout: options.timeoutMillis }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport { diag } from '@opentelemetry/api';\n\nfunction parseAndValidateTimeoutFromEnv(\n timeoutEnvVar: string\n): number | undefined {\n const envTimeout = getNumberFromEnv(timeoutEnvVar);\n if (envTimeout != null) {\n if (Number.isFinite(envTimeout) && envTimeout > 0) {\n return envTimeout;\n }\n diag.warn(\n `Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`\n );\n }\n\n return undefined;\n}\n\nfunction getTimeoutFromEnv(signalIdentifier: string) {\n const specificTimeout = parseAndValidateTimeoutFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`\n );\n const nonSpecificTimeout = parseAndValidateTimeoutFromEnv(\n 'OTEL_EXPORTER_OTLP_TIMEOUT'\n );\n\n return specificTimeout ?? nonSpecificTimeout;\n}\n\nfunction parseAndValidateCompressionFromEnv(\n compressionEnvVar: string\n): 'none' | 'gzip' | undefined {\n const compression = getStringFromEnv(compressionEnvVar)?.trim();\n\n if (compression == null || compression === 'none' || compression === 'gzip') {\n return compression;\n }\n\n diag.warn(\n `Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`\n );\n return undefined;\n}\n\nfunction getCompressionFromEnv(\n signalIdentifier: string\n): 'none' | 'gzip' | undefined {\n const specificCompression = parseAndValidateCompressionFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`\n );\n const nonSpecificCompression = parseAndValidateCompressionFromEnv(\n 'OTEL_EXPORTER_OTLP_COMPRESSION'\n );\n\n return specificCompression ?? nonSpecificCompression;\n}\n\nexport function getSharedConfigurationFromEnvironment(\n signalIdentifier: string\n): Partial<OtlpSharedConfiguration> {\n return {\n timeoutMillis: getTimeoutFromEnv(signalIdentifier),\n compression: getCompressionFromEnv(signalIdentifier),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStringFromEnv, parseKeyPairsIntoRecord } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { getSharedConfigurationFromEnvironment } from './shared-env-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { OtlpNodeHttpConfiguration } from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from './otlp-node-http-configuration';\n\nfunction getStaticHeadersFromEnv(\n signalIdentifier: string\n): Record<string, string> | undefined {\n const signalSpecificRawHeaders = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`\n );\n const nonSignalSpecificRawHeaders = getStringFromEnv(\n 'OTEL_EXPORTER_OTLP_HEADERS'\n );\n\n const signalSpecificHeaders = parseKeyPairsIntoRecord(\n signalSpecificRawHeaders\n );\n const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(\n nonSignalSpecificRawHeaders\n );\n\n if (\n Object.keys(signalSpecificHeaders).length === 0 &&\n Object.keys(nonSignalSpecificHeaders).length === 0\n ) {\n return undefined;\n }\n\n // headers are combined instead of overwritten, with the specific headers taking precedence over\n // the non-specific ones.\n return Object.assign(\n {},\n parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders),\n parseKeyPairsIntoRecord(signalSpecificRawHeaders)\n );\n}\n\nfunction appendRootPathToUrlIfNeeded(url: string): string | undefined {\n try {\n const parsedUrl = new URL(url);\n // This will automatically append '/' if there's no root path.\n return parsedUrl.toString();\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n}\n\nfunction appendResourcePathToUrl(\n url: string,\n path: string\n): string | undefined {\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n\n if (!url.endsWith('/')) {\n url = url + '/';\n }\n url += path;\n\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`\n );\n return undefined;\n }\n\n return url;\n}\n\nfunction getNonSpecificUrlFromEnv(\n signalResourcePath: string\n): string | undefined {\n const envUrl = getStringFromEnv('OTEL_EXPORTER_OTLP_ENDPOINT');\n if (envUrl === undefined) {\n return undefined;\n }\n return appendResourcePathToUrl(envUrl, signalResourcePath);\n}\n\nfunction getSpecificUrlFromEnv(signalIdentifier: string): string | undefined {\n const envUrl = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`\n );\n if (envUrl === undefined) {\n return undefined;\n }\n return appendRootPathToUrlIfNeeded(envUrl);\n}\n\nfunction readFileFromEnv(\n signalSpecificEnvVar: string,\n nonSignalSpecificEnvVar: string,\n warningMessage: string\n): Buffer | undefined {\n const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);\n const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);\n const filePath = signalSpecificPath ?? nonSignalSpecificPath;\n\n if (filePath != null) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), filePath));\n } catch {\n diag.warn(warningMessage);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction getClientCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n 'Failed to read client certificate chain file'\n );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n 'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n 'Failed to read client certificate private key file'\n );\n}\n\nfunction getRootCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CERTIFICATE',\n 'Failed to read root certificate file'\n );\n}\n\n/**\n * Reads and returns configuration from the environment\n *\n * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS)\n * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs)\n */\nexport function getNodeHttpConfigurationFromEnvironment(\n signalIdentifier: string,\n signalResourcePath: string\n): Partial<OtlpNodeHttpConfiguration> {\n return {\n ...getSharedConfigurationFromEnvironment(signalIdentifier),\n url:\n getSpecificUrlFromEnv(signalIdentifier) ??\n getNonSpecificUrlFromEnv(signalResourcePath),\n headers: wrapStaticHeadersInFunction(\n getStaticHeadersFromEnv(signalIdentifier)\n ),\n agentFactory: httpAgentFactoryFromOptions({\n keepAlive: true,\n ca: getRootCertificateFromEnv(signalIdentifier),\n cert: getClientCertificateFromEnv(signalIdentifier),\n key: getClientKeyFromEnv(signalIdentifier),\n }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n if (typeof config.headers === 'function') {\n return config.headers;\n }\n return wrapStaticHeadersInFunction(config.headers);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport type {\n HttpAgentFactory,\n OtlpNodeHttpConfiguration,\n} from './otlp-node-http-configuration';\nimport {\n getNodeHttpConfigurationDefaults,\n mergeOtlpNodeHttpConfigurationWithDefaults,\n} from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from '../index-node-http';\nimport { getNodeHttpConfigurationFromEnvironment } from './otlp-node-http-env-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\nfunction convertLegacyAgentOptions(\n config: OTLPExporterNodeConfigBase\n): HttpAgentFactory | undefined {\n if (typeof config.httpAgentOptions === 'function') {\n return config.httpAgentOptions;\n }\n\n let legacy = config.httpAgentOptions;\n if (config.keepAlive != null) {\n legacy = { keepAlive: config.keepAlive, ...legacy };\n }\n\n if (legacy != null) {\n return httpAgentFactoryFromOptions(legacy);\n } else {\n return undefined;\n }\n}\n\n/**\n * @deprecated this will be removed in 2.0\n * @param config\n * @param signalIdentifier\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyHttpOptions(\n config: OTLPExporterNodeConfigBase,\n signalIdentifier: string,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): OtlpNodeHttpConfiguration {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((config as any).metadata) {\n diag.warn('Metadata cannot be set when using http');\n }\n\n return mergeOtlpNodeHttpConfigurationWithDefaults(\n {\n url: config.url,\n headers: convertLegacyHeaders(config),\n concurrencyLimit: config.concurrencyLimit,\n timeoutMillis: config.timeoutMillis,\n compression: config.compression,\n agentFactory: convertLegacyAgentOptions(config),\n userAgent: config.userAgent,\n },\n getNodeHttpConfigurationFromEnvironment(\n signalIdentifier,\n signalResourcePath\n ),\n getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport {\n convertLegacyHttpOptions,\n createOtlpHttpExportDelegate,\n} from '@opentelemetry/otlp-exporter-base/node-http';\n\n/**\n * Collector Trace Exporter for Node\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBase<ReadableSpan[]>\n implements SpanExporter\n{\n constructor(config: OTLPExporterNodeConfigBase = {}) {\n super(\n createOtlpHttpExportDelegate(\n convertLegacyHttpOptions(config, 'TRACES', 'v1/traces', {\n 'Content-Type': 'application/json',\n }),\n JsonTraceSerializer\n )\n );\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n}\n","/**\n * SDK Lifecycle State Machine\n *\n * Provides a single source of truth for SDK state across three runtime\n * layers: core, auth, and OTel coexistence. (The CLI layer is handled\n * separately via the runtime state file bridge in SDK-026.)\n *\n * The core layer provides a shared typed event emitter that other layers\n * and SDK modules use for cross-layer communication.\n *\n * This module has NO imports from other SDK modules. It accepts a logger\n * function via initLifecycle() to avoid circular dependencies.\n *\n * @see docs/component-designs/sdk-lifecycle.md\n */\n\nimport { EventEmitter } from \"node:events\";\n\n// ---------------------------------------------------------------------------\n// State Enums\n// ---------------------------------------------------------------------------\n\nexport const CoreState = {\n IDLE: \"IDLE\",\n REGISTERING: \"REGISTERING\",\n KEY_PENDING: \"KEY_PENDING\",\n KEY_RESOLVED: \"KEY_RESOLVED\",\n ACTIVE: \"ACTIVE\",\n ACTIVE_DEGRADED: \"ACTIVE_DEGRADED\",\n SHUTTING_DOWN: \"SHUTTING_DOWN\",\n SHUTDOWN: \"SHUTDOWN\",\n PRODUCTION_DISABLED: \"PRODUCTION_DISABLED\",\n REGISTRATION_FAILED: \"REGISTRATION_FAILED\",\n} as const;\nexport type CoreState = (typeof CoreState)[keyof typeof CoreState];\n\nexport const AuthState = {\n ANONYMOUS: \"ANONYMOUS\",\n AUTHENTICATED: \"AUTHENTICATED\",\n CLAIMING: \"CLAIMING\",\n CLAIMED: \"CLAIMED\",\n} as const;\nexport type AuthState = (typeof AuthState)[keyof typeof AuthState];\n\nexport const OtelState = {\n UNCONFIGURED: \"UNCONFIGURED\",\n CONFIGURING: \"CONFIGURING\",\n OWNS_PROVIDER: \"OWNS_PROVIDER\",\n AUTO_ATTACHED: \"AUTO_ATTACHED\",\n PROCESSOR_PRESENT: \"PROCESSOR_PRESENT\",\n COEXISTENCE_FAILED: \"COEXISTENCE_FAILED\",\n} as const;\nexport type OtelState = (typeof OtelState)[keyof typeof OtelState];\n\n// ---------------------------------------------------------------------------\n// Valid Transitions\n// ---------------------------------------------------------------------------\n\nconst VALID_CORE_TRANSITIONS: Record<CoreState, readonly CoreState[]> = {\n [CoreState.IDLE]: [CoreState.REGISTERING, CoreState.REGISTRATION_FAILED, CoreState.SHUTTING_DOWN],\n [CoreState.REGISTERING]: [\n CoreState.KEY_PENDING,\n CoreState.PRODUCTION_DISABLED,\n CoreState.REGISTRATION_FAILED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.KEY_PENDING]: [\n CoreState.KEY_RESOLVED,\n CoreState.REGISTRATION_FAILED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.KEY_RESOLVED]: [\n CoreState.ACTIVE,\n CoreState.ACTIVE_DEGRADED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.ACTIVE]: [\n CoreState.ACTIVE_DEGRADED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.ACTIVE_DEGRADED]: [\n CoreState.ACTIVE,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.SHUTTING_DOWN]: [CoreState.SHUTDOWN],\n [CoreState.SHUTDOWN]: [],\n [CoreState.PRODUCTION_DISABLED]: [],\n [CoreState.REGISTRATION_FAILED]: [],\n};\n\nconst VALID_AUTH_TRANSITIONS: Record<AuthState, readonly AuthState[]> = {\n [AuthState.ANONYMOUS]: [AuthState.CLAIMING],\n [AuthState.AUTHENTICATED]: [AuthState.CLAIMING],\n [AuthState.CLAIMING]: [AuthState.CLAIMED],\n [AuthState.CLAIMED]: [AuthState.CLAIMING],\n};\n\nconst VALID_OTEL_TRANSITIONS: Record<OtelState, readonly OtelState[]> = {\n [OtelState.UNCONFIGURED]: [OtelState.CONFIGURING],\n [OtelState.CONFIGURING]: [\n OtelState.OWNS_PROVIDER,\n OtelState.AUTO_ATTACHED,\n OtelState.PROCESSOR_PRESENT,\n OtelState.COEXISTENCE_FAILED,\n ],\n [OtelState.OWNS_PROVIDER]: [],\n [OtelState.AUTO_ATTACHED]: [],\n [OtelState.PROCESSOR_PRESENT]: [],\n [OtelState.COEXISTENCE_FAILED]: [],\n};\n\n// ---------------------------------------------------------------------------\n// Event Types\n// ---------------------------------------------------------------------------\n\nexport interface SdkLifecycleEvents {\n \"core:state_changed\": { from: CoreState; to: CoreState };\n \"core:ready\": Record<string, never>;\n \"core:shutdown_started\": Record<string, never>;\n \"core:shutdown_completed\": Record<string, never>;\n\n \"auth:key_resolved\": { key: string; mode: \"anonymous\" | \"dev\" };\n \"auth:claim_started\": { accountId: string };\n \"auth:claim_completed\": { newKey: string; accountId: string };\n\n \"otel:configured\": { state: OtelState; scenario?: string };\n \"otel:injection_succeeded\": { method: string };\n \"otel:injection_failed\": { reason: string };\n \"otel:shutdown_started\": Record<string, never>;\n \"otel:shutdown_completed\": Record<string, never>;\n\n \"health:init_succeeded\": Record<string, never>;\n \"health:init_failed\": { error: string };\n \"health:heartbeat_tick\": Record<string, never>;\n \"health:config_refreshed\": Record<string, never>;\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _coreState: CoreState = CoreState.IDLE;\nlet _authState: AuthState = AuthState.ANONYMOUS;\nlet _otelState: OtelState = OtelState.UNCONFIGURED;\nlet _emitter: EventEmitter = new EventEmitter();\nlet _logger: ((level: \"warn\" | \"info\" | \"error\", message: string) => void) | null = null;\nlet _initialized = false;\nlet _initWarned = false;\nlet _coreReadyEmitted = false;\nlet _authInitialized = false;\nlet _emitting = false;\n\n// ---------------------------------------------------------------------------\n// Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Initialize the lifecycle module. Must be called before any state\n * transitions. Accepts a logger function to avoid importing SDK modules.\n *\n * Calling this twice logs a warning and is ignored.\n */\nexport function initLifecycle(options: {\n logger: (level: \"warn\" | \"info\" | \"error\", message: string) => void;\n}): void {\n if (_initialized) {\n options.logger(\"warn\", \"[glasstrace] initLifecycle() called twice — ignored.\");\n return;\n }\n _logger = options.logger;\n _initialized = true;\n}\n\n// ---------------------------------------------------------------------------\n// State Transitions\n// ---------------------------------------------------------------------------\n\n/** Warn once if lifecycle functions are called before initLifecycle(). */\nfunction warnIfNotInitialized(): void {\n if (!_initialized && !_initWarned) {\n _initWarned = true;\n // Use console.warn directly since _logger is null\n console.warn(\n \"[glasstrace] Lifecycle state changed before initLifecycle() was called. \" +\n \"Logger not available — errors will be silent.\",\n );\n }\n}\n\n/**\n * Transition the core lifecycle state. Invalid transitions are logged\n * and ignored — the state does not change.\n *\n * Guards against reentrant calls: if a listener calls setCoreState()\n * during emission, the inner transition completes first. The outer\n * call's post-transition events (core:ready, shutdown) check the\n * current state before emitting to avoid stale signals.\n */\nexport function setCoreState(to: CoreState): void {\n warnIfNotInitialized();\n\n const from = _coreState;\n if (from === to) return;\n\n const valid = VALID_CORE_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid core state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _coreState = to;\n\n // Guard against reentrant emission: if a listener calls setCoreState(),\n // the inner call will complete (including its own events). The outer call\n // skips its post-transition events to avoid stale/duplicate signals.\n if (_emitting) return;\n\n _emitting = true;\n try {\n emitSafe(\"core:state_changed\", { from, to });\n\n // Check current state (not `to`) in case a listener changed it\n const current = _coreState;\n\n if (!_coreReadyEmitted && (current === CoreState.ACTIVE || current === CoreState.ACTIVE_DEGRADED)) {\n _coreReadyEmitted = true;\n emitSafe(\"core:ready\", {});\n }\n\n if (current === CoreState.SHUTTING_DOWN) {\n emitSafe(\"core:shutdown_started\", {});\n }\n if (current === CoreState.SHUTDOWN) {\n emitSafe(\"core:shutdown_completed\", {});\n }\n } finally {\n _emitting = false;\n }\n}\n\n/**\n * Set the initial auth state. Must be called exactly once during\n * registration, before any auth transitions. This bypasses transition\n * validation because the initial state (ANONYMOUS vs AUTHENTICATED)\n * is determined by configuration, not by a runtime transition.\n *\n * Subsequent calls log a warning and are ignored.\n */\nexport function initAuthState(state: AuthState): void {\n if (_authInitialized) {\n _logger?.(\n \"warn\",\n \"[glasstrace] initAuthState() called after auth state already initialized. Ignored.\",\n );\n return;\n }\n _authInitialized = true;\n _authState = state;\n}\n\n/**\n * Transition the auth lifecycle state. Invalid transitions are logged\n * and ignored.\n */\nexport function setAuthState(to: AuthState): void {\n warnIfNotInitialized();\n\n const from = _authState;\n if (from === to) return;\n\n const valid = VALID_AUTH_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid auth state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _authState = to;\n}\n\n/**\n * Transition the OTel coexistence state. Invalid transitions are logged\n * and ignored.\n */\nexport function setOtelState(to: OtelState): void {\n warnIfNotInitialized();\n\n const from = _otelState;\n if (from === to) return;\n\n const valid = VALID_OTEL_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid OTel state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _otelState = to;\n}\n\n// ---------------------------------------------------------------------------\n// State Queries\n// ---------------------------------------------------------------------------\n\n/** Returns the current core lifecycle state. */\nexport function getCoreState(): CoreState {\n return _coreState;\n}\n\n/** Returns the current auth lifecycle state. */\nexport function getAuthState(): AuthState {\n return _authState;\n}\n\n/** Returns the current OTel coexistence state. */\nexport function getOtelState(): OtelState {\n return _otelState;\n}\n\n/** Returns the full internal state across all layers. */\nexport function getSdkState(): {\n core: CoreState;\n auth: AuthState;\n otel: OtelState;\n} {\n return {\n core: _coreState,\n auth: _authState,\n otel: _otelState,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Event Emitter\n// ---------------------------------------------------------------------------\n\n/**\n * Subscribe to a lifecycle event. The listener is synchronous.\n * Errors in listeners are caught and logged.\n */\nexport function onLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n _emitter.on(event, listener);\n}\n\n/**\n * Emit a typed lifecycle event. Exported so that other SDK modules\n * (auth, OTel, health) can emit their layer-specific events through\n * the shared emitter with type safety.\n */\nexport function emitLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n payload: SdkLifecycleEvents[K],\n): void {\n emitSafe(event, payload);\n}\n\n/**\n * Unsubscribe from a lifecycle event.\n */\nexport function offLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n _emitter.off(event, listener);\n}\n\n/**\n * Emit a lifecycle event. Each listener is called individually so that\n * an error in one listener does not prevent subsequent listeners from\n * running. Both synchronous throws and async rejections are caught and\n * logged via the lifecycle logger.\n */\nfunction emitSafe<K extends keyof SdkLifecycleEvents>(\n event: K,\n payload: SdkLifecycleEvents[K],\n): void {\n const listeners = _emitter.listeners(event);\n for (const listener of listeners) {\n try {\n const result = (listener as (p: SdkLifecycleEvents[K]) => unknown)(payload);\n // Catch async listeners that return a rejected promise\n if (result && typeof (result as Promise<unknown>).catch === \"function\") {\n (result as Promise<unknown>).catch((err: unknown) => {\n _logger?.(\n \"error\",\n `[glasstrace] Async error in lifecycle event listener for \"${event}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n }\n } catch (err) {\n _logger?.(\n \"error\",\n `[glasstrace] Error in lifecycle event listener for \"${event}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Readiness API\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true when the SDK is in ACTIVE or ACTIVE_DEGRADED state.\n */\nexport function isReady(): boolean {\n return _coreState === CoreState.ACTIVE || _coreState === CoreState.ACTIVE_DEGRADED;\n}\n\n/**\n * Resolves when the SDK reaches ACTIVE or ACTIVE_DEGRADED.\n * Rejects on PRODUCTION_DISABLED, REGISTRATION_FAILED, or timeout.\n *\n * Checks current state synchronously first — resolves/rejects immediately\n * if the SDK has already reached a terminal or ready state.\n */\nexport function waitForReady(timeoutMs = 30000): Promise<void> {\n // Check current state synchronously\n if (isReady()) {\n return Promise.resolve();\n }\n if (\n _coreState === CoreState.PRODUCTION_DISABLED ||\n _coreState === CoreState.REGISTRATION_FAILED ||\n _coreState === CoreState.SHUTTING_DOWN ||\n _coreState === CoreState.SHUTDOWN\n ) {\n return Promise.reject(new Error(`SDK is in terminal state: ${_coreState}`));\n }\n\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const listener = ({ to }: { from: CoreState; to: CoreState }) => {\n if (settled) return;\n if (to === CoreState.ACTIVE || to === CoreState.ACTIVE_DEGRADED) {\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n resolve();\n } else if (\n to === CoreState.PRODUCTION_DISABLED ||\n to === CoreState.REGISTRATION_FAILED ||\n to === CoreState.SHUTTING_DOWN ||\n to === CoreState.SHUTDOWN\n ) {\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n reject(new Error(`SDK reached terminal state: ${to}`));\n }\n };\n\n onLifecycleEvent(\"core:state_changed\", listener);\n\n if (timeoutMs > 0) {\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n reject(new Error(`waitForReady timed out after ${timeoutMs}ms (state: ${_coreState})`));\n }, timeoutMs);\n // unref() so this timer doesn't prevent process exit\n if (typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n }\n });\n}\n\n/**\n * Simplified public state query for external consumers.\n * Hides implementation details like coexistence scenarios.\n */\nexport function getStatus(): {\n ready: boolean;\n mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n} {\n let mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n if (_coreState === CoreState.PRODUCTION_DISABLED) {\n mode = \"disabled\";\n } else if (_authState === AuthState.CLAIMING || _authState === AuthState.CLAIMED) {\n mode = \"claiming\";\n } else if (_authState === AuthState.AUTHENTICATED) {\n mode = \"authenticated\";\n } else {\n mode = \"anonymous\";\n }\n\n let tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n if (_otelState === OtelState.COEXISTENCE_FAILED || _otelState === OtelState.UNCONFIGURED || _otelState === OtelState.CONFIGURING) {\n tracing = \"not-configured\";\n } else if (_coreState === CoreState.ACTIVE_DEGRADED) {\n tracing = \"degraded\";\n } else if (_otelState === OtelState.AUTO_ATTACHED || _otelState === OtelState.PROCESSOR_PRESENT) {\n tracing = \"coexistence\";\n } else {\n tracing = \"active\";\n }\n\n return {\n ready: isReady(),\n mode,\n tracing,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shutdown Coordinator\n//\n// IMPORTANT: The shutdown system has two parts that must stay in sync:\n// 1. HOOKS — registered via registerShutdownHook() by each module\n// 2. TRIGGERS — registerSignalHandlers() for signal-based exit, or\n// registerBeforeExitTrigger() for event-loop-drain exit. Both\n// call executeShutdown() which is idempotent.\n//\n// Rules for agents modifying shutdown behavior:\n// - When registering a hook, verify its trigger exists in the same PR.\n// A hook without a trigger is dead code.\n// - When removing a trigger, verify no hooks depend on it.\n// A trigger removal without hook cleanup drops spans on exit.\n// - Scenario A (bare path): register BOTH signal handlers AND\n// beforeExit trigger. Signals cover SIGTERM/SIGINT, beforeExit\n// covers clean event loop drain (all timers unref'd).\n// - Scenario B (coexistence): register ONLY beforeExit trigger.\n// The existing provider owns signals. beforeExit covers the edge\n// case where the provider doesn't propagate shutdown on drain.\n// ---------------------------------------------------------------------------\n\nexport interface ShutdownHook {\n name: string;\n priority: number;\n fn: () => Promise<void>;\n}\n\nlet _shutdownHooks: ShutdownHook[] = [];\nlet _signalHandlersRegistered = false;\nlet _signalHandler: ((signal: NodeJS.Signals) => void) | null = null;\nlet _beforeExitRegistered = false;\nlet _beforeExitHandler: (() => void) | null = null;\nlet _shutdownExecuted = false;\n\n/**\n * Register a shutdown hook. Hooks are executed in priority order\n * (lower number = earlier execution) during shutdown.\n */\nexport function registerShutdownHook(hook: ShutdownHook): void {\n _shutdownHooks.push(hook);\n _shutdownHooks.sort((a, b) => a.priority - b.priority);\n}\n\n/**\n * Execute all registered shutdown hooks in priority order.\n * Each hook runs with a timeout. Errors in individual hooks are caught\n * and logged — remaining hooks still execute.\n *\n * Idempotent: calling this multiple times has no effect after the first.\n */\nexport async function executeShutdown(timeoutMs = 5000): Promise<void> {\n if (_shutdownExecuted) return;\n _shutdownExecuted = true;\n\n setCoreState(CoreState.SHUTTING_DOWN);\n\n for (const hook of _shutdownHooks) {\n try {\n // Suppress unhandled rejection on the hook promise if the timeout wins the race.\n const hookPromise = hook.fn();\n hookPromise.catch(() => {});\n\n await Promise.race([\n hookPromise,\n new Promise<void>((_, reject) => {\n const timer = setTimeout(() => reject(new Error(`Shutdown hook \"${hook.name}\" timed out`)), timeoutMs);\n if (typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n }),\n ]);\n } catch (err) {\n _logger?.(\n \"warn\",\n `[glasstrace] Shutdown hook \"${hook.name}\" failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n setCoreState(CoreState.SHUTDOWN);\n}\n\n/**\n * Register SIGTERM and SIGINT handlers that trigger the shutdown\n * coordinator. Called by the core lifecycle setup, not by individual\n * layers. Re-raises the signal after shutdown completes.\n */\nexport function registerSignalHandlers(): void {\n if (_signalHandlersRegistered) return;\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n _signalHandlersRegistered = true;\n\n const handler = (signal: NodeJS.Signals) => {\n void executeShutdown().finally(() => {\n // Remove our handler and re-raise the signal for default behavior\n if (_signalHandler) {\n process.removeListener(\"SIGTERM\", _signalHandler);\n process.removeListener(\"SIGINT\", _signalHandler);\n }\n process.kill(process.pid, signal);\n });\n };\n\n _signalHandler = handler;\n process.once(\"SIGTERM\", handler);\n process.once(\"SIGINT\", handler);\n}\n\n/**\n * Register a beforeExit handler that triggers the shutdown coordinator.\n * beforeExit fires when the event loop drains (not on signals).\n *\n * For Scenario B (coexistence): the existing provider owns SIGTERM/SIGINT.\n * This trigger covers the edge case where the process exits without signals\n * (event loop drains naturally). The existing provider's MultiSpanProcessor\n * handles signal-based shutdown by propagating to our injected processor.\n *\n * Both signal handlers and beforeExit triggers call the same executeShutdown(),\n * which is idempotent — if signals already ran shutdown, beforeExit is a no-op.\n */\nexport function registerBeforeExitTrigger(): void {\n if (_beforeExitRegistered) return;\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n _beforeExitRegistered = true;\n\n const handler = () => {\n void executeShutdown();\n };\n\n _beforeExitHandler = handler;\n process.once(\"beforeExit\", handler);\n}\n\n// ---------------------------------------------------------------------------\n// Testing\n// ---------------------------------------------------------------------------\n\n/**\n * Reset all lifecycle state to initial values. For testing only.\n * Removes all event listeners, resets all state enums, and clears\n * the initialized flag.\n */\nexport function resetLifecycleForTesting(): void {\n _coreState = CoreState.IDLE;\n _authState = AuthState.ANONYMOUS;\n _otelState = OtelState.UNCONFIGURED;\n _emitter.removeAllListeners();\n _emitter = new EventEmitter();\n _logger = null;\n _initialized = false;\n _initWarned = false;\n _coreReadyEmitted = false;\n _authInitialized = false;\n _emitting = false;\n _shutdownHooks = [];\n _shutdownExecuted = false;\n if (_signalHandler && typeof process !== \"undefined\") {\n process.removeListener(\"SIGTERM\", _signalHandler);\n process.removeListener(\"SIGINT\", _signalHandler);\n }\n _signalHandler = null;\n _signalHandlersRegistered = false;\n if (_beforeExitHandler && typeof process !== \"undefined\") {\n process.removeListener(\"beforeExit\", _beforeExitHandler);\n }\n _beforeExitHandler = null;\n _beforeExitRegistered = false;\n}\n","/**\n * OTel Coexistence Public API\n *\n * Provides createGlasstraceSpanProcessor() for developers who want to\n * manually integrate Glasstrace with their existing OTel provider\n * (e.g., Sentry's openTelemetrySpanProcessors config option).\n *\n * Also provides the auto-attach path (tryAutoAttachGlasstraceProcessor)\n * that configureOtel() uses when it detects a pre-registered provider\n * at runtime (Next.js 16 production, Sentry, Datadog, New Relic). Both\n * entry points reuse the same span-processor factory so the manual and\n * automatic paths stay in lockstep.\n *\n * Design: sdk-otel-coexistence.md Sections 3, 4, 5, 6\n */\n\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport type * as otelApi from \"@opentelemetry/api\";\nimport type { GlasstraceOptions } from \"@glasstrace/protocol\";\nimport { GlasstraceExporter } from \"./enriching-exporter.js\";\nimport { getResolvedApiKey, registerExporterForKeyNotification } from \"./otel-config.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { getSessionManager } from \"./register.js\";\nimport { resolveConfig } from \"./env-detection.js\";\nimport { getOtelState, OtelState } from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\n\n/** Branded symbol used to identify Glasstrace's exporter across bundled copies. */\nconst GLASSTRACE_EXPORTER_BRAND = Symbol.for(\"glasstrace.exporter\");\n\n/**\n * Creates a Glasstrace span processor for manual integration with an\n * existing OTel provider.\n *\n * Use this when another tool (e.g., Sentry) owns the OTel provider and\n * you want to add Glasstrace to their processor list:\n *\n * @example\n * ```ts\n * import * as Sentry from \"@sentry/nextjs\";\n * import { createGlasstraceSpanProcessor } from \"@glasstrace/sdk\";\n *\n * Sentry.init({\n * dsn: \"...\",\n * openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\n * });\n * ```\n *\n * **Important:** `registerGlasstrace()` is still required even when using\n * this function. The processor handles span transport (enrichment and\n * export). `registerGlasstrace()` handles everything else: init calls,\n * config sync, session management, anonymous key generation, discovery\n * endpoint, and health reporting.\n *\n * @param options - Optional SDK configuration. If omitted, uses the same\n * config as registerGlasstrace() (environment variables).\n * @returns A BatchSpanProcessor wrapping a GlasstraceExporter with the\n * branded Symbol.for('glasstrace.exporter') for coexistence detection.\n */\nexport function createGlasstraceSpanProcessor(\n options?: GlasstraceOptions,\n): SpanProcessor {\n const config = resolveConfig(options);\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n const exporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager: getSessionManager(),\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n // Propagate verbose so exporter-level enrichment and export logs\n // stay observable whether the processor is built automatically by\n // the coexistence path or wired manually by the developer.\n verbose: config.verbose,\n });\n\n // Register for key-resolution notification so buffered spans flush\n // immediately when the key resolves (not waiting for BSP timer tick).\n registerExporterForKeyNotification(exporter);\n\n return new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: 1000,\n });\n}\n\n/**\n * Result returned by {@link tryAutoAttachGlasstraceProcessor}.\n *\n * - `{ method, processor }` — a Glasstrace span processor was successfully\n * injected into the existing provider's processor list. The caller MUST\n * retain the returned processor so it can be flushed on shutdown.\n * - `\"already_present\"` — a Glasstrace-branded processor was already in\n * the provider's list (e.g., the developer already registered one via\n * `createGlasstraceSpanProcessor()`). No additional processor was added.\n * - `null` — injection was not possible (provider internals inaccessible\n * or `addSpanProcessor` threw). The caller should emit guidance.\n */\nexport type AutoAttachResult =\n | { method: \"v1_public\" | \"v2_private\"; processor: SpanProcessor }\n | \"already_present\"\n | null;\n\n/**\n * Checks whether a Glasstrace-branded span processor is already present\n * in the existing provider's processor list.\n *\n * Uses the branded symbol {@link GLASSTRACE_EXPORTER_BRAND} so detection\n * works across bundled copies of `@glasstrace/sdk` (hoisted vs. nested\n * `node_modules`). `Symbol.for()` uses a global registry, so every copy\n * resolves to the same symbol.\n *\n * Fully defensive — any error or missing internal structure returns\n * `false` and lets the caller fall through to injection or guidance.\n */\nexport function isGlasstraceProcessorPresent(\n tracerProvider: otelApi.TracerProvider,\n): boolean {\n try {\n const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n const delegate = typeof proxy.getDelegate === \"function\"\n ? proxy.getDelegate()\n : tracerProvider;\n\n // Path 1: v2 internal (_activeSpanProcessor._spanProcessors)\n const v2 = delegate as unknown as {\n _activeSpanProcessor?: {\n _spanProcessors?: Array<{ _exporter?: unknown }>;\n };\n };\n const v2Processors = v2._activeSpanProcessor?._spanProcessors;\n if (Array.isArray(v2Processors) && hasBrandedProcessor(v2Processors)) {\n return true;\n }\n\n // Path 2: v1 getActiveSpanProcessor()\n const v1 = delegate as unknown as {\n getActiveSpanProcessor?: () => { _spanProcessors?: Array<{ _exporter?: unknown }> };\n };\n if (typeof v1.getActiveSpanProcessor === \"function\") {\n const active = v1.getActiveSpanProcessor();\n const processors = active?._spanProcessors;\n if (Array.isArray(processors) && hasBrandedProcessor(processors)) {\n return true;\n }\n }\n\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Attempts to inject a Glasstrace span processor into an existing\n * provider's processor pipeline.\n *\n * Tiered approach:\n * 1. Feature-detect `addSpanProcessor` (OTel v1 public API) → call it\n * 2. Feature-detect `_activeSpanProcessor._spanProcessors` (OTel v2\n * internal) → push the processor\n *\n * The processor is constructed via {@link createGlasstraceSpanProcessor}\n * so the auto-attach path and the manual integration path share identical\n * configuration (including the branded exporter for\n * {@link isGlasstraceProcessorPresent} detection and key-notification\n * registration).\n *\n * **Idempotence:** {@link isGlasstraceProcessorPresent} is consulted\n * before construction; if a Glasstrace-branded processor is already\n * attached, this function returns `\"already_present\"` without creating\n * a second exporter.\n *\n * **Defensive:** all errors are swallowed and return `null`. The SDK\n * falls back to emitting guidance rather than crashing.\n *\n * @param tracerProvider - The existing global provider returned by\n * `otelApi.trace.getTracerProvider()`.\n * @param options - Optional SDK configuration passed through to\n * `createGlasstraceSpanProcessor()`.\n * @returns See {@link AutoAttachResult}.\n */\nexport function tryAutoAttachGlasstraceProcessor(\n tracerProvider: otelApi.TracerProvider,\n options?: GlasstraceOptions,\n): AutoAttachResult {\n try {\n // Short-circuit: if a Glasstrace-branded processor is already present,\n // never create a second exporter. Covers the duplicate\n // registerGlasstrace() case (idempotence) and the B-clean scenario\n // where the user wired createGlasstraceSpanProcessor() into their\n // provider config manually.\n if (isGlasstraceProcessorPresent(tracerProvider)) {\n return \"already_present\";\n }\n\n // Unwrap ProxyTracerProvider to reach the concrete delegate.\n const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n const delegate = typeof proxy.getDelegate === \"function\"\n ? proxy.getDelegate()\n : tracerProvider;\n\n // Attempt 1: OTel v1 public API (addSpanProcessor).\n const withAdd = delegate as unknown as {\n addSpanProcessor?: (p: SpanProcessor) => void;\n };\n if (typeof withAdd.addSpanProcessor === \"function\") {\n const processor = createGlasstraceSpanProcessor(options);\n withAdd.addSpanProcessor(processor);\n return { method: \"v1_public\", processor };\n }\n\n // Attempt 2: OTel v2 internals (_activeSpanProcessor._spanProcessors).\n // Accessing a private field is justified in the design doc\n // (sdk-otel-coexistence.md Section 4). Same pattern Sentry uses.\n const v2 = delegate as unknown as {\n _activeSpanProcessor?: { _spanProcessors?: unknown[] };\n };\n const multiProcessor = v2._activeSpanProcessor;\n if (!multiProcessor || !Array.isArray(multiProcessor._spanProcessors)) {\n return null;\n }\n\n const processor = createGlasstraceSpanProcessor(options);\n multiProcessor._spanProcessors.push(processor);\n return { method: \"v2_private\", processor };\n } catch {\n return null;\n }\n}\n\n/**\n * Emits a nudge message guiding the developer toward the clean\n * createGlasstraceSpanProcessor() integration path.\n *\n * Called by configureOtel() when auto-attach succeeds (Scenarios B-auto, D1, D2).\n * NOT called when the processor is already present (Scenario B-clean).\n */\nexport function emitNudgeMessage(): void {\n const isSentry = detectSentry();\n\n if (isSentry) {\n sdkLog(\"info\",\n `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n `For a cleaner setup, add Glasstrace to your Sentry config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` Sentry.init({\\n` +\n ` dsn: '...',\\n` +\n ` openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n ` });\\n\\n` +\n `This message will not appear once Glasstrace is added to your provider config.`,\n );\n } else {\n sdkLog(\"info\",\n `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n `For a cleaner setup, add Glasstrace to your provider config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` const provider = new BasicTracerProvider({\\n` +\n ` spanProcessors: [\\n` +\n ` // ... your existing processors,\\n` +\n ` createGlasstraceSpanProcessor(),\\n` +\n ` ],\\n` +\n ` });\\n\\n` +\n `This message will not appear once Glasstrace is added to your provider config.`,\n );\n }\n}\n\n/**\n * Emits a guidance message when auto-attach fails (Scenarios C, F).\n */\nexport function emitGuidanceMessage(): void {\n const isSentry = detectSentry();\n\n if (isSentry) {\n sdkLog(\"warn\",\n `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n `could not auto-attach its span processor.\\n` +\n `Add Glasstrace to your Sentry config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` Sentry.init({\\n` +\n ` dsn: '...',\\n` +\n ` openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n ` });`,\n );\n } else {\n sdkLog(\"warn\",\n `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n `could not auto-attach its span processor.\\n` +\n `Add Glasstrace to your provider configuration:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` const provider = new BasicTracerProvider({\\n` +\n ` spanProcessors: [\\n` +\n ` // ... your existing processors,\\n` +\n ` createGlasstraceSpanProcessor(),\\n` +\n ` ],\\n` +\n ` });`,\n );\n }\n}\n\n/**\n * Returns true if the nudge message should be shown.\n * Only show when auto-attach was used (not when the user already\n * configured the processor manually).\n */\nexport function shouldShowNudge(): boolean {\n return getOtelState() === OtelState.AUTO_ATTACHED;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n/**\n * Scans a processor list for one whose exporter carries the Glasstrace\n * brand symbol. Defensive — missing fields or non-object exporters return\n * `false`.\n */\nfunction hasBrandedProcessor(\n processors: Array<{ _exporter?: unknown }>,\n): boolean {\n return processors.some((p) => {\n const exporter = p._exporter as Record<symbol, unknown> | undefined;\n return exporter?.[GLASSTRACE_EXPORTER_BRAND] === true;\n });\n}\n\nfunction detectSentry(): boolean {\n try {\n // Check if @sentry/node or @sentry/nextjs is installed\n // Use require.resolve which checks module resolution without importing\n require.resolve(\"@sentry/node\");\n return true;\n } catch {\n try {\n require.resolve(\"@sentry/nextjs\");\n return true;\n } catch {\n return false;\n }\n }\n}\n","import type { ResolvedConfig } from \"./env-detection.js\";\nimport type { SessionManager } from \"./session.js\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { BasicTracerProvider, BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GlasstraceExporter, API_KEY_PENDING } from \"./enriching-exporter.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { setOtelState, OtelState, getCoreState, CoreState, setCoreState, emitLifecycleEvent, registerShutdownHook, registerBeforeExitTrigger } from \"./lifecycle.js\";\nimport {\n emitNudgeMessage,\n emitGuidanceMessage,\n tryAutoAttachGlasstraceProcessor,\n} from \"./coexistence.js\";\n\n/** Module-level resolved API key, updated when the anon key resolves. */\nlet _resolvedApiKey: string = API_KEY_PENDING;\n\n/** Module-level reference to the active exporter for key-resolution notification. */\nlet _activeExporter: GlasstraceExporter | null = null;\n\n/** Additional exporters that need key-resolution notification (from createGlasstraceSpanProcessor). */\nconst _additionalExporters: GlasstraceExporter[] = [];\n\n/** Injected processor in coexistence mode, tracked for flush on exit. */\nlet _injectedProcessor: SpanProcessor | null = null;\n\n/**\n * Sets the resolved API key for OTel export authentication.\n * Called once the anonymous key or dev key is available.\n * @param key - The resolved API key (anonymous or developer).\n */\nexport function setResolvedApiKey(key: string): void {\n _resolvedApiKey = key;\n}\n\n/**\n * Returns the current resolved API key.\n * Returns the {@link API_KEY_PENDING} sentinel if the key has not yet resolved.\n */\nexport function getResolvedApiKey(): string {\n return _resolvedApiKey;\n}\n\n/**\n * Notifies the active exporter that the API key has transitioned from\n * \"pending\" to a resolved value. This triggers flushing of any buffered spans.\n */\nexport function notifyApiKeyResolved(): void {\n _activeExporter?.notifyKeyResolved();\n for (const exporter of _additionalExporters) {\n exporter.notifyKeyResolved();\n }\n}\n\n/**\n * Register an additional exporter for key-resolution notification.\n * Used by createGlasstraceSpanProcessor() so its exporter gets notified\n * when the API key resolves (flushing buffered spans immediately rather\n * than waiting for the next BSP timer tick).\n */\nexport function registerExporterForKeyNotification(exporter: GlasstraceExporter): void {\n _additionalExporters.push(exporter);\n}\n\n/**\n * Resets OTel configuration state to initial values. For testing only.\n */\nexport function resetOtelConfigForTesting(): void {\n _resolvedApiKey = API_KEY_PENDING;\n _activeExporter = null;\n _injectedProcessor = null;\n _additionalExporters.length = 0;\n // Signal and beforeExit handler cleanup is handled by resetLifecycleForTesting()\n // via the shutdown coordinator.\n}\n\n/**\n * Dynamically imports an optional peer dependency at runtime.\n *\n * Uses `Function()` constructor to build the `import()` expression so that\n * bundlers (webpack, esbuild, turbopack) do not attempt to resolve the module\n * at compile time. This is intentional -- the SDK's peer dependencies are\n * optional, and static analysis would cause missing-module build errors for\n * users who have not installed them.\n *\n * **CSP note:** The `Function()` constructor is semantically equivalent to\n * `eval()` and will trigger Content Security Policy violations in environments\n * that disallow `unsafe-eval`. If your CSP blocks this, install the OTel peer\n * dependencies explicitly so they resolve via normal `import` statements, or\n * use the `@vercel/otel` path which does not rely on `tryImport` for its own\n * module.\n *\n * @param moduleId - The npm package name to import (e.g. \"@vercel/otel\").\n * @returns The module namespace object, or `null` if the module is not installed.\n */\nasync function tryImport(moduleId: string): Promise<Record<string, unknown> | null> {\n try {\n return await (Function(\"id\", \"return import(id)\")(moduleId) as Promise<Record<string, unknown>>);\n } catch {\n return null;\n }\n}\n\n/**\n * Configures OpenTelemetry with the GlasstraceExporter.\n *\n * Detection flow (per sdk-otel-coexistence.md v8+):\n * 1. Yield one tick (let synchronous Sentry.init() complete)\n * 2. Probe for existing provider\n * 3. If provider exists → shared coexistence path via\n * {@link tryAutoAttachGlasstraceProcessor} (resolves DISC-493 Issues 2\n * and 4 — Next.js 16 production pre-registration and Sentry hoisting)\n * 4. If no provider → registration path (Vercel or bare)\n */\nexport async function configureOtel(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n setOtelState(OtelState.CONFIGURING);\n\n // Step 1: Yield one tick to let synchronous Sentry.init() (or other tools)\n // complete before probing for an existing provider (DISC-1202).\n await new Promise<void>((resolve) => {\n if (typeof setImmediate === \"function\") {\n setImmediate(resolve);\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n // Step 2: Probe for an existing OTel provider BEFORE the Vercel/bare split.\n // This unified detection ensures coexistence works regardless of whether\n // @vercel/otel is installed (sdk-otel-coexistence.md Section 2.4).\n const existingProvider = otelApi.trace.getTracerProvider();\n const probeTracer = existingProvider.getTracer(\"glasstrace-probe\");\n const anotherProviderRegistered = probeTracer.constructor.name !== \"ProxyTracer\";\n\n // Step 3: If another provider exists → shared coexistence path.\n // This is the DISC-493 Issues 2 and 4 fix: instead of silently giving up\n // when a Next.js 16 production build or a Sentry import has already\n // registered a provider, auto-attach our span processor onto it.\n if (anotherProviderRegistered) {\n await runCoexistencePath(existingProvider, config);\n return;\n }\n\n // Step 4: No existing provider → registration path.\n await runRegistrationPath(config, sessionManager);\n}\n\n/**\n * Shared coexistence path for DISC-493 Issues 2 and 4.\n *\n * Used whenever `configureOtel()` detects a pre-registered OTel provider.\n * Delegates processor construction to {@link tryAutoAttachGlasstraceProcessor}\n * which reuses the `createGlasstraceSpanProcessor()` public primitive, so\n * the auto-attach path and the manual integration path stay in lockstep.\n *\n * Idempotence: if a Glasstrace-branded processor is already attached (from\n * a prior `registerGlasstrace()` call or a manual `createGlasstraceSpanProcessor()`\n * wiring), the auto-attach path returns `\"already_present\"` and no second\n * processor is created.\n */\nasync function runCoexistencePath(\n existingProvider: ReturnType<typeof otelApi.trace.getTracerProvider>,\n config: ResolvedConfig,\n): Promise<void> {\n // Attempt to auto-attach via the shared primitive.\n //\n // tryAutoAttachGlasstraceProcessor() performs its own \"already present\"\n // check against the branded Symbol BEFORE constructing an exporter, so\n // idempotent registration does not create a wasted exporter instance.\n // It also reuses createGlasstraceSpanProcessor() for construction, so\n // the processor wiring (branded exporter, key-notification registration,\n // BSP flush interval) matches the documented manual path exactly.\n //\n // Pass through the subset of resolved config that `GlasstraceOptions`\n // accepts. `environment` is not in `GlasstraceOptions` (it's derived\n // from env vars inside `resolveConfig`), so the primitive picks it up\n // from the same environment variables `configureOtel()` sees.\n const result = tryAutoAttachGlasstraceProcessor(existingProvider, {\n endpoint: config.endpoint,\n verbose: config.verbose,\n });\n\n if (result === \"already_present\") {\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Existing provider detected — Glasstrace processor already present.\");\n }\n setOtelState(OtelState.PROCESSOR_PRESENT);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.PROCESSOR_PRESENT, scenario: \"B-clean\" });\n return;\n }\n\n if (result !== null) {\n // Success: processor was attached. Retain a reference for the\n // coexistence flush hook (Section 7.2) so beforeExit drains buffered\n // spans even if the existing provider's shutdown does not propagate.\n _injectedProcessor = result.processor;\n\n if (config.verbose) {\n sdkLog(\n \"info\",\n \"[glasstrace] Existing provider detected — auto-attached Glasstrace span processor.\",\n );\n }\n\n // Register coexistence flush hook via the lifecycle coordinator, and\n // wire the beforeExit trigger so the coordinator runs on event loop drain.\n // The existing provider handles signal-based shutdown (its MultiSpanProcessor\n // propagates shutdown() to our injected processor). The beforeExit trigger\n // covers the edge case where the process exits without signals. Both\n // triggers (signals and beforeExit) call executeShutdown() which is\n // idempotent — if one already ran, the other is a no-op.\n registerShutdownHook({\n name: \"coexistence-flush\",\n priority: 5,\n fn: async () => {\n if (_injectedProcessor) {\n await _injectedProcessor.forceFlush();\n }\n },\n });\n registerBeforeExitTrigger();\n\n const scenario = result.method === \"v1_public\" ? \"D1\" : \"B-auto\";\n setOtelState(OtelState.AUTO_ATTACHED);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.AUTO_ATTACHED, scenario });\n emitLifecycleEvent(\"otel:injection_succeeded\", { method: result.method });\n emitNudgeMessage();\n return;\n }\n\n // Injection failed (Scenario C/F) — emit guidance.\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Existing provider detected — could not auto-attach.\");\n }\n emitGuidanceMessage();\n setOtelState(OtelState.COEXISTENCE_FAILED);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.COEXISTENCE_FAILED, scenario: \"C/F\" });\n emitLifecycleEvent(\"otel:injection_failed\", { reason: \"provider internals inaccessible\" });\n // Cross-layer effect: trigger ACTIVE_DEGRADED if core state permits it\n // (per DISC-1247, KEY_PENDING → ACTIVE_DEGRADED is not valid, so we guard).\n const coreState = getCoreState();\n if (coreState === CoreState.ACTIVE || coreState === CoreState.KEY_RESOLVED) {\n setCoreState(CoreState.ACTIVE_DEGRADED);\n }\n}\n\n/**\n * Registration path when no existing OTel provider is detected.\n *\n * Tries `@vercel/otel` first (Scenario E). Falls back to constructing a\n * bare `BasicTracerProvider` (Scenario A). In both sub-scenarios,\n * Glasstrace owns the provider and installs its own shutdown hooks.\n */\nasync function runRegistrationPath(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n // Build OTLP exporter configuration\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n // OTLP exporter factory — always available since OTel is bundled.\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n // Create the GlasstraceExporter that enriches + buffers + delegates\n const glasstraceExporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager,\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n verbose: config.verbose,\n });\n _activeExporter = glasstraceExporter;\n\n // Try @vercel/otel first (Scenario E)\n const vercelOtel = await tryImport(\"@vercel/otel\");\n if (vercelOtel && typeof vercelOtel.registerOTel === \"function\") {\n const otelConfig: Record<string, unknown> = {\n serviceName: \"glasstrace-sdk\",\n traceExporter: glasstraceExporter,\n };\n\n // Try @prisma/instrumentation\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown) | undefined;\n if (PrismaInstrumentation) {\n otelConfig.instrumentations = [new PrismaInstrumentation()];\n }\n }\n\n (vercelOtel.registerOTel as (opts: Record<string, unknown>) => void)(otelConfig);\n setOtelState(OtelState.OWNS_PROVIDER);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"E\" });\n return;\n }\n\n // Bare OTel SDK fallback (Scenario A)\n\n // Enable OTel diagnostic logging in verbose mode so OTLP exporter\n // errors (auth failures, network issues) are surfaced to the developer.\n // Routes through sdkLog to avoid console-capture recording OTel internals.\n if (config.verbose) {\n otelApi.diag.setLogger(\n {\n verbose: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n debug: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n info: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n warn: (msg) => sdkLog(\"warn\", `[otel] ${msg}`),\n error: (msg) => sdkLog(\"error\", `[otel] ${msg}`),\n },\n otelApi.DiagLogLevel.WARN,\n );\n }\n\n const processor = new BatchSpanProcessor(glasstraceExporter, {\n scheduledDelayMillis: 1000,\n });\n const provider = new BasicTracerProvider({\n spanProcessors: [processor],\n });\n\n // Context manager is registered synchronously in registerGlasstrace()\n // before configureOtel() is called (DISC-1183). By this point, it's\n // already active and propagating trace context across async boundaries.\n\n otelApi.trace.setGlobalTracerProvider(provider);\n\n // Register OTel shutdown via lifecycle coordinator.\n // Signal handlers are installed upfront by registerGlasstrace() so they\n // exist during this async setup window (DISC-1249). beforeExit is still\n // wired here because Scenario A owns the provider and the coexistence\n // path registers its own beforeExit trigger independently.\n registerShutdownHook({\n name: \"otel-provider-shutdown\",\n priority: 0,\n fn: async () => {\n await provider.shutdown();\n },\n });\n registerBeforeExitTrigger();\n\n // Register Prisma instrumentation on the bare path (DISC-1223).\n // The Vercel path handles this via registerOTel({ instrumentations: [...] }).\n // The coexistence path gets Prisma from the existing provider (e.g., Sentry).\n // Only the bare path was missing it.\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown & { setTracerProvider: (p: unknown) => void; enable: () => void }) | undefined;\n if (PrismaInstrumentation) {\n try {\n const inst = new PrismaInstrumentation();\n inst.setTracerProvider(provider);\n inst.enable();\n } catch {\n // Prisma instrumentation is optional — failure is not fatal\n }\n }\n }\n\n setOtelState(OtelState.OWNS_PROVIDER);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"A\" });\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport * as otelApi from \"@opentelemetry/api\";\n\n/**\n * Registers an AsyncLocalStorage-based context manager with the OTel API.\n *\n * This MUST be called synchronously before any spans are created —\n * otherwise, spans created before registration have no parent context\n * and each gets a fresh traceId (DISC-1183).\n *\n * Uses a static import of `node:async_hooks` (synchronous, no race\n * condition). This means the module cannot be evaluated in non-Node\n * environments (Edge Runtime, browser) — but the SDK is a server-side\n * package and non-Node environments are guarded by the `sideEffects: false`\n * flag in package.json (browser bundlers tree-shake it) and the browser\n * import check CI step externalizes `async_hooks`.\n *\n * @returns `true` if the context manager was installed, `false` if\n * another tool already registered a context manager.\n */\nexport function installContextManager(): boolean {\n try {\n const als = new AsyncLocalStorage<otelApi.Context>();\n\n const contextManager: otelApi.ContextManager = {\n active: () => als.getStore() ?? otelApi.ROOT_CONTEXT,\n with: <A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: otelApi.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> => als.run(context, () => fn.apply(thisArg, args)),\n bind: <T>(context: otelApi.Context, target: T): T => {\n if (typeof target === \"function\") {\n const bound = (...fnArgs: unknown[]) =>\n als.run(context, () => (target as (...a: unknown[]) => unknown)(...fnArgs));\n return bound as T;\n }\n return target;\n },\n enable: () => contextManager,\n disable: () => contextManager,\n };\n\n const success = otelApi.context.setGlobalContextManager(contextManager);\n if (!success) {\n console.warn(\n \"[glasstrace] Another context manager is already registered. \" +\n \"Trace context propagation may not work as expected.\",\n );\n }\n return success;\n } catch {\n return false;\n }\n}\n","import type { AnonApiKey } from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { collectHealthReport } from \"./health-collector.js\";\nimport { performInit, consumeRateLimitFlag } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { registerShutdownHook, executeShutdown } from \"./lifecycle.js\";\n\nconst HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nconst BACKOFF_BASE_MS = HEARTBEAT_INTERVAL_MS; // 5 minutes\nconst BACKOFF_MAX_MS = 30 * 60 * 1000; // 30 minutes\nconst BACKOFF_JITTER = 0.2; // ±20%\n\n/**\n * Shutdown hook priority for the final heartbeat report.\n *\n * Per docs/component-designs/sdk-lifecycle.md Section 8.3:\n * 0 — OTel flush (must run first so spans are exported)\n * 10 — Heartbeat final report (includes final span counts)\n * 20 — Runtime state write (terminal state persisted last)\n */\nconst HEARTBEAT_SHUTDOWN_PRIORITY = 10;\n\nconst SHUTDOWN_MARKER_RELPATH = \".glasstrace/shutdown-requested\";\n\n// --- Module-level state ---\n\nlet heartbeatTimer: ReturnType<typeof setInterval> | null = null;\nlet heartbeatGeneration = 0;\nlet backoffAttempts = 0;\nlet backoffUntil = 0;\nlet tickInProgress = false;\n\n/**\n * Ensures the shutdown hook is only registered once per process and that\n * the final report is only sent once even if the hook runs more than once.\n */\nlet shutdownHookRegistered = false;\nlet shutdownFired = false;\n\n// --- Public API ---\n\n/**\n * Starts the periodic health heartbeat after successful init.\n * Timer is unref()'d so it doesn't prevent process exit.\n *\n * Registers a shutdown hook with the lifecycle coordinator (priority 10)\n * so the final health report runs after OTel flush (priority 0) and before\n * runtime state write (priority 20). The hook is registered once per\n * process; subsequent `startHeartbeat` calls do not re-register.\n *\n * @param onClaimTransition - Callback for claim key rotation, avoiding\n * circular dependency with otel-config.ts.\n */\nexport function startHeartbeat(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n generation: number,\n onClaimTransition: (newApiKey: string, accountId: string) => void,\n): void {\n // Prevent double-start\n if (heartbeatTimer !== null) return;\n\n heartbeatGeneration = generation;\n\n heartbeatTimer = setInterval(() => {\n void heartbeatTick(config, anonKey, sdkVersion, generation, onClaimTransition);\n }, HEARTBEAT_INTERVAL_MS);\n\n // unref() so the timer doesn't prevent Node.js process exit\n heartbeatTimer.unref();\n\n // Register the final health-report hook with the lifecycle coordinator.\n // Signal handling is owned by the coordinator (registerSignalHandlers in\n // otel-config.ts), so the heartbeat module no longer attaches directly to\n // SIGTERM/SIGINT.\n registerHeartbeatShutdownHook(config, anonKey, sdkVersion);\n\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat started (5-minute interval).\");\n }\n}\n\n/**\n * Stops the heartbeat timer.\n *\n * The shutdown hook is intentionally not unregistered — the lifecycle\n * coordinator does not expose a removal API. Stopping the heartbeat here\n * suppresses future periodic ticks by clearing the timer, but it does not\n * prevent the already-registered shutdown hook from sending its final\n * health report once during process shutdown. The hook's internal\n * `shutdownFired` guard ensures it runs at most once regardless.\n */\nexport function stopHeartbeat(): void {\n if (heartbeatTimer !== null) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * Resets all heartbeat state. For testing only.\n */\nexport function _resetHeartbeatForTesting(): void {\n stopHeartbeat();\n heartbeatGeneration = 0;\n backoffAttempts = 0;\n backoffUntil = 0;\n tickInProgress = false;\n shutdownHookRegistered = false;\n shutdownFired = false;\n}\n\n/**\n * Checks for the presence of the `.glasstrace/shutdown-requested` marker\n * file and, if present, triggers the lifecycle shutdown coordinator and\n * removes the marker (DISC-1247 Scenario 1).\n *\n * Returns `true` when the marker was found and the shutdown coordinator\n * was scheduled, `false` otherwise. The marker is removed synchronously\n * BEFORE executeShutdown() is scheduled so a crash during shutdown does\n * not cause the marker to be re-detected on restart.\n *\n * The filesystem lookup itself is synchronous, but `node:fs`/`node:path`\n * are loaded lazily via `require()` inside this helper rather than via\n * top-level imports. This keeps the helper usable from fake-timer-driven\n * heartbeat ticks without introducing extra microtask boundaries, while\n * also avoiding unconditional top-level built-in imports on module\n * load. The downstream `executeShutdown()` call can be awaited by the\n * caller when desired.\n *\n * Self-contained so it can be called from either the heartbeat tick\n * (current location) or a dedicated lifecycle hook after DISC-1248 lands.\n *\n * @param projectRoot - Optional project root; defaults to `process.cwd()`.\n * @returns An object describing the outcome. When `triggered` is true,\n * `shutdown` is the promise returned by `executeShutdown()` so the\n * caller can optionally await full shutdown completion.\n */\nexport function checkShutdownMarker(projectRoot?: string): {\n triggered: boolean;\n shutdown?: Promise<void>;\n} {\n // node:fs and node:path are imported lazily via require to remain\n // compatible with non-Node bundlers that externalize node:* modules.\n // Errors are swallowed — a non-Node environment simply reports\n // \"no marker\".\n let fsSync: typeof import(\"node:fs\") | null = null;\n let pathSync: typeof import(\"node:path\") | null = null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n fsSync = require(\"node:fs\") as typeof import(\"node:fs\");\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n pathSync = require(\"node:path\") as typeof import(\"node:path\");\n } catch {\n return { triggered: false };\n }\n\n const root = projectRoot ?? (typeof process !== \"undefined\" ? process.cwd() : \".\");\n const markerPath = pathSync.join(root, SHUTDOWN_MARKER_RELPATH);\n\n if (!fsSync.existsSync(markerPath)) return { triggered: false };\n\n // Remove the marker BEFORE scheduling shutdown. If we removed it\n // afterwards, a crashed process would leave the marker in place and\n // cause the next start to shut down immediately.\n try {\n fsSync.unlinkSync(markerPath);\n } catch {\n // Best-effort — proceed with shutdown even if removal fails.\n }\n\n // executeShutdown is idempotent and never throws; fire-and-track the\n // returned promise so the caller can optionally await completion.\n const shutdown = executeShutdown().catch(() => {\n // executeShutdown is designed not to throw; swallow defensively.\n });\n return { triggered: true, shutdown };\n}\n\n// --- Internal: heartbeat tick ---\n\nasync function heartbeatTick(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n generation: number,\n onClaimTransition: (newApiKey: string, accountId: string) => void,\n): Promise<void> {\n // Prevent concurrent ticks (setInterval doesn't await async callbacks)\n if (tickInProgress) return;\n tickInProgress = true;\n\n try {\n // Generation check — stop if registration was reset\n if (generation !== heartbeatGeneration) {\n stopHeartbeat();\n return;\n }\n\n // DISC-1247 Scenario 1: check for the shutdown-requested marker at\n // the top of each tick. If `sdk uninit` has been run, the marker\n // exists and we trigger shutdown immediately. Moved into a dedicated\n // lifecycle hook once DISC-1248 lands — the helper is module-exported\n // to keep that migration mechanical.\n //\n // The check itself is synchronous (fs.existsSync) so fake-timer tests\n // stay deterministic; we do await the shutdown promise once it has\n // been scheduled so the tick does not race its own cleanup.\n const markerResult = checkShutdownMarker();\n if (markerResult.triggered) {\n stopHeartbeat();\n if (markerResult.shutdown) {\n await markerResult.shutdown;\n }\n return;\n }\n\n // Backoff check — skip this tick if in backoff window\n if (Date.now() < backoffUntil) {\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat skipped (rate-limit backoff).\");\n }\n return;\n }\n\n // Collect and send health report (same pattern as backgroundInit)\n const healthReport = collectHealthReport(sdkVersion);\n const initResult = await performInit(config, anonKey, sdkVersion, healthReport);\n\n // Generation re-check after async work\n if (generation !== heartbeatGeneration) return;\n\n // Handle 429 backoff via consumeRateLimitFlag\n if (initResult === null && consumeRateLimitFlag()) {\n backoffAttempts++;\n const delay = Math.min(\n BACKOFF_BASE_MS * Math.pow(2, backoffAttempts - 1),\n BACKOFF_MAX_MS,\n );\n const jitter = delay * BACKOFF_JITTER * (Math.random() * 2 - 1);\n backoffUntil = Date.now() + delay + jitter;\n if (config.verbose) {\n sdkLog(\"info\", `[glasstrace] Heartbeat backing off for ${Math.round((delay + jitter) / 1000)}s.`);\n }\n } else {\n // Success or non-429 failure — reset backoff\n backoffAttempts = 0;\n backoffUntil = 0;\n }\n\n // Handle claim transition via callback (no otel-config import needed)\n if (initResult?.claimResult) {\n onClaimTransition(initResult.claimResult.newApiKey, initResult.claimResult.accountId);\n }\n\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat completed.\");\n }\n } finally {\n tickInProgress = false;\n }\n}\n\n// --- Internal: shutdown health report ---\n\n/**\n * Registers the heartbeat's final-report hook exactly once per process.\n *\n * The hook:\n * - Is idempotent (`shutdownFired` guard) so a duplicate invocation by\n * the coordinator cannot double-report.\n * - Stops the timer first so no further ticks race with the final report.\n * - Preserves the exact payload that the previous direct-handler code\n * sent (`collectHealthReport` + `performInit`), so consumers observe\n * identical shutdown telemetry before and after this refactor.\n * - Does NOT re-raise the signal. The lifecycle coordinator's signal\n * handler owns signal propagation and calls process.kill() after all\n * hooks complete.\n */\nfunction registerHeartbeatShutdownHook(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n): void {\n if (shutdownHookRegistered) return;\n shutdownHookRegistered = true;\n\n registerShutdownHook({\n name: \"heartbeat-final-report\",\n priority: HEARTBEAT_SHUTDOWN_PRIORITY,\n fn: async () => {\n if (shutdownFired) return;\n shutdownFired = true;\n\n // Stop the heartbeat timer — no more ticks after this\n if (heartbeatTimer !== null) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n\n // Best-effort final report. Errors are swallowed so they don't\n // prevent the remainder of the shutdown sequence from completing.\n try {\n const healthReport = collectHealthReport(sdkVersion);\n await performInit(config, anonKey, sdkVersion, healthReport);\n } catch {\n // Intentionally swallow final-report failures to avoid adding\n // shutdown noise or interrupting the remaining shutdown hooks.\n }\n },\n });\n}\n","/**\n * Runtime State Bridge\n *\n * Writes the SDK's lifecycle state to `.glasstrace/runtime-state.json`\n * so that CLI commands (npx @glasstrace/sdk status) can report runtime\n * state without a live process connection.\n *\n * Design: sdk-lifecycle.md Section 14 (Runtime State File)\n * Task brief: SDK-026\n */\n\nimport { writeFileSync, renameSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n getSdkState,\n onLifecycleEvent,\n CoreState,\n} from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\n\n/** Schema for the runtime state file. */\nexport interface RuntimeState {\n updatedAt: string;\n pid: number;\n sdkVersion: string;\n core: { state: string };\n auth: { state: string };\n otel: { state: string; scenario?: string };\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _projectRoot: string | null = null;\nlet _sdkVersion: string = \"unknown\";\nlet _lastScenario: string | undefined;\nlet _debounceTimer: ReturnType<typeof setTimeout> | null = null;\nlet _started = false;\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start writing runtime state to disk on every lifecycle state transition.\n * Must be called after initLifecycle() and after the project root is known.\n *\n * Writes are debounced to max once per second. The final SHUTDOWN state\n * bypasses debounce to ensure it's always persisted.\n */\nexport function startRuntimeStateWriter(options: {\n projectRoot: string;\n sdkVersion: string;\n}): void {\n if (_started) return;\n _started = true;\n\n _projectRoot = options.projectRoot;\n _sdkVersion = options.sdkVersion;\n\n // Listen for state changes across all layers\n onLifecycleEvent(\"core:state_changed\", ({ to }) => {\n if (to === CoreState.SHUTDOWN) {\n // Bypass debounce for terminal state — write immediately\n writeStateNow();\n } else {\n debouncedWrite();\n }\n });\n\n onLifecycleEvent(\"otel:configured\", ({ scenario }) => {\n _lastScenario = scenario;\n debouncedWrite();\n });\n\n // Auth events — write when key resolves or claim transitions occur\n onLifecycleEvent(\"auth:key_resolved\", () => debouncedWrite());\n onLifecycleEvent(\"auth:claim_started\", () => debouncedWrite());\n onLifecycleEvent(\"auth:claim_completed\", () => debouncedWrite());\n\n // No shutdown hook needed — the SHUTDOWN bypass in the core:state_changed\n // listener writes the final state synchronously during setCoreState(SHUTDOWN).\n // A hook would write SHUTTING_DOWN (before SHUTDOWN) and be immediately\n // overwritten by the listener. The listener is simpler and correct.\n\n // Write initial state immediately\n writeStateNow();\n}\n\n/**\n * Reset runtime state writer. For testing only.\n */\nexport function _resetRuntimeStateForTesting(): void {\n if (_debounceTimer) {\n clearTimeout(_debounceTimer);\n _debounceTimer = null;\n }\n _projectRoot = null;\n _sdkVersion = \"unknown\";\n _lastScenario = undefined;\n _started = false;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\nfunction debouncedWrite(): void {\n if (_debounceTimer) return; // Already scheduled\n\n _debounceTimer = setTimeout(() => {\n _debounceTimer = null;\n writeStateNow();\n }, 1000);\n\n // unref so the timer doesn't prevent process exit\n if (typeof _debounceTimer === \"object\" && \"unref\" in _debounceTimer) {\n _debounceTimer.unref();\n }\n}\n\nfunction writeStateNow(): void {\n if (!_projectRoot) return;\n\n try {\n const state = getSdkState();\n const runtimeState: RuntimeState = {\n updatedAt: new Date().toISOString(),\n pid: process.pid,\n sdkVersion: _sdkVersion,\n core: { state: state.core },\n auth: { state: state.auth },\n otel: { state: state.otel, scenario: _lastScenario },\n };\n\n const dir = join(_projectRoot, \".glasstrace\");\n const filePath = join(dir, \"runtime-state.json\");\n const tmpPath = join(dir, \"runtime-state.json.tmp\");\n\n // Ensure directory exists (may not if uninit deleted it)\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n\n // Atomic write: write to temp file then rename to avoid partial reads\n writeFileSync(tmpPath, JSON.stringify(runtimeState, null, 2) + \"\\n\", {\n mode: 0o600,\n });\n renameSync(tmpPath, filePath);\n } catch (err) {\n // Fire-and-forget — never block state transitions for a file write failure\n sdkLog(\n \"warn\",\n `[glasstrace] Failed to write runtime state: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n}\n","declare const __SDK_VERSION__: string;\n\nimport type { GlasstraceOptions, AnonApiKey } from \"@glasstrace/protocol\";\nimport { resolveConfig, isProductionDisabled, isAnonymousMode } from \"./env-detection.js\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { SessionManager } from \"./session.js\";\nimport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\nimport { loadCachedConfig, performInit, _setCurrentConfig, getActiveConfig, getLinkedAccountId, getClaimResult, didLastInitSucceed } from \"./init-client.js\";\nimport { createDiscoveryHandler } from \"./discovery-endpoint.js\";\nimport { configureOtel, setResolvedApiKey, getResolvedApiKey, notifyApiKeyResolved, resetOtelConfigForTesting } from \"./otel-config.js\";\nimport { installContextManager } from \"./context-manager.js\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { installConsoleCapture, uninstallConsoleCapture, sdkLog } from \"./console-capture.js\";\nimport { collectHealthReport, _resetHealthForTesting } from \"./health-collector.js\";\nimport { startHeartbeat, _resetHeartbeatForTesting } from \"./heartbeat.js\";\nimport { initLifecycle, setCoreState, CoreState, getCoreState, initAuthState, AuthState, setAuthState, emitLifecycleEvent, registerSignalHandlers, resetLifecycleForTesting } from \"./lifecycle.js\";\nimport { startRuntimeStateWriter, _resetRuntimeStateForTesting } from \"./runtime-state.js\";\n\n/** Mask an API key for safe event emission — shows prefix + last 4 chars. */\nfunction maskKey(key: string): string {\n if (key.length <= 12) return key.slice(0, 4) + \"...\";\n return key.slice(0, 8) + \"...\" + key.slice(-4);\n}\n\n/** Whether console capture has been installed in this registration cycle. */\nlet consoleCaptureInstalled = false;\n\n/** Module-level state tracking for the registered discovery handler. */\nlet discoveryHandler: ((request: Request) => Promise<Response | null>) | null = null;\n\n/** Generation counter to invalidate stale background promises after reset. */\nlet registrationGeneration = 0;\n\n/** Module-level session manager, shared with createGlasstraceSpanProcessor(). */\nlet _sessionManager: SessionManager | null = null;\n\n/** Returns the shared SessionManager. Creates a new one if registerGlasstrace() hasn't run yet. */\nexport function getSessionManager(): SessionManager {\n if (!_sessionManager) {\n _sessionManager = new SessionManager();\n }\n return _sessionManager;\n}\n\n/**\n * The primary SDK entry point called by developers in their `instrumentation.ts`.\n * Orchestrates OTel setup, span processor, init client, anon key, and discovery endpoint.\n *\n * This function is synchronous and MUST NOT throw. The developer's server is never blocked.\n * Background work (key resolution, init call) happens via fire-and-forget promises.\n *\n * @param options - Optional SDK configuration. Environment variables are used as fallbacks.\n *\n * @example\n * ```ts\n * // instrumentation.ts\n * import { registerGlasstrace } from \"@glasstrace/sdk\";\n * registerGlasstrace(); // uses env vars\n * ```\n */\nexport function registerGlasstrace(options?: GlasstraceOptions): void {\n try {\n // Prevent double registration (lifecycle state check replaces isRegistered flag)\n if (getCoreState() !== CoreState.IDLE) {\n return;\n }\n\n // Initialize lifecycle state machine before any state transitions.\n initLifecycle({ logger: sdkLog });\n\n // Guard: SDK requires Node.js runtime. Some environments (e.g. Bun,\n // Deno with partial Node compat) resolve node: imports but lack full\n // Node.js APIs. This guard prevents cryptic failures deeper in the\n // SDK by detecting these environments early and returning a no-op.\n //\n // Note: environments that cannot resolve node: imports at all (pure\n // Edge Runtime, Cloudflare Workers) will fail at module evaluation\n // before this guard runs. Those cases are mitigated by the package's\n // `sideEffects: false` flag and bundler externalization of node: modules.\n if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n console.warn(\n \"[glasstrace] SDK requires a Node.js runtime. \" +\n \"Edge Runtime, browser, and Deno without Node compat are not supported. \" +\n \"Glasstrace is disabled in this environment.\",\n );\n return;\n }\n\n setCoreState(CoreState.REGISTERING);\n\n // Start runtime state writer — writes lifecycle state to\n // .glasstrace/runtime-state.json for CLI status reporting (SDK-026).\n // Must be after initLifecycle() and Node.js guard.\n startRuntimeStateWriter({\n projectRoot: process.cwd(),\n sdkVersion: __SDK_VERSION__,\n });\n\n // Resolve config\n const config = resolveConfig(options);\n if (config.verbose) {\n console.info(\"[glasstrace] Config resolved.\");\n }\n\n // Production check\n if (isProductionDisabled(config)) {\n setCoreState(CoreState.PRODUCTION_DISABLED);\n console.warn(\n \"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override.\",\n );\n return;\n }\n if (config.verbose) {\n console.info(\"[glasstrace] Not production-disabled.\");\n }\n\n // Synchronous probe for an existing OTel provider. Used both to gate\n // the context manager installation below AND to decide whether to own\n // SIGTERM / SIGINT signal handling. If another tracing tool (Datadog,\n // Sentry, New Relic) has already registered a provider, the SDK must\n // NOT claim the global context manager slot — doing so would break\n // the other tool's context propagation. The ProxyTracer check is\n // synchronous; it sees any provider installed before registerGlasstrace()\n // was called (the standard instrumentation order).\n const existingProbe = otelApi.trace.getTracerProvider().getTracer(\"glasstrace-probe\");\n const anotherProviderRegistered = existingProbe.constructor.name !== \"ProxyTracer\";\n\n // Register SIGTERM/SIGINT handlers BEFORE any async work (DISC-1249),\n // but ONLY when this SDK will own the provider (Scenario A, bare path).\n // configureOtel() yields a tick and awaits the @vercel/otel probe;\n // without an early handler a signal arriving in that window would find\n // no coordinator and silently drop buffered spans.\n //\n // In coexistence mode (Scenario B) the existing provider already owns\n // signal shutdown. Adding a second handler here would race against it:\n // our handler re-raises the signal via process.kill() as soon as our\n // (initially empty) hook list drains, which could terminate the\n // process before the other provider's async flush completes. Instead,\n // we rely on the coexistence beforeExit trigger wired inside\n // configureOtel() plus the other provider's propagation of shutdown()\n // into our injected BatchSpanProcessor.\n //\n // Registered AFTER the production check so PRODUCTION_DISABLED processes\n // don't retain a handler that would log invalid-transition warnings if\n // signaled.\n if (!anotherProviderRegistered) {\n registerSignalHandlers();\n }\n\n // Determine auth mode\n const anonymous = isAnonymousMode(config);\n let effectiveKey: string | undefined = config.apiKey;\n\n // Set initial auth lifecycle state based on configuration\n initAuthState(anonymous ? AuthState.ANONYMOUS : AuthState.AUTHENTICATED);\n\n if (effectiveKey) {\n setResolvedApiKey(effectiveKey);\n emitLifecycleEvent(\"auth:key_resolved\", {\n key: maskKey(effectiveKey),\n mode: anonymous ? \"anonymous\" : \"dev\",\n });\n }\n\n if (config.verbose) {\n console.info(\n `[glasstrace] Auth mode = ${anonymous ? \"anonymous\" : \"dev-key\"}.`,\n );\n }\n\n // Load cached config and apply to in-memory store\n const cachedInitResponse = loadCachedConfig();\n if (cachedInitResponse) {\n _setCurrentConfig(cachedInitResponse);\n }\n if (config.verbose) {\n console.info(\n `[glasstrace] Cached config ${cachedInitResponse ? \"loaded and applied\" : \"not found\"}.`,\n );\n }\n\n // Create or reuse SessionManager (shared with createGlasstraceSpanProcessor)\n const sessionManager = getSessionManager();\n if (config.verbose) {\n console.info(\"[glasstrace] SessionManager created.\");\n }\n\n setCoreState(CoreState.KEY_PENDING);\n const currentGeneration = registrationGeneration;\n\n if (anotherProviderRegistered) {\n if (config.verbose) {\n console.info(\"[glasstrace] Another OTel provider detected — using existing context manager.\");\n }\n } else {\n // Register the context manager SYNCHRONOUSLY before any spans are\n // created. Without this, each span starts a new root trace with a\n // fresh traceId because there's no parent context to inherit from.\n // Must happen before configureOtel (which is async) — Next.js may\n // create spans between registerGlasstrace() returning and\n // configureOtel() completing (DISC-1183).\n const contextManagerInstalled = installContextManager();\n if (config.verbose) {\n console.info(\n contextManagerInstalled\n ? \"[glasstrace] Context manager installed.\"\n : \"[glasstrace] Context manager not available — trace context propagation disabled.\",\n );\n }\n }\n\n // Configure OTel IMMEDIATELY in all modes.\n // OTel is registered before the anon key resolves so that\n // spans are captured from cold start. GlasstraceExporter buffers spans\n // while the key is \"pending\" and flushes them once notifyApiKeyResolved()\n // is called after anonymous key resolution.\n // This is fire-and-forget -- OTel failure must not block init.\n void configureOtel(config, sessionManager).then(\n () => {\n // Check cached config for consoleErrors (may be stale or absent).\n // Re-checked after performInit completes with the authoritative config.\n maybeInstallConsoleCapture();\n\n if (config.verbose) {\n console.info(\"[glasstrace] OTel configured.\");\n }\n },\n (err: unknown) => {\n console.warn(\n `[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`,\n );\n },\n );\n\n // Background work: anonymous key resolution, discovery endpoint, init\n if (anonymous) {\n // Register discovery endpoint IMMEDIATELY with async key resolution\n if (isDiscoveryEnabled(config)) {\n let resolvedAnonKey: AnonApiKey | null = null;\n const anonKeyPromise = getOrCreateAnonKey();\n\n // Derive claim state from the init response.\n // Called on every discovery request so it reflects the latest state.\n // Two sources indicate a claimed account:\n // 1. linkedAccountId — key was already linked to an account\n // 2. claimResult — a claim just completed during this init call\n const getClaimState = () => {\n if (getLinkedAccountId()) return { claimed: true as const };\n if (getClaimResult()) return { claimed: true as const };\n return null;\n };\n\n // Use getResolvedApiKey() for session ID instead of\n // capturing the mutable effectiveKey closure variable.\n discoveryHandler = createDiscoveryHandler(\n async () => resolvedAnonKey,\n () => sessionManager.getSessionId(getResolvedApiKey()),\n getClaimState,\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Discovery endpoint registered (key pending).\");\n }\n\n // Background: resolve key, update API key, then init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await anonKeyPromise;\n resolvedAnonKey = anonKey;\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n // Update the discovery handler to serve the resolved key\n // Use getResolvedApiKey() for canonical key state\n discoveryHandler = createDiscoveryHandler(\n () => Promise.resolve(anonKey),\n () => sessionManager.getSessionId(getResolvedApiKey()),\n getClaimState,\n );\n\n await backgroundInit(config, anonKey, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n } else {\n // Anonymous + non-dev: no discovery endpoint, just background init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await getOrCreateAnonKey();\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n await backgroundInit(config, anonKey, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n } else {\n // Dev key mode: read straggler anon key, then fire init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n let anonKeyForInit: AnonApiKey | null = null;\n try {\n anonKeyForInit = await readAnonKey();\n } catch {\n // Expected when no prior anon key file exists on disk (first run).\n }\n\n if (currentGeneration !== registrationGeneration) return;\n\n await backgroundInit(config, anonKeyForInit, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n\n // Import graph (coverageMapEnabled) -- placeholder\n if (config.coverageMapEnabled && config.verbose) {\n console.info(\"[glasstrace] Import graph building skipped.\");\n }\n } catch (err) {\n setCoreState(CoreState.REGISTRATION_FAILED);\n console.warn(\n `[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Shared background init logic for all auth modes.\n *\n * Fires the init request, handles account claim transitions (updating\n * the exporter key), and re-checks console capture config. The anonymous\n * paths pass the anon key as `anonKeyForInit`; the dev-key path passes\n * the straggler anon key (or null).\n */\nasync function backgroundInit(\n config: ResolvedConfig,\n anonKeyForInit: AnonApiKey | null,\n generation: number,\n): Promise<void> {\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n const healthReport = collectHealthReport(__SDK_VERSION__);\n const initResult = await performInit(config, anonKeyForInit, __SDK_VERSION__, healthReport);\n\n if (generation !== registrationGeneration) return;\n\n // Bail if shutdown was initiated while backgroundInit was in flight.\n const currentState = getCoreState();\n if (currentState === CoreState.SHUTTING_DOWN || currentState === CoreState.SHUTDOWN) {\n return;\n }\n\n // Advance core lifecycle: KEY_PENDING → KEY_RESOLVED → ACTIVE/ACTIVE_DEGRADED.\n // In the full lifecycle (SDK-024), KEY_RESOLVED is triggered by auth:key_resolved.\n // For now, drive both transitions here since the auth layer isn't wired yet.\n if (currentState === CoreState.KEY_PENDING) {\n setCoreState(CoreState.KEY_RESOLVED);\n }\n if (getCoreState() === CoreState.KEY_RESOLVED) {\n setCoreState(didLastInitSucceed() ? CoreState.ACTIVE : CoreState.ACTIVE_DEGRADED);\n }\n\n // If the backend reported an account claim, update the exporter\n // key so subsequent span exports authenticate with the dev key.\n if (initResult?.claimResult) {\n const { newApiKey, accountId } = initResult.claimResult;\n setAuthState(AuthState.CLAIMING);\n emitLifecycleEvent(\"auth:claim_started\", { accountId });\n setResolvedApiKey(newApiKey);\n notifyApiKeyResolved();\n setAuthState(AuthState.CLAIMED);\n emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n }\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n\n // Start the periodic health heartbeat if init succeeded.\n // The heartbeat re-calls performInit every 5 minutes to report health\n // metrics and refresh config. Only starts after first successful init.\n if (didLastInitSucceed()) {\n startHeartbeat(config, anonKeyForInit, __SDK_VERSION__, generation, (newApiKey, accountId) => {\n setAuthState(AuthState.CLAIMING);\n emitLifecycleEvent(\"auth:claim_started\", { accountId });\n setResolvedApiKey(newApiKey);\n notifyApiKeyResolved();\n setAuthState(AuthState.CLAIMED);\n emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n });\n }\n}\n\n/**\n * Returns the registered discovery handler, or null if not registered.\n */\nexport function getDiscoveryHandler(): ((request: Request) => Promise<Response | null>) | null {\n return discoveryHandler;\n}\n\n/**\n * Checks the active config and installs console capture if enabled.\n * Idempotent — safe to call multiple times (after OTel config, after init).\n * This ensures console capture is installed whenever authoritative config\n * becomes available, whether from the file cache or the init response.\n */\nfunction maybeInstallConsoleCapture(): void {\n if (consoleCaptureInstalled) return;\n if (getActiveConfig().consoleErrors) {\n consoleCaptureInstalled = true;\n void installConsoleCapture();\n }\n}\n\n/**\n * Returns `true` if the discovery endpoint should be enabled for this environment.\n *\n * Tightened from \"not production\" to explicit development conditions:\n * 1. `GLASSTRACE_DISCOVERY_ENABLED=true` -- explicit override (highest priority)\n * 2. `GLASSTRACE_DISCOVERY_ENABLED=false` -- explicit disable (highest priority)\n * 3. `NODE_ENV` is `\"development\"` or unset, AND `VERCEL_ENV` is not `\"production\"`\n *\n * Environments like `staging`, `test`, and `ci` do not expose the discovery\n * endpoint by default, since it serves the anonymous API key over CORS.\n *\n * @param config - The resolved SDK configuration.\n * @returns Whether the discovery endpoint should be registered.\n */\nfunction isDiscoveryEnabled(config: ResolvedConfig): boolean {\n // Explicit flag takes precedence\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"true\") return true;\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"false\") return false;\n\n // Block production environments\n if (config.nodeEnv === \"production\") return false;\n if (config.vercelEnv === \"production\") return false;\n\n // Only allow in development or when NODE_ENV is unset\n if (config.nodeEnv === \"development\" || config.nodeEnv === undefined) return true;\n\n return false;\n}\n\n/**\n * Resets registration state. For testing only.\n */\nexport function _resetRegistrationForTesting(): void {\n discoveryHandler = null;\n consoleCaptureInstalled = false;\n registrationGeneration++;\n _resetHealthForTesting();\n _resetHeartbeatForTesting();\n uninstallConsoleCapture();\n resetOtelConfigForTesting();\n _resetRuntimeStateForTesting();\n _sessionManager = null;\n resetLifecycleForTesting();\n}\n","import { isBuiltin as isNodeBuiltin } from \"node:module\";\n\n/**\n * Structural view of Next.js's `NextConfig`. The SDK does not import Next's\n * type directly because Next is not a peer dependency — this wrapper must\n * type-check regardless of which Next.js version the consumer has installed.\n *\n * The constraint is `object` rather than `Record<string, unknown>` because\n * Next's actual `NextConfig` is an interface *without* a string index\n * signature. Requiring `[key: string]: unknown` would fail the assignability\n * check that caused DISC-1256, reported by Next 16 consumers as:\n * > Argument of type 'NextConfig' is not assignable to parameter of type\n * > 'NextConfig'. Index signature for type 'string' is missing in type\n * > 'NextConfig'.\n *\n * `object` accepts every non-primitive value, which is what the wrapper\n * actually handles at runtime (it shallow-copies the input and reads a few\n * known properties defensively). Combined with the generic signature on\n * `withGlasstraceConfig`, callers preserve their exact config subtype.\n */\ntype NextConfig = object;\ntype WebpackConfigFn = (config: Record<string, unknown>, context: Record<string, unknown>) => Record<string, unknown>;\n\n/** Subset of the webpack context object passed by Next.js to the webpack config function. */\ninterface WebpackContext {\n isServer: boolean;\n dev: boolean;\n [key: string]: unknown;\n}\n\n/** Minimal webpack compiler shape for the afterEmit hook. */\ninterface WebpackCompiler {\n hooks?: {\n afterEmit?: {\n tapPromise?: (name: string, fn: (compilation: unknown) => Promise<void>) => void;\n };\n };\n}\n\n/**\n * Detects whether the current `next build` invocation is using Turbopack.\n *\n * Next 16 made Turbopack the default bundler for `next build`. We detect it\n * via `process.argv` (the `--turbopack` flag or the absence of `--webpack`\n * on Next 16) and the `TURBOPACK` environment variable that Next sets\n * internally. Falls back to `false` in non-Node environments.\n */\nfunction isTurbopackBuild(): boolean {\n if (typeof process === \"undefined\") return false;\n\n const argv = Array.isArray(process.argv) ? process.argv : [];\n if (argv.includes(\"--webpack\")) return false;\n if (argv.includes(\"--turbopack\")) return true;\n\n // Next sets TURBOPACK=1 when running its Turbopack pipeline.\n if (process.env?.TURBOPACK === \"1\") return true;\n\n return false;\n}\n\n/**\n * Package name the wrapper adds to Next's server-external-packages list.\n * Kept as a module-level constant so tests can reference the exact string\n * without risk of drift between implementation and assertion.\n */\nconst SDK_PACKAGE_NAME = \"@glasstrace/sdk\";\n\n/**\n * Signature of a webpack 5 externals function in the array-of-entries form.\n * The `data` argument carries the import request; the `callback` signals\n * either an externalization decision (`\"commonjs <specifier>\"`) or a\n * pass-through (no second argument).\n *\n * Typed structurally rather than importing from `webpack` to keep the SDK\n * free of a webpack peer dependency.\n */\ntype WebpackExternalsFn = (\n data: { request?: string; context?: string; contextInfo?: unknown; getResolve?: unknown },\n callback: (err: Error | null, result?: string) => void,\n) => void;\n\n/**\n * Appends an externals entry to a webpack config that rewrites every\n * Node.js built-in import into a runtime CommonJS `require()`. This is\n * the piece of DISC-1257 that actually fixes `next dev --webpack`:\n * webpack dev-mode ships no default handler for the `node:` URI scheme\n * AND does not auto-externalize bare built-ins pulled through transitive\n * SDK dependencies (e.g. `import * as zlib from \"zlib\"` inside an OTel\n * exporter). Either form crashes the first render — `UnhandledSchemeError`\n * for `node:*`, `Can't resolve 'zlib'` for bare built-ins — unless the\n * wrapper tells webpack to treat them as runtime externals.\n *\n * Membership is decided by Node's own `isBuiltin` helper\n * (`node:module`, available since Node 18.6; SDK `engines` floor is\n * Node >= 20), so the list of built-ins stays authoritative across\n * Node versions — no hand-maintained allowlist to drift out of date.\n *\n * Webpack 5 accepts externals as a string, RegExp, object, function, or\n * array of any mixture of those. Next.js itself uses the array form. The\n * helper preserves whatever the user (or Next) already supplied:\n * - Array: append the new entry, user entries keep their positions.\n * - Function or object: wrap in an array with the user entry first so it\n * takes precedence over the SDK's handler.\n * - Missing / nullish: initialise as a single-entry array.\n *\n * The emitted `commonjs <request>` form preserves whichever specifier the\n * caller used (prefixed or bare), which Node resolves natively on Node\n * >= 14.18 — well below the SDK's `engines` floor of Node >= 20.\n */\nfunction appendNodeSchemeExternal(webpackConfig: Record<string, unknown>): void {\n const nodeBuiltinExternal: WebpackExternalsFn = (data, callback) => {\n const request = data.request;\n if (typeof request === \"string\" && isNodeBuiltin(request)) {\n callback(null, \"commonjs \" + request);\n return;\n }\n callback(null);\n };\n\n const existing = webpackConfig.externals;\n if (Array.isArray(existing)) {\n webpackConfig.externals = [...existing, nodeBuiltinExternal];\n } else if (existing == null) {\n webpackConfig.externals = [nodeBuiltinExternal];\n } else {\n // Function, object-map, RegExp, or string form — preserve as the first\n // array entry so user/Next externals resolve before the SDK's fallback.\n webpackConfig.externals = [existing, nodeBuiltinExternal];\n }\n}\n\n/**\n * Pushes `@glasstrace/sdk` onto Next.js's `serverExternalPackages` list so\n * the package is loaded via Node's `require()` at runtime instead of\n * bundled through webpack/Turbopack.\n *\n * Only the Next 15+ stable top-level key is written. The Next 14 legacy\n * `experimental.serverComponentsExternalPackages` key was dropped because\n * Next 16 logs a deprecation warning for it on every build. Next 14 is\n * EOL; webpack-dev users on Next 14 are covered by the companion\n * `node:*` externals function installed below, and Turbopack users on\n * Next 14 were already unaffected.\n *\n * Dedupe is intentional: if the user already added `@glasstrace/sdk` to\n * the array, the entry is not duplicated. User entries are preserved in\n * their original order; the SDK entry is appended.\n *\n * Note that `serverExternalPackages` only affects RSC and Route Handler\n * bundling — it does NOT externalize the instrumentation path under\n * `next dev --webpack` (see vercel/next.js#58003, #28774). The full fix\n * for DISC-1257 pairs this write with the `node:*` externals function.\n *\n * Mutates the `config` bag in place; callers pass the shallow-copied bag\n * owned by `withGlasstraceConfig`, so the user's original reference is not\n * affected.\n */\nfunction ensureServerExternal(config: Record<string, unknown>): void {\n // Next 15+ stable key: top-level `serverExternalPackages`.\n const existingStable = config.serverExternalPackages;\n const stable: string[] = Array.isArray(existingStable)\n ? // Clone so we never mutate a caller-owned array in place.\n existingStable.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n if (!stable.includes(SDK_PACKAGE_NAME)) {\n stable.push(SDK_PACKAGE_NAME);\n }\n config.serverExternalPackages = stable;\n}\n\n/**\n * Wraps the developer's Next.js config to enable source map generation\n * and upload .map files to the ingestion API at build time.\n *\n * The build NEVER fails because of Glasstrace — all errors are caught\n * and logged as warnings.\n *\n * ## What the wrapper configures for you\n *\n * - `experimental.serverSourceMaps: true` — enables server-side source maps\n * so Glasstrace can resolve stack traces back to your source.\n * - `serverExternalPackages: [\"@glasstrace/sdk\"]` — tells Next to load the\n * SDK via Node's `require()` at runtime instead of bundling it through\n * webpack or Turbopack on the RSC / Route Handler paths. This is the same\n * pattern Prisma, `@vercel/otel`, Sentry, `sharp`, and `bcrypt` ship with.\n * - A webpack `externals` entry that marks every Node.js built-in import\n * (both `node:*` and bare forms like `zlib` or `stream`) as a runtime\n * `commonjs` require. `serverExternalPackages` does not apply to the\n * instrumentation path under `next dev --webpack`\n * (vercel/next.js#58003, #28774), so any bundled SDK chunk that imports\n * `node:child_process` or the bare `zlib` specifier used by\n * `@opentelemetry/otlp-exporter-base` would otherwise crash with\n * `UnhandledSchemeError` or `Can't resolve 'zlib'`. This entry is the\n * actual DISC-1257 fix for the dev-webpack path. Turbopack is\n * unaffected — it ignores `config.webpack` and resolves Node built-ins\n * natively.\n * - An empty `turbopack: {}` when none is set, so Next 16 does not reject\n * the config for setting `webpack` without a companion `turbopack` key\n * (DISC-1256).\n * - A `webpack` hook that collects and uploads `.map` files on client-side\n * production builds.\n *\n * ## Turbopack\n *\n * Next.js 16 made Turbopack the default bundler for `next build`, and Next\n * rejects configs that set `webpack` without also setting `turbopack`. This\n * wrapper therefore seeds an empty `turbopack: {}` when the user has not set\n * one themselves, preserving existing behaviour for explicit Turbopack configs.\n *\n * **Source-map upload is currently webpack-only.** Under Turbopack the build\n * succeeds, but the afterEmit hook that collects and uploads `.map` files does\n * not fire. Run `next build --webpack` to get source-map uploads, or wait for\n * a follow-up release that ports the plugin to Turbopack.\n *\n * @param nextConfig - The developer's existing Next.js configuration object.\n * @returns A new config object with source map generation and upload enabled.\n * The return type mirrors the input type so that caller-side config\n * properties are preserved. The `object` constraint (rather than\n * `Record<string, unknown>`) is what makes the wrapper accept Next's\n * real `NextConfig` interface (DISC-1256).\n */\nexport function withGlasstraceConfig<T extends NextConfig>(nextConfig: T): T {\n // Guard: config wrapper requires Node.js for source map instrumentation.\n // In non-Node environments (Edge Runtime, browser), return config unchanged.\n if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n return (nextConfig != null ? { ...nextConfig } : ({} as T));\n }\n\n // Handle null/undefined gracefully\n const config: T = nextConfig != null ? { ...nextConfig } : ({} as T);\n // Mutable bag-of-props view of the same object. Using `object` as the\n // constraint (see the `NextConfig` type alias above) means `T` does not\n // declare the keys we touch — `experimental`, `turbopack`, `distDir`,\n // `webpack` — so we interact with them through this looser view while the\n // public return type stays faithfully `T`.\n const bag = config as Record<string, unknown>;\n\n // Enable server-side source map generation for Glasstrace uploads.\n // Intentionally does NOT set productionBrowserSourceMaps — that exposes\n // full source code publicly via browser DevTools. Users who want public\n // browser source maps can set it explicitly in their Next.js config.\n\n // Enable server-side source maps (Next.js experimental feature)\n const existingExperimental = (bag.experimental as Record<string, unknown>) ?? {};\n bag.experimental = {\n ...existingExperimental,\n serverSourceMaps: true,\n };\n\n // Mark the SDK as a server-external package (DISC-1257). This covers the\n // RSC and Route Handler bundlers on Next 15+. The companion `node:*`\n // externals entry inside the `config.webpack` hook below is what actually\n // unblocks `next dev --webpack`.\n ensureServerExternal(bag);\n\n // Seed an empty Turbopack config when the user has not set one. Next 16\n // refuses builds that set `webpack` without a companion `turbopack` key\n // (DISC-1256). Merging preserves any existing Turbopack config the user\n // supplied — we only fill in the default.\n if (bag.turbopack == null) {\n bag.turbopack = {};\n }\n\n // One-time warning: source-map upload does not run under Turbopack yet.\n // Log at most once per process to avoid spamming repeated builds (dev mode,\n // watch mode). The warning goes to stderr via console.warn — intentionally\n // not using sdkLog so the message surfaces during the build even if SDK\n // logging is otherwise suppressed.\n if (isTurbopackBuild()) {\n warnTurbopackLimitationOnce();\n }\n\n // Capture distDir for source map collection (default: .next)\n const distDir = typeof bag.distDir === \"string\" ? bag.distDir : \".next\";\n\n // Capture existing webpack config if any\n const existingWebpack = bag.webpack as WebpackConfigFn | undefined;\n\n // Register webpack config modifier\n bag.webpack = (\n webpackConfig: Record<string, unknown>,\n context: Record<string, unknown>,\n ): Record<string, unknown> => {\n // Call existing webpack config first\n let result = webpackConfig;\n if (typeof existingWebpack === \"function\") {\n result = existingWebpack(webpackConfig, context);\n }\n\n // DISC-1257: externalize Node.js built-in imports for the webpack path.\n const webpackContext = context as WebpackContext;\n\n // Next's `serverExternalPackages` only influences RSC / Route Handler\n // bundling; the instrumentation path under `next dev --webpack` still\n // runs transitive SDK imports through the dev bundler, which crashes\n // on any built-in module — `UnhandledSchemeError` for `node:*` and\n // `Can't resolve 'zlib'` / `'stream'` / etc. for bare specifiers used\n // by OTel's exporter dependencies (vercel/next.js#58003, #28774).\n //\n // Telling webpack to externalize every Node built-in as a runtime\n // CommonJS require resolves the crash on every SERVER webpack code\n // path — production build, dev server, instrumentation hook. We\n // scope it to `webpackContext.isServer` so client-side compilations\n // (where Next applies browser polyfills / fallbacks for things like\n // `buffer` / `stream` / `crypto`) are not affected. Emitting\n // `commonjs` externals on the client would bypass those fallbacks\n // and inject `require(...)` at runtime, which fails in the browser.\n // Turbopack ignores this field and resolves Node built-ins natively\n // on both client and server.\n if (webpackContext.isServer) {\n appendNodeSchemeExternal(result);\n }\n\n // Only run source map upload on client-side production builds (not server, not dev)\n if (!webpackContext.isServer && webpackContext.dev === false) {\n // Register a plugin to collect and upload source maps after compilation\n const plugins = (result.plugins as Array<Record<string, unknown>>) ?? [];\n plugins.push({\n apply(compiler: Record<string, unknown>) {\n const typedCompiler = compiler as WebpackCompiler;\n if (typedCompiler.hooks?.afterEmit?.tapPromise) {\n typedCompiler.hooks.afterEmit.tapPromise(\n \"GlasstraceSourceMapUpload\",\n async () => {\n await handleSourceMapUpload(distDir);\n },\n );\n }\n },\n });\n result.plugins = plugins;\n }\n\n return result;\n };\n\n return config;\n}\n\nlet _turbopackWarningEmitted = false;\nfunction warnTurbopackLimitationOnce(): void {\n if (_turbopackWarningEmitted) return;\n _turbopackWarningEmitted = true;\n console.warn(\n \"[glasstrace] Turbopack detected. Source-map upload currently runs only under webpack — \" +\n \"run `next build --webpack` to upload source maps, or wait for the Turbopack port in a future SDK release.\",\n );\n}\n\n/**\n * Resets the one-shot Turbopack warning flag. For test use only.\n *\n * @internal\n */\nexport function _resetTurbopackWarningForTesting(): void {\n _turbopackWarningEmitted = false;\n}\n\n/**\n * Collects source map files from the build output directory and uploads\n * them to the Glasstrace ingestion API. Never throws — all errors are\n * caught and logged as warnings so the build is never blocked.\n *\n * Exported for testing only; not part of the public API.\n *\n * @param distDir - The Next.js build output directory (e.g. \".next\").\n */\nexport async function handleSourceMapUpload(distDir: string): Promise<void> {\n try {\n const apiKey = process.env.GLASSTRACE_API_KEY;\n const endpoint =\n process.env.GLASSTRACE_ENDPOINT ?? \"https://api.glasstrace.dev\";\n\n // Anonymous mode: skip upload\n if (!apiKey || apiKey.trim() === \"\") {\n console.info(\n \"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations.\",\n );\n return;\n }\n\n // Dynamic import: source-map-uploader uses node:fs, node:path, node:crypto,\n // and node:child_process. Deferring the import avoids a module-evaluation\n // crash when config-wrapper.ts is loaded in a non-Node bundler context.\n const { discoverSourceMapFiles, computeBuildHash, uploadSourceMaps } =\n await import(\"./source-map-uploader.js\");\n\n const files = await discoverSourceMapFiles(distDir);\n\n if (files.length === 0) {\n console.info(\"[glasstrace] No source map files found. Skipping upload.\");\n return;\n }\n\n const buildHash = await computeBuildHash(files);\n\n await uploadSourceMaps(apiKey, endpoint, buildHash, files);\n console.info(\n `[glasstrace] Uploaded ${String(files.length)} source map(s) for build ${buildHash}.`,\n );\n } catch (error: unknown) {\n // Build must NEVER fail because of Glasstrace\n const message =\n error instanceof Error ? error.message : \"Unknown error\";\n console.warn(\n `[glasstrace] Source map upload failed: ${message}. Build continues normally.`,\n );\n }\n}\n","/**\n * Manual error capture API.\n *\n * Provides a simple function for developers to manually record errors\n * as span events, independent of the `consoleErrors` config flag.\n */\n\nimport * as otelApi from \"@opentelemetry/api\";\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Records an error as a span event on the currently active OTel span.\n *\n * Works regardless of the `consoleErrors` configuration — this is an\n * explicit, opt-in API for manual error reporting. If no span is active\n * or OTel is not available, the call is silently ignored.\n *\n * On the first captured error, may display a one-time diagnostic nudge\n * to stderr if the MCP connection marker is absent (dev environments only).\n *\n * @param error - The error to capture. Accepts `Error` objects, strings, or any value.\n *\n * @example\n * ```ts\n * import { captureError } from \"@glasstrace/sdk\";\n *\n * try {\n * await riskyOperation();\n * } catch (err) {\n * captureError(err);\n * // handle error normally...\n * }\n * ```\n */\nexport function captureError(error: unknown): void {\n try {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (!span) return;\n\n const attributes: Record<string, string> = {\n \"error.message\": String(error),\n };\n\n if (error instanceof Error) {\n attributes[\"error.type\"] = error.constructor.name;\n if (error.stack) {\n attributes[\"error.stack\"] = error.stack;\n }\n }\n\n span.addEvent(\"glasstrace.error\", attributes);\n\n // Show one-time MCP connection nudge on first captured error\n maybeShowMcpNudge(String(error));\n } catch {\n // Silently ignore failures\n }\n}\n\n/**\n * Eagerly loads the OTel API module. Previously required for async resolution;\n * now a no-op since OTel is statically imported. Retained for test compatibility.\n *\n * @internal\n */\nexport async function _preloadOtelApi(): Promise<void> {\n // No-op: OTel API is now statically imported and always available.\n}\n\n/**\n * Resets internal state. For testing only.\n * @internal\n */\nexport function _resetCaptureErrorForTesting(): void {\n // No-op: OTel API is now statically imported and always available.\n // Kept for backward compatibility with existing tests.\n}\n","import { trace } from \"@opentelemetry/api\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\nconst HEADER_NAME = \"x-gt-cid\";\n\n/**\n * Hard cap on the correlation ID length we accept from the wire. Our\n * own extension emits ULIDs (26 characters); 128 is a generous ceiling\n * that still prevents a hostile client from ballooning span payloads.\n */\nconst MAX_CID_LENGTH = 128;\n\n/**\n * Minimal Fetch-API `Headers`-like interface supporting case-insensitive\n * single-value lookup. Matches `Headers` from `undici` / the Web Fetch API.\n */\ninterface FetchHeadersLike {\n get(name: string): string | null;\n}\n\n/**\n * Minimal Node `IncomingMessage.headers`-like shape: a dictionary mapping\n * (typically lower-cased) header names to a value, a list of values, or\n * `undefined`.\n */\ntype NodeHeadersLike = Record<\n string,\n string | string[] | undefined\n>;\n\n/**\n * Accepted request shape for {@link captureCorrelationId}. Intentionally\n * loose so callers can pass either a Fetch `Request` (or `NextRequest`)\n * or a Node `IncomingMessage` without adapting the type.\n */\nexport interface CorrelationIdRequest {\n headers: FetchHeadersLike | NodeHeadersLike | undefined;\n}\n\n/**\n * Captures the Glasstrace correlation ID header (`x-gt-cid`) from an\n * incoming request and materializes it as the\n * `glasstrace.correlation.id` attribute on the currently active OTel span\n * (DISC-1253).\n *\n * The SDK does not own any HTTP instrumentation, so it cannot read this\n * header itself. Users opt in by calling this helper from a hook that\n * runs inside the request's OTel context — typically a Next.js\n * `middleware.ts` or a custom server request handler.\n *\n * The function is intentionally forgiving:\n * - No active span → no-op.\n * - Missing / empty header → no-op.\n * - Array header values (Node IncomingMessage) → the first non-empty\n * value is used; subsequent values are ignored because a correlation\n * ID is a single logical value.\n * - Malformed or unexpected `headers` shapes → caught and ignored; the\n * helper never throws.\n *\n * @example\n * ```ts\n * // Next.js middleware.ts\n * import { captureCorrelationId } from \"@glasstrace/sdk\";\n *\n * export function middleware(req: Request) {\n * captureCorrelationId(req);\n * return NextResponse.next();\n * }\n * ```\n */\nexport function captureCorrelationId(req: CorrelationIdRequest | null | undefined): void {\n try {\n if (!req || !req.headers) {\n return;\n }\n\n const value = readHeader(req.headers);\n if (!value) {\n return;\n }\n\n const span = trace.getActiveSpan();\n if (!span) {\n return;\n }\n\n span.setAttribute(ATTR.CORRELATION_ID, value);\n } catch {\n // Never throw from a request hook — correlation is a best-effort\n // enrichment and must not break the user's request pipeline.\n }\n}\n\n/**\n * Reads the `x-gt-cid` header from either a Fetch-API `Headers` object\n * or a Node-style dictionary. Returns a trimmed single value, or\n * `undefined` if the header is missing or empty.\n */\nfunction readHeader(\n headers: FetchHeadersLike | NodeHeadersLike,\n): string | undefined {\n // Fetch-API Headers: duck-type on `.get(name)` being a function.\n const asFetch = headers as FetchHeadersLike;\n if (typeof asFetch.get === \"function\") {\n const raw = asFetch.get(HEADER_NAME);\n return firstToken(raw);\n }\n\n // Node IncomingMessage headers: case-insensitive dictionary lookup.\n // Node normalizes to lower-case but some frameworks preserve case, so\n // scan keys defensively.\n const dict = headers as NodeHeadersLike;\n const direct = dict[HEADER_NAME];\n if (direct !== undefined) {\n return firstValue(direct);\n }\n\n for (const key of Object.keys(dict)) {\n if (key.toLowerCase() === HEADER_NAME) {\n return firstValue(dict[key]);\n }\n }\n\n return undefined;\n}\n\n/**\n * Picks the first value from a possibly-array header and trims it.\n * Correlation IDs are logically single-valued; when duplicated we keep\n * the first occurrence and drop the rest.\n *\n * Also handles the comma-joined form that intermediaries (and some\n * Node.js HTTP stacks) produce when the same header is sent multiple\n * times — `x-gt-cid: cid1, x-gt-cid: cid2` may surface as the single\n * string `\"cid1, cid2\"` via `Headers.get()` or `IncomingMessage.headers`.\n * Storing that raw merged value would both fail correlation and\n * silently suppress the DISC-1253 Server Action nudge (which only\n * checks attribute presence, not validity). We split on commas and\n * keep the first non-empty token.\n */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n if (Array.isArray(value)) {\n for (const entry of value) {\n const token = firstToken(entry);\n if (token) return token;\n }\n return undefined;\n }\n return firstToken(value);\n}\n\n/**\n * Extracts the first comma-separated token from a header-like string\n * and normalizes it. Returns undefined when no non-empty token exists\n * within the length bound.\n */\nfunction firstToken(value: string | null | undefined): string | undefined {\n if (typeof value !== \"string\") return undefined;\n // Split on commas (HTTP list-header separator). Trim each token and\n // return the first non-empty one that fits within MAX_CID_LENGTH.\n // A single un-merged header has no commas and this reduces to the\n // previous normalize() behavior.\n const parts = value.split(\",\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n if (trimmed.length > MAX_CID_LENGTH) return undefined;\n return trimmed;\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O,UAAU,SAAU,QAAO;AAKtC,QAAM,QAAQ,MAAM,MAAM,GAAG;AAC7B,aAAW,QAAQ,OAAO;AACxB,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,QAAQ,WAAW,EAAG;AAC1B,QAAI,QAAQ,SAAS,eAAgB,QAAO;AAC5C,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["cachedPort","cachedPort","_sessionManager","context","context","ExportResultCode","resolve","hrTime","hrTime","VERSION","VERSION","resolve","resolve","path","SamplingDecision","SamplingDecision","SamplingDecision","context","context","SamplingDecision","TracesSamplerValues","resolve","SamplingDecision","VERSION","VERSION","context","resolve","context","ForceFlushState","resolve","resolve","processor","resolve","prismaModule","context","context","discoverSourceMapFiles","computeBuildHash","uploadSourceMaps","ATTR"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/session.ts","../src/fetch-classifier.ts","../src/span-processor.ts","../src/enriching-exporter.ts","../src/discovery-endpoint.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts","../../../node_modules/@opentelemetry/core/src/semconv.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/@opentelemetry/resources/src/default-service-name.ts","../../../node_modules/@opentelemetry/resources/src/utils.ts","../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/version.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../src/lifecycle.ts","../src/signal-handler.ts","../src/coexistence.ts","../src/otel-config.ts","../src/context-manager.ts","../src/heartbeat.ts","../src/runtime-state.ts","../src/register.ts","../src/config-wrapper.ts","../src/capture-error.ts","../src/correlation-id.ts"],"sourcesContent":["import type { SdkDiagnosticCode } from \"@glasstrace/protocol\";\n\n/**\n * Internal SDK error class with a typed diagnostic code.\n * Caught at the boundary and converted to a log message + diagnostic entry.\n * Never thrown to the developer.\n */\nexport class SdkError extends Error {\n readonly code: SdkDiagnosticCode;\n\n constructor(code: SdkDiagnosticCode, message: string, cause?: Error) {\n super(message, { cause });\n this.name = \"SdkError\";\n this.code = code;\n }\n}\n","import { SessionIdSchema } from \"@glasstrace/protocol\";\nimport type { SessionId } from \"@glasstrace/protocol\";\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\n\n/**\n * Lazy-loaded hash function. Uses Node.js `node:crypto` when available,\n * falling back to a deterministic non-cryptographic hash (FNV-1a) in\n * environments where `node:crypto` cannot be resolved (Edge Runtime,\n * browser bundles).\n *\n * Session IDs are identifiers, not security-sensitive values, so a\n * non-cryptographic hash is acceptable as a fallback.\n */\nlet hashFn: ((input: string) => string) | null = null;\n\n/**\n * FNV-1a hash producing an 8-character hex string.\n * Used as a fallback when `node:crypto` is unavailable.\n * Not cryptographically secure, but deterministic and fast.\n */\nfunction fnv1aHash(input: string): string {\n let hash = 0x811c9dc5; // FNV offset basis (32-bit)\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193); // FNV prime\n hash >>>= 0; // keep unsigned 32-bit\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n/**\n * Returns a hash function, resolving `node:crypto` on first call.\n * Thread-safe: worst case two calls both resolve — same result either way.\n */\nfunction getHashFn(): (input: string) => string {\n if (hashFn) return hashFn;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { createHash } = require(\"node:crypto\") as typeof import(\"node:crypto\");\n hashFn = (input: string) =>\n createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 16);\n } catch {\n // node:crypto unavailable — use FNV-1a fallback.\n // Pad to 16 chars by double-hashing the first and second halves.\n hashFn = (input: string) => {\n const h1 = fnv1aHash(input);\n const h2 = fnv1aHash(input + \"\\0\");\n return (h1 + h2).slice(0, 16);\n };\n }\n\n return hashFn;\n}\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedGlasstraceEnv: string | undefined = process.env.GLASSTRACE_ENV;\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Resets the lazy-loaded hash function. For testing only.\n * @internal\n */\nexport function _resetHashFnForTesting(): void {\n hashFn = null;\n}\n\n/**\n * Forces the fallback (FNV-1a) hash function. For testing only.\n * @internal\n */\nexport function _useFallbackHashForTesting(): void {\n hashFn = (input: string) => {\n const h1 = fnv1aHash(input);\n const h2 = fnv1aHash(input + \"\\0\");\n return (h1 + h2).slice(0, 16);\n };\n}\n\n/**\n * Derives a deterministic session ID from the given inputs.\n * Uses SHA-256 (truncated to 16 hex chars) when `node:crypto` is available,\n * or a deterministic FNV-1a hash as a fallback in non-Node environments.\n *\n * @param apiKey - The project's API key (or anonymous placeholder).\n * @param origin - The origin string identifying the deployment environment.\n * @param date - UTC date as YYYY-MM-DD.\n * @param windowIndex - Zero-based index of the 4-hour activity window within the day.\n * @returns A 16-character hex SessionId.\n */\nexport function deriveSessionId(\n apiKey: string,\n origin: string,\n date: string,\n windowIndex: number,\n): SessionId {\n const input = JSON.stringify([apiKey, origin, date, windowIndex]);\n const hash = getHashFn()(input);\n return SessionIdSchema.parse(hash);\n}\n\n/**\n * Returns the origin string for the current process.\n * If GLASSTRACE_ENV is set, returns that value.\n * Otherwise returns `localhost:{PORT}` (PORT defaults to 3000).\n *\n * @returns The origin string used as a session derivation input.\n */\nexport function getOrigin(): string {\n if (cachedGlasstraceEnv) {\n return cachedGlasstraceEnv;\n }\n return `localhost:${cachedPort}`;\n}\n\n/**\n * Returns the current UTC date as a YYYY-MM-DD string.\n *\n * @returns The UTC date formatted as \"YYYY-MM-DD\".\n */\nexport function getDateString(): string {\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(now.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n\n/**\n * Tracks the current session state with 4-hour window tracking.\n * Instantiated once by the orchestrator.\n */\nexport class SessionManager {\n private windowIndex: number = 0;\n private lastActivityTimestamp: number = 0;\n private lastDate: string = \"\";\n private lastApiKey: string = \"\";\n private currentSessionId: SessionId | null = null;\n\n /**\n * Returns the current session ID, deriving a new one if:\n * - More than 4 hours have elapsed since last activity\n * - The UTC date has changed (resets window index to 0)\n * - The API key has changed (e.g., deferred anonymous key swap)\n * - This is the first call\n *\n * @param apiKey - The project's API key used in session derivation.\n * @returns The current or newly derived SessionId.\n */\n getSessionId(apiKey: string): SessionId {\n const now = Date.now();\n const currentDate = getDateString();\n const origin = getOrigin();\n\n const elapsed = now - this.lastActivityTimestamp;\n const dateChanged = currentDate !== this.lastDate;\n const apiKeyChanged = apiKey !== this.lastApiKey;\n\n if (dateChanged) {\n // New UTC day: reset window index\n this.windowIndex = 0;\n this.lastDate = currentDate;\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (apiKeyChanged) {\n // API key changed (e.g., anonymous key resolved): re-derive with same window\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {\n // First call or gap exceeding 4 hours: increment window\n if (this.currentSessionId !== null) {\n this.windowIndex++;\n }\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n this.lastDate = currentDate;\n }\n\n this.lastActivityTimestamp = now;\n return this.currentSessionId;\n }\n}\n","/**\n * The set of recognized fetch target categories.\n */\nexport type FetchTarget = \"supabase\" | \"stripe\" | \"internal\" | \"unknown\";\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Classifies an outbound fetch target URL into a known category.\n * Classification is case-insensitive and based on the URL hostname.\n * Uses dot-boundary matching to avoid false positives (e.g. evilstripe.com).\n *\n * Returns one of: 'supabase', 'stripe', 'internal', or 'unknown'.\n */\nexport function classifyFetchTarget(url: string): FetchTarget {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return \"unknown\";\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n if (\n hostname === \"supabase.co\" ||\n hostname.endsWith(\".supabase.co\") ||\n hostname === \"supabase.in\" ||\n hostname.endsWith(\".supabase.in\")\n ) {\n return \"supabase\";\n }\n\n if (hostname === \"stripe.com\" || hostname.endsWith(\".stripe.com\")) {\n return \"stripe\";\n }\n\n const internalOrigin = `localhost:${cachedPort}`;\n const parsedPort = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n const urlOrigin = `${hostname}:${parsedPort}`;\n\n if (urlOrigin === internalOrigin) {\n return \"internal\";\n }\n\n return \"unknown\";\n}\n","import type { SpanProcessor, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport type { Span } from \"@opentelemetry/sdk-trace-base\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\n\n/**\n * Lightweight SpanProcessor that delegates to a wrapped processor.\n *\n * All glasstrace.* attribute enrichment has been moved to {@link GlasstraceExporter}\n * (see enriching-exporter.ts), which enriches spans at export time. This resolves:\n * - Cold-start spans are buffered in the exporter, not dropped\n * - Vercel's CompositeSpanProcessor skips onEnding(); the exporter doesn't need it\n * - Session ID is computed at export time with the resolved API key\n *\n * This class is retained for backward compatibility. New code should use\n * GlasstraceExporter directly.\n *\n * @deprecated Use GlasstraceExporter for span enrichment. This processor is now a pass-through.\n */\nexport class GlasstraceSpanProcessor implements SpanProcessor {\n private readonly wrappedProcessor: SpanProcessor;\n\n /* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */\n constructor(\n wrappedProcessor: SpanProcessor,\n _sessionManager?: SessionManager,\n _apiKey?: string | (() => string),\n _getConfig?: () => CaptureConfig,\n _environment?: string,\n ) {\n /* eslint-enable @typescript-eslint/no-unused-vars */\n this.wrappedProcessor = wrappedProcessor;\n }\n\n onStart(span: Span, parentContext: Parameters<SpanProcessor[\"onStart\"]>[1]): void {\n this.wrappedProcessor.onStart(span, parentContext);\n }\n\n onEnd(readableSpan: ReadableSpan): void {\n this.wrappedProcessor.onEnd(readableSpan);\n }\n\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n}\n","import { SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport type { ExportResult } from \"@opentelemetry/core\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\nimport { classifyFetchTarget } from \"./fetch-classifier.js\";\nimport { recordSpansExported, recordSpansDropped } from \"./health-collector.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { maybeShowServerActionNudge } from \"./nudge/error-nudge.js\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\n\n/**\n * Sentinel value indicating the API key has not yet been resolved.\n */\nexport const API_KEY_PENDING = \"pending\" as const;\n\n/**\n * Maximum number of spans to buffer while waiting for key resolution.\n * Prevents unbounded memory growth if the key never resolves.\n */\nconst MAX_PENDING_SPANS = 1024;\n\n\n/**\n * Options for constructing a {@link GlasstraceExporter}.\n */\nexport interface GlasstraceExporterOptions {\n getApiKey: () => string;\n sessionManager: SessionManager;\n getConfig: () => CaptureConfig;\n environment: string | undefined;\n endpointUrl: string;\n createDelegate: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n /** When true, logs diagnostic details about enrichment decisions via sdkLog. */\n verbose?: boolean;\n}\n\ninterface PendingBatch {\n spans: ReadableSpan[];\n resultCallback: (result: ExportResult) => void;\n}\n\n/**\n * A SpanExporter that enriches spans with glasstrace.* attributes at export\n * time, then delegates to a real OTLP exporter.\n *\n * This design resolves three issues:\n * - Spans emitted before the API key resolves are buffered (not dropped)\n * and flushed once the key is available.\n * - Enrichment happens in the exporter (not onEnding), so it works\n * on Vercel where CompositeSpanProcessor does not forward onEnding().\n * - Session ID is computed at export time using the resolved API key,\n * not the \"pending\" placeholder.\n */\nexport class GlasstraceExporter implements SpanExporter {\n private readonly getApiKey: () => string;\n private readonly sessionManager: SessionManager;\n private readonly getConfig: () => CaptureConfig;\n private readonly environment: string | undefined;\n private readonly endpointUrl: string;\n private readonly createDelegateFn: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n private readonly verbose: boolean;\n\n private delegate: SpanExporter | null = null;\n private delegateKey: string | null = null;\n private pendingBatches: PendingBatch[] = [];\n private pendingSpanCount = 0;\n private overflowLogged = false;\n\n constructor(options: GlasstraceExporterOptions) {\n this.getApiKey = options.getApiKey;\n this.sessionManager = options.sessionManager;\n this.getConfig = options.getConfig;\n this.environment = options.environment;\n this.endpointUrl = options.endpointUrl;\n this.createDelegateFn = options.createDelegate;\n this.verbose = options.verbose ?? false;\n\n // Brand for coexistence detection — allows isGlasstraceProcessorPresent()\n // to detect our exporter across bundled copies via a global symbol registry.\n (this as unknown as Record<symbol, boolean>)[Symbol.for(\"glasstrace.exporter\")] = true;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) {\n // Buffer raw (unenriched) spans — enrichment deferred to flush time\n // so session IDs are computed with the resolved key, not \"pending\".\n this.bufferSpans(spans, resultCallback);\n return;\n }\n\n // Key is available — enrich and export\n const enrichedSpans = spans.map((span) => this.enrichSpan(span));\n const exporter = this.ensureDelegate();\n if (exporter) {\n exporter.export(enrichedSpans, (result) => {\n if (result.code !== 0) {\n sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n }\n resultCallback(result);\n });\n recordSpansExported(enrichedSpans.length);\n } else {\n // No delegate factory — spans are discarded, count as dropped\n recordSpansDropped(enrichedSpans.length);\n resultCallback({ code: 0 });\n }\n }\n\n /**\n * Called when the API key transitions from \"pending\" to a resolved value.\n * Creates the delegate exporter and flushes all buffered spans.\n */\n notifyKeyResolved(): void {\n this.flushPending();\n }\n\n async shutdown(): Promise<void> {\n const currentKey = this.getApiKey();\n if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n } else if (this.pendingBatches.length > 0) {\n console.warn(\n `[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans — API key never resolved, spans lost.`,\n );\n recordSpansDropped(this.pendingSpanCount);\n // Complete pending callbacks so pipeline doesn't hang\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n }\n\n if (this.delegate) {\n return this.delegate.shutdown();\n }\n }\n\n /**\n * Flushes any pending buffered spans (if the API key has resolved) and\n * delegates to the underlying exporter's forceFlush to drain its queue.\n */\n forceFlush(): Promise<void> {\n // Flush pending batches if the key has resolved but they haven't been\n // drained yet (e.g., key resolved between the last export and this flush).\n if (this.getApiKey() !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n }\n\n if (this.delegate?.forceFlush) {\n return this.delegate.forceFlush();\n }\n return Promise.resolve();\n }\n\n /**\n * Enriches a ReadableSpan with all glasstrace.* attributes.\n * Returns a new ReadableSpan wrapper; the original span is not mutated.\n *\n * Only {@link SessionManager.getSessionId} is individually guarded because\n * it calls into crypto and schema validation — a session ID failure should\n * not prevent the rest of enrichment. The other helper calls\n * ({@link deriveErrorCategory}, {@link deriveOrmProvider},\n * {@link classifyFetchTarget}) are pure functions on typed string inputs\n * and rely on the outer catch for any unexpected failure.\n *\n * On total failure, returns the original span unchanged.\n */\n private enrichSpan(span: ReadableSpan): ReadableSpan {\n try {\n const attrs = span.attributes ?? {};\n const name = span.name ?? \"\";\n const extra: Record<string, string | number | boolean> = {};\n\n // glasstrace.trace.type\n extra[ATTR.TRACE_TYPE] = \"server\";\n\n // glasstrace.session.id — calls external code (crypto, schema validation)\n try {\n const sessionId = this.sessionManager.getSessionId(this.getApiKey());\n extra[ATTR.SESSION_ID] = sessionId;\n } catch { /* session ID omitted */ }\n\n // glasstrace.environment\n const env = this.environment ?? process.env.GLASSTRACE_ENV;\n if (env) {\n extra[ATTR.ENVIRONMENT] = env;\n }\n\n // glasstrace.correlation.id\n const existingCid = attrs[\"glasstrace.correlation.id\"];\n if (typeof existingCid === \"string\") {\n extra[ATTR.CORRELATION_ID] = existingCid;\n }\n\n // glasstrace.route\n // OTel's AttributeValue allows non-string shapes (number, boolean,\n // array) on `http.route`. A custom instrumentation could set a\n // non-string there and blow up `.trim()` / `.startsWith()` calls\n // below; guard with typeof so malformed route attributes fall back\n // to `name` (always a string per OTel span contract) instead of\n // disabling all enrichment for the span.\n const rawRoute = attrs[\"http.route\"];\n const route = typeof rawRoute === \"string\" ? rawRoute : name;\n if (route) {\n extra[ATTR.ROUTE] = route;\n }\n\n // glasstrace.trpc.procedure\n // Extract tRPC procedure name from URL path (DISC-1215).\n // Pattern: /api/trpc/{procedure} where procedure is a single path segment\n // that may contain dots (polls.modify) or commas (batched: proc1,proc2).\n const rawUrl = attrs[\"http.url\"] ?? attrs[\"url.full\"] ?? attrs[\"http.target\"];\n const trpcUrl = typeof rawUrl === \"string\" ? rawUrl : undefined;\n if (trpcUrl) {\n const trpcMatch = trpcUrl.match(/\\/api\\/trpc\\/([^/?#]+)/);\n if (trpcMatch) {\n let procedure: string;\n try {\n procedure = decodeURIComponent(trpcMatch[1]);\n } catch {\n procedure = trpcMatch[1];\n }\n if (procedure) {\n extra[ATTR.TRPC_PROCEDURE] = procedure;\n }\n }\n }\n\n // glasstrace.http.method\n const method =\n (attrs[\"http.method\"] as string | undefined) ??\n (attrs[\"http.request.method\"] as string | undefined);\n if (method) {\n extra[ATTR.HTTP_METHOD] = method;\n }\n\n // glasstrace.next.action.detected — DISC-1253.\n // Heuristic: a POST to a page route (not /api/*, not /_next/*) is\n // almost always a Server Action in idiomatic Next.js App Router code.\n // We cannot identify the specific action without extra metadata —\n // DISC-1254 covers that path. Label \"detected\" not \"confirmed\" to\n // leave room for rare false-positive cases (legacy form POSTs,\n // hand-rolled page-route POST handlers).\n //\n // `route` may come from `http.route` (a bare path like \"/login\") or\n // fall back to `span.name` (which Next.js formats as \"POST /login\",\n // sometimes \"middleware POST\", etc.). We normalize to the leading\n // path segment before matching so a span named \"POST /api/auth\"\n // does not slip past the `/api/` guard and get falsely flagged.\n const actionRoute = extractLeadingPath(route);\n if (method === \"POST\" && actionRoute) {\n const isApiRoute = actionRoute === \"/api\" || actionRoute.startsWith(\"/api/\");\n const isInternalRoute = actionRoute.startsWith(\"/_next/\");\n if (!isApiRoute && !isInternalRoute) {\n extra[ATTR.NEXT_ACTION_DETECTED] = true;\n // Developer-facing nudge (once per process): when a Server Action\n // trace is detected but no glasstrace.correlation.id is present,\n // the Glasstrace browser extension is likely absent. Installing it\n // unlocks per-action identification via the Next-Action header\n // (DISC-1254 covers capture).\n if (typeof extra[ATTR.CORRELATION_ID] !== \"string\") {\n maybeShowServerActionNudge();\n }\n }\n }\n\n // glasstrace.http.status_code\n const statusCode =\n (attrs[\"http.status_code\"] as number | undefined) ??\n (attrs[\"http.response.status_code\"] as number | undefined);\n if (statusCode !== undefined) {\n extra[ATTR.HTTP_STATUS_CODE] = statusCode;\n }\n\n // Infer error status when Next.js timing race reports 200 on error spans.\n // Three signals indicate an error span:\n // 1. span.status.code === ERROR (explicit, most reliable)\n // 2. span.events contains an \"exception\" event (recordException fired)\n // 3. span attributes contain exception.type or exception.message\n // The timing race in Next.js dev server (DISC-1134) can cause span\n // export before closeSpanWithError runs, leaving status.code as UNSET.\n // Exception events from recordException may still be present (DISC-1204).\n // Does NOT trigger when status is explicitly OK (handler recovered).\n const isErrorByStatus = span.status?.code === SpanStatusCode.ERROR;\n const isErrorByEvent = hasExceptionEvent(span);\n const isErrorByAttrs = typeof attrs[\"exception.type\"] === \"string\"\n || typeof attrs[\"exception.message\"] === \"string\";\n const statusNotExplicitlyOK = span.status?.code !== SpanStatusCode.OK;\n\n if (this.verbose && method) {\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": status.code=${span.status?.code}, ` +\n `http.status_code=${statusCode}, isErrorByStatus=${isErrorByStatus}, ` +\n `isErrorByEvent=${isErrorByEvent}, isErrorByAttrs=${isErrorByAttrs}`,\n );\n }\n\n if (method && statusNotExplicitlyOK && (isErrorByStatus || isErrorByEvent || isErrorByAttrs)) {\n if (statusCode === undefined || statusCode === 0 || statusCode === 200) {\n const httpErrorType = attrs[\"error.type\"];\n if (typeof httpErrorType === \"string\") {\n const parsed = parseInt(httpErrorType, 10);\n if (!isNaN(parsed) && parsed >= 400 && parsed <= 599) {\n extra[ATTR.HTTP_STATUS_CODE] = parsed;\n } else {\n extra[ATTR.HTTP_STATUS_CODE] = 500;\n }\n } else {\n extra[ATTR.HTTP_STATUS_CODE] = 500;\n }\n\n if (this.verbose) {\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": inferred status_code=${extra[ATTR.HTTP_STATUS_CODE]} ` +\n `(was ${statusCode}), error.type=${attrs[\"error.type\"]}`,\n );\n }\n }\n // If statusCode is already >= 400, leave it alone (correct value)\n }\n\n // glasstrace.http.duration_ms\n if (span.startTime && span.endTime) {\n const [startSec, startNano] = span.startTime;\n const [endSec, endNano] = span.endTime;\n const durationMs =\n (endSec - startSec) * 1000 + (endNano - startNano) / 1_000_000;\n if (durationMs >= 0) {\n extra[ATTR.HTTP_DURATION_MS] = durationMs;\n }\n }\n\n // glasstrace.error.message + glasstrace.error.code + glasstrace.error.category\n // Primary source: span attributes. Fallback: exception event attributes.\n // OTel's recordException() stores exception info in events, not span\n // attributes, so the fallback is needed for most error spans (DISC-1204).\n // Event fallback is gated on statusNotExplicitlyOK to avoid labeling\n // recovered OK spans with error metadata from handled exceptions.\n const eventDetails = statusNotExplicitlyOK\n ? getExceptionEventDetails(span)\n : { type: undefined, message: undefined };\n\n const errorMessage = attrs[\"exception.message\"];\n if (typeof errorMessage === \"string\") {\n extra[ATTR.ERROR_MESSAGE] = errorMessage;\n } else if (eventDetails.message) {\n extra[ATTR.ERROR_MESSAGE] = eventDetails.message;\n }\n\n // Guard against non-string attribute values (OTel attributes can be\n // string | number | boolean | Array) to prevent toLowerCase() throws.\n const errorType = attrs[\"exception.type\"];\n if (typeof errorType === \"string\") {\n extra[ATTR.ERROR_CODE] = errorType;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(errorType);\n } else if (eventDetails.type) {\n extra[ATTR.ERROR_CODE] = eventDetails.type;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(eventDetails.type);\n }\n\n if (this.verbose && (extra[ATTR.ERROR_MESSAGE] || extra[ATTR.ERROR_CODE])) {\n const msgSource = typeof errorMessage === \"string\" ? \"attrs\"\n : eventDetails.message ? \"event\" : \"none\";\n const typeSource = typeof errorType === \"string\" ? \"attrs\"\n : eventDetails.type ? \"event\" : \"none\";\n sdkLog(\"info\",\n `[glasstrace] enrichSpan \"${name}\": error.message source=${msgSource}, ` +\n `error.code source=${typeSource}`,\n );\n }\n\n // glasstrace.error.field\n const errorField = attrs[\"error.field\"];\n if (typeof errorField === \"string\") {\n extra[ATTR.ERROR_FIELD] = errorField;\n }\n\n // glasstrace.error.response_body (DISC-1216 Phase 1 — passthrough)\n // Adapters (e.g., future tRPC handler wrapper) should set error response\n // body data on `glasstrace.internal.response_body` — a Glasstrace-internal\n // attribute that is only promoted to the public namespace when the config\n // flag is enabled. This prevents response body leakage when disabled.\n if (this.getConfig().errorResponseBodies) {\n const responseBody = attrs[\"glasstrace.internal.response_body\"];\n if (typeof responseBody === \"string\") {\n extra[ATTR.ERROR_RESPONSE_BODY] = responseBody.slice(0, 500);\n }\n }\n\n // glasstrace.orm.*\n const spanAny = span as unknown as Record<string, { name?: string } | undefined>;\n const instrumentationName =\n (spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name) ?? \"\";\n const ormProvider = deriveOrmProvider(instrumentationName);\n if (ormProvider) {\n extra[ATTR.ORM_PROVIDER] = ormProvider;\n\n const table = attrs[\"db.sql.table\"];\n const prismaModel = attrs[\"db.prisma.model\"];\n const model = typeof table === \"string\" ? table\n : typeof prismaModel === \"string\" ? prismaModel\n : undefined;\n if (model) {\n extra[ATTR.ORM_MODEL] = model;\n }\n\n const operation = attrs[\"db.operation\"];\n if (typeof operation === \"string\") {\n extra[ATTR.ORM_OPERATION] = operation;\n }\n }\n\n // glasstrace.fetch.target\n const httpUrl = attrs[\"http.url\"];\n const fullUrl = attrs[\"url.full\"];\n const url = typeof httpUrl === \"string\" ? httpUrl\n : typeof fullUrl === \"string\" ? fullUrl\n : undefined;\n if (url && span.kind === SpanKind.CLIENT) {\n extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);\n }\n\n return createEnrichedSpan(span, extra);\n } catch {\n // Return original span unchanged so the export pipeline is never blocked\n return span;\n }\n }\n\n /**\n * Lazily creates the delegate OTLP exporter once the API key is resolved.\n * Recreates the delegate if the key has changed (e.g., after key rotation)\n * so the Authorization header stays current.\n */\n private ensureDelegate(): SpanExporter | null {\n if (!this.createDelegateFn) return null;\n\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) return null;\n\n // Recreate delegate if the key has changed since last creation\n if (this.delegate && this.delegateKey === currentKey) {\n return this.delegate;\n }\n\n // Shut down old delegate if key rotated. Catch errors to prevent\n // unhandled rejections from crashing the process during rotation.\n if (this.delegate) {\n void this.delegate.shutdown?.().catch(() => {});\n }\n\n this.delegate = this.createDelegateFn(this.endpointUrl, {\n Authorization: `Bearer ${currentKey}`,\n });\n this.delegateKey = currentKey;\n return this.delegate;\n }\n\n /**\n * Buffers raw (unenriched) spans while the API key is pending.\n * Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.\n * Re-checks the key after buffering to close the race window where\n * the key resolves between the caller's check and this buffer call.\n */\n private bufferSpans(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n this.pendingBatches.push({ spans, resultCallback });\n this.pendingSpanCount += spans.length;\n\n // Evict oldest batches if over limit\n while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {\n const evicted = this.pendingBatches.shift()!;\n this.pendingSpanCount -= evicted.spans.length;\n recordSpansDropped(evicted.spans.length);\n // Complete callback so pipeline doesn't hang\n evicted.resultCallback({ code: 0 });\n\n if (!this.overflowLogged) {\n this.overflowLogged = true;\n console.warn(\n \"[glasstrace] Pending span buffer overflow — oldest spans evicted. \" +\n \"This usually means the API key is taking too long to resolve.\",\n );\n }\n }\n\n // Re-check: if the key resolved between the caller's check and now,\n // flush immediately to avoid spans stuck in the buffer.\n if (this.getApiKey() !== API_KEY_PENDING) {\n this.flushPending();\n }\n }\n\n /**\n * Flushes all buffered spans through the delegate exporter.\n * Enriches spans at flush time (not buffer time) so that session IDs\n * are computed with the resolved API key instead of the \"pending\" sentinel.\n */\n private flushPending(): void {\n if (this.pendingBatches.length === 0) return;\n\n const exporter = this.ensureDelegate();\n if (!exporter) {\n // No delegate factory — complete callbacks and count as dropped\n let discardedCount = 0;\n for (const batch of this.pendingBatches) {\n discardedCount += batch.spans.length;\n batch.resultCallback({ code: 0 });\n }\n recordSpansDropped(discardedCount);\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n return;\n }\n\n const batches = this.pendingBatches;\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n\n for (const batch of batches) {\n // Enrich at flush time with the now-resolved key\n const enriched = batch.spans.map((span) => this.enrichSpan(span));\n exporter.export(enriched, (result) => {\n if (result.code !== 0) {\n sdkLog(\"warn\", `[glasstrace] Span export failed: ${result.error?.message ?? \"unknown error\"}`);\n }\n batch.resultCallback(result);\n });\n recordSpansExported(enriched.length);\n }\n }\n\n}\n\n/**\n * Creates a ReadableSpan wrapper that inherits all properties from the\n * original span but overrides `attributes` to include additional entries.\n * The original span is not mutated.\n */\nfunction createEnrichedSpan(\n span: ReadableSpan,\n extra: Record<string, string | number | boolean>,\n): ReadableSpan {\n const enrichedAttributes = { ...span.attributes, ...extra };\n return Object.create(span, {\n attributes: {\n value: enrichedAttributes,\n enumerable: true,\n },\n }) as ReadableSpan;\n}\n\n/**\n * Returns true if the span has at least one \"exception\" event.\n * This signals that `span.recordException()` was called, even if\n * `span.setStatus(ERROR)` was not yet applied due to the timing race\n * in Next.js dev server (DISC-1204).\n */\nfunction hasExceptionEvent(span: ReadableSpan): boolean {\n return span.events?.some((e) => e.name === \"exception\") ?? false;\n}\n\n/**\n * Extracts exception.type and exception.message from the first \"exception\"\n * event on the span. Returns undefined values if not found.\n *\n * OTel's `recordException()` stores error details in event attributes, not\n * span attributes. The enrichment code needs this fallback to populate\n * glasstrace.error.message and glasstrace.error.code when the standard\n * span attributes are absent.\n */\nfunction getExceptionEventDetails(span: ReadableSpan): {\n type: string | undefined;\n message: string | undefined;\n} {\n const event = span.events?.find((e) => e.name === \"exception\");\n if (!event?.attributes) {\n return { type: undefined, message: undefined };\n }\n const type = event.attributes[\"exception.type\"];\n const message = event.attributes[\"exception.message\"];\n return {\n type: typeof type === \"string\" ? type : undefined,\n message: typeof message === \"string\" ? message : undefined,\n };\n}\n\n/**\n * Extracts the leading path from a route-or-span-name string so the\n * Server Action heuristic (DISC-1253) can match reliably regardless of\n * whether the value came from `http.route` (bare path, e.g. \"/login\")\n * or from `span.name` (Next.js-formatted, e.g. \"POST /login\" or\n * \"middleware POST /login\").\n *\n * Returns the first `/…`-prefixed token, or `undefined` if no such\n * token is present. Empty input yields `undefined` so callers can use\n * the result as a truthy guard.\n */\nexport function extractLeadingPath(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return undefined;\n\n // Fast path: already a bare path.\n if (trimmed.startsWith(\"/\")) {\n const firstSpace = trimmed.indexOf(\" \");\n return firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace);\n }\n\n // Fallback: scan for the first whitespace-separated token that looks\n // like a path. Handles \"POST /login\", \"middleware POST /login\", etc.\n for (const token of trimmed.split(/\\s+/)) {\n if (token.startsWith(\"/\")) {\n return token;\n }\n }\n\n return undefined;\n}\n\n/**\n * Derives ORM provider from the instrumentation library name.\n */\nexport function deriveOrmProvider(instrumentationName: string): string | null {\n const lower = instrumentationName.toLowerCase();\n if (lower.includes(\"prisma\")) {\n return \"prisma\";\n }\n if (lower.includes(\"drizzle\")) {\n return \"drizzle\";\n }\n return null;\n}\n\n/**\n * Derives error category from error type string.\n */\nexport function deriveErrorCategory(errorType: string): string {\n const lower = errorType.toLowerCase();\n if (lower.includes(\"validation\") || lower.includes(\"zod\")) {\n return \"validation\";\n }\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"fetch\") ||\n lower.includes(\"timeout\")\n ) {\n return \"network\";\n }\n if (lower.includes(\"auth\") || lower.includes(\"unauthorized\") || lower.includes(\"forbidden\")) {\n return \"auth\";\n }\n if (lower.includes(\"notfound\") || lower.includes(\"not_found\")) {\n return \"not-found\";\n }\n return \"internal\";\n}\n","import type { AnonApiKey, SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Checks whether the given Origin header is allowed for CORS access.\n *\n * Allowed origins:\n * - `chrome-extension://*` — any Chrome extension\n * - `moz-extension://*` — any Firefox extension\n * - `safari-web-extension://*` — any Safari extension\n * - Absent origin (same-origin / non-browser request)\n *\n * Replaced wildcard `*` to prevent arbitrary websites from\n * reading the anonymous API key from localhost.\n */\nfunction isAllowedOrigin(origin: string | null): boolean {\n if (origin === null) return true;\n if (origin.startsWith(\"chrome-extension://\")) return true;\n if (origin.startsWith(\"moz-extension://\")) return true;\n if (origin.startsWith(\"safari-web-extension://\")) return true;\n return false;\n}\n\n/**\n * Builds CORS headers for a given request origin.\n * Returns headers with `Access-Control-Allow-Origin` set to the origin\n * if allowed, otherwise omits that header entirely.\n */\nfunction buildCorsHeaders(origin: string | null): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Vary: \"Origin\",\n };\n\n if (origin && isAllowedOrigin(origin)) {\n headers[\"Access-Control-Allow-Origin\"] = origin;\n }\n\n return headers;\n}\n\n/**\n * Claim state returned by the `getClaimState` callback.\n *\n * - `claimed` — `true` when the anonymous key has been linked to an account.\n * - `accountHint` — optional masked identifier (e.g. `\"er***@example.com\"`)\n * for the browser extension to display to the user.\n */\nexport interface ClaimState {\n claimed: boolean;\n accountHint?: string;\n}\n\n/**\n * Creates a request handler for the `/__glasstrace/config` discovery endpoint.\n *\n * The returned handler checks if the request URL path is `/__glasstrace/config`.\n * If not, returns `null` (pass-through). If it matches, returns a `DiscoveryResponse`\n * with the anonymous key and current session ID.\n *\n * When `getClaimState` returns a non-null value with `claimed: true`, the\n * response includes `claimed` and (optionally) `accountHint` so the browser\n * extension can prompt the user to sign in.\n *\n * The triple guard (anonymous + dev + active) is enforced by the caller,\n * not by this module. If the handler is registered, it serves.\n */\nexport function createDiscoveryHandler(\n getAnonKey: () => Promise<AnonApiKey | null>,\n getSessionId: () => SessionId,\n getClaimState?: () => ClaimState | null,\n): (request: Request) => Promise<Response | null> {\n return async (request: Request): Promise<Response | null> => {\n // Check path match\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n\n if (url.pathname !== \"/__glasstrace/config\") {\n return null;\n }\n\n // Restrict CORS to known extension origins instead of wildcard\n const origin = request.headers.get(\"Origin\");\n const corsHeaders = buildCorsHeaders(origin);\n\n // Handle CORS preflight\n if (request.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n ...corsHeaders,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n },\n });\n }\n\n // Only allow GET requests\n if (request.method !== \"GET\") {\n return new Response(\n JSON.stringify({ error: \"method_not_allowed\" }),\n {\n status: 405,\n headers: corsHeaders,\n },\n );\n }\n\n try {\n // Get the anonymous key\n const anonKey = await getAnonKey();\n\n if (anonKey === null) {\n return new Response(\n JSON.stringify({ error: \"not_ready\" }),\n {\n status: 503,\n headers: corsHeaders,\n },\n );\n }\n\n // Get the current session ID\n const sessionId = getSessionId();\n\n // Build response body, conditionally including claim fields\n const responseBody: Record<string, unknown> = { key: anonKey, sessionId };\n const claimState = getClaimState?.();\n if (claimState?.claimed) {\n responseBody.claimed = true;\n if (claimState.accountHint) {\n responseBody.accountHint = claimState.accountHint;\n }\n }\n\n return new Response(\n JSON.stringify(responseBody),\n {\n status: 200,\n headers: corsHeaders,\n },\n );\n } catch {\n return new Response(\n JSON.stringify({ error: \"internal_error\" }),\n {\n status: 500,\n headers: corsHeaders,\n },\n );\n }\n };\n}\n\n// Exported for testing\nexport { isAllowedOrigin, buildCorsHeaders };\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n private _delegate: IOtlpExportDelegate<Internal>;\n constructor(delegate: IOtlpExportDelegate<Internal>) {\n this._delegate = delegate;\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._delegate.export(items, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n timeoutMillis: number;\n concurrencyLimit: number;\n compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n return timeoutMillis;\n }\n throw new Error(\n `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n );\n}\n\nexport function wrapStaticHeadersInFunction(\n headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n if (headers == null) {\n return undefined;\n }\n\n return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n return {\n timeoutMillis: validateTimeoutMillis(\n userProvidedConfiguration.timeoutMillis ??\n fallbackConfiguration.timeoutMillis ??\n defaultConfiguration.timeoutMillis\n ),\n concurrencyLimit:\n userProvidedConfiguration.concurrencyLimit ??\n fallbackConfiguration.concurrencyLimit ??\n defaultConfiguration.concurrencyLimit,\n compression:\n userProvidedConfiguration.compression ??\n fallbackConfiguration.compression ??\n defaultConfiguration.compression,\n };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n return {\n timeoutMillis: 10000,\n concurrencyLimit: 30,\n compression: 'none',\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n pushPromise(promise: Promise<void>): void;\n hasReachedLimit(): boolean;\n awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n private readonly _concurrencyLimit: number;\n private _sendingPromises: Promise<unknown>[] = [];\n\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit: number) {\n this._concurrencyLimit = concurrencyLimit;\n }\n\n public pushPromise(promise: Promise<void>): void {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n public hasReachedLimit(): boolean {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n\n public async awaitAll(): Promise<void> {\n await Promise.all(this._sendingPromises);\n }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n concurrencyLimit: number;\n}): IExportPromiseHandler {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Baggage, BaggageEntryMetadata } from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n if (!entry) return;\n const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n const keyPairPart =\n metadataSeparatorIndex === -1\n ? entry\n : entry.substring(0, metadataSeparatorIndex);\n\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n\n const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n if (!rawKey || !rawValue) return;\n let key: string;\n let value: string;\n try {\n key = decodeURIComponent(rawKey);\n value = decodeURIComponent(rawValue);\n } catch {\n return;\n }\n\n let metadata;\n if (\n metadataSeparatorIndex !== -1 &&\n metadataSeparatorIndex < entry.length - 1\n ) {\n const metadataString = entry.substring(metadataSeparatorIndex + 1);\n metadata = baggageEntryMetadataFromString(metadataString);\n }\n\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (typeof value === 'string' && value.length > 0) {\n value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n\n if (keyPair !== undefined && keyPair.value.length > 0) {\n result[keyPair.key] = keyPair.value;\n }\n });\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n const out: Attributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = (attributes as Record<string, unknown>)[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n const elementType = typeof element;\n\n if (elementType === type) {\n continue;\n }\n\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n );\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n } else if (raw === 'false') {\n return false;\n } else {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n );\n return false;\n }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n response: unknown\n): response is { partialSuccess: never } {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n T,\n>(): IOtlpResponseHandler<T> {\n return {\n handleResponse(response: T) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (\n response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0\n ) {\n return;\n }\n diag.warn(\n 'Received Partial Success response:',\n JSON.stringify(response.partialSuccess)\n );\n },\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { IExporterTransport } from './exporter-transport';\nimport type { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport type { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport type { DiagLogger } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n implements IOtlpExportDelegate<Internal>\n{\n private _diagLogger: DiagLogger;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<Internal, Response>;\n private _responseHandler: IOtlpResponseHandler<Response>;\n private _promiseQueue: IExportPromiseHandler;\n private _timeout: number;\n\n constructor(\n transport: IExporterTransport,\n serializer: ISerializer<Internal, Response>,\n responseHandler: IOtlpResponseHandler<Response>,\n promiseQueue: IExportPromiseHandler,\n timeout: number\n ) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n const serializedRequest = this._serializer.serializeRequest(\n internalRepresentation\n );\n\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n\n this._promiseQueue.pushPromise(\n this._transport.send(serializedRequest, this._timeout).then(\n response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(\n this._serializer.deserializeResponse(response.data)\n );\n } catch (e) {\n this._diagLogger.warn(\n 'Export succeeded but could not deserialize response - is the response specification compliant?',\n e,\n response.data\n );\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n } else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n } else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error:\n response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n } else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n },\n reason =>\n resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })\n )\n );\n }\n\n forceFlush(): Promise<void> {\n return this._promiseQueue.awaitAll();\n }\n\n async shutdown(): Promise<void> {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n components: {\n transport: IExporterTransport;\n serializer: ISerializer<Internal, Response>;\n promiseHandler: IExportPromiseHandler;\n },\n settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n return new OTLPExportDelegate(\n components.transport,\n components.serializer,\n createLoggingPartialSuccessResponseHandler(),\n components.promiseHandler,\n settings.timeout\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport type { Attributes } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\n\nexport function createResource(\n resource: ISdkResource,\n encoder: Encoder\n): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n return result;\n}\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(\n attributes: Attributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n\nexport function toKeyValue(\n key: string,\n value: unknown,\n encoder: Encoder\n): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values: IAnyValue[] = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values: IKeyValue[] = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n\n return {};\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return (\n BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes: Uint8Array): string => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\nimport type {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n encoder: Encoder\n): IExportTraceServiceRequest {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n record.instrumentationScope.version || ''\n }:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans: IResourceSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { ISerializer } from '../../i-serializer';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n const headers: Record<string, string> = {};\n Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n url: string;\n headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n userProvidedHeaders: HeadersFactory | undefined | null,\n fallbackHeaders: HeadersFactory | undefined | null,\n defaultHeaders: HeadersFactory\n): HeadersFactory {\n return async () => {\n const requiredHeaders = {\n ...(await defaultHeaders()),\n };\n const headers = {};\n\n // add fallback ones first\n if (fallbackHeaders != null) {\n Object.assign(headers, await fallbackHeaders());\n }\n\n // override with user-provided ones\n if (userProvidedHeaders != null) {\n Object.assign(\n headers,\n validateAndNormalizeHeaders(await userProvidedHeaders())\n );\n }\n\n // override required ones.\n return Object.assign(headers, requiredHeaders);\n };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n if (url == null) {\n return undefined;\n }\n try {\n // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n const base = globalThis.location?.href;\n return new URL(url, base).href;\n } catch {\n throw new Error(\n `Configuration: Could not parse user-provided export URL: '${url}'`\n );\n }\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n headers: mergeHeaders(\n userProvidedConfiguration.headers,\n fallbackConfiguration.headers,\n defaultConfiguration.headers\n ),\n url:\n validateUserProvidedUrl(userProvidedConfiguration.url) ??\n fallbackConfiguration.url ??\n defaultConfiguration.url,\n };\n}\n\nexport function getHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpHttpConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n headers: async () => requiredHeaders,\n url: 'http://localhost:4318/' + signalResourcePath,\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OtlpHttpConfiguration } from './otlp-http-configuration';\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n} from './otlp-http-configuration';\n\n// NOTE: do not change these imports to be actual imports, otherwise they WILL break `@opentelemetry/instrumentation-http`\nimport type * as http from 'http';\nimport type * as https from 'https';\n\nexport type HttpAgentFactory = (\n protocol: string\n) => http.Agent | https.Agent | Promise<http.Agent> | Promise<https.Agent>;\n\nexport interface OtlpNodeHttpConfiguration extends OtlpHttpConfiguration {\n /**\n * Factory function for creating agents.\n *\n * @remarks\n * Prefer using {@link httpAgentFactoryFromOptions} over manually writing a factory function wherever possible.\n * If using a factory function (`HttpAgentFactory`), **do not import `http.Agent` or `https.Agent`\n * statically at the top of the file**.\n * Instead, use dynamic `import()` or `require()` to load the module. This ensures that the `http` or `https`\n * module is not loaded before `@opentelemetry/instrumentation-http` can instrument it.\n */\n agentFactory: HttpAgentFactory;\n /**\n * User agent header string to be appended to the exporter's value as a prefix.\n * Availablie since v1.49.0 of the spec.\n * Ref: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#user-agent\n */\n userAgent?: string;\n}\n\nexport function httpAgentFactoryFromOptions(\n options: http.AgentOptions | https.AgentOptions\n): HttpAgentFactory {\n return async protocol => {\n const isInsecure = protocol === 'http:';\n const module = isInsecure ? import('http') : import('https');\n const { Agent } = await module;\n\n if (isInsecure) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n const { ca, cert, key, ...insecureOptions } =\n options as https.AgentOptions;\n return new Agent(insecureOptions);\n }\n return new Agent(options);\n };\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpNodeHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpNodeHttpConfiguration>,\n defaultConfiguration: OtlpNodeHttpConfiguration\n): OtlpNodeHttpConfiguration {\n return {\n ...mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n agentFactory:\n userProvidedConfiguration.agentFactory ??\n fallbackConfiguration.agentFactory ??\n defaultConfiguration.agentFactory,\n userAgent: userProvidedConfiguration.userAgent,\n };\n}\n\nexport function getNodeHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpNodeHttpConfiguration {\n return {\n ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport type { ExportResponse } from '../export-response';\nimport {\n isExportHTTPErrorRetryable,\n parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\n\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(\n request: typeof https.request | typeof http.request,\n url: string,\n headers: Record<string, string>,\n compression: 'gzip' | 'none',\n userAgent: string | undefined,\n agent: http.Agent | https.Agent,\n data: Uint8Array,\n timeoutMillis: number\n): Promise<ExportResponse> {\n return new Promise<ExportResponse>(resolve => {\n const parsedUrl = new URL(url);\n\n if (userAgent) {\n headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n } else {\n headers['User-Agent'] = DEFAULT_USER_AGENT;\n }\n\n const options: http.RequestOptions | https.RequestOptions = {\n hostname: parsedUrl.hostname,\n port: parsedUrl.port,\n path: parsedUrl.pathname,\n method: 'POST',\n headers,\n agent,\n };\n\n const req = request(options, (res: http.IncomingMessage) => {\n const responseData: Buffer[] = [];\n res.on('data', chunk => responseData.push(chunk));\n\n res.on('end', () => {\n if (res.statusCode && res.statusCode <= 299) {\n resolve({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n const error = new OTLPExporterError(\n res.statusMessage,\n res.statusCode,\n Buffer.concat(responseData).toString()\n );\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n res.on('error', (error: Error) => {\n // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n // the first call to resolve() will determine the final state.\n if (res.statusCode && res.statusCode <= 299) {\n // If the response is successful but an error occurs while reading the response,\n // we consider it a success since the data has been sent successfully.\n resolve({\n status: 'success',\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n error: error,\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n });\n\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n resolve({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n\n req.on('error', (error: Error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n resolve({\n status: 'retryable',\n error,\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n compressAndSend(req, compression, data, (error: Error) => {\n resolve({\n status: 'failure',\n error,\n });\n });\n });\n}\n\nexport function compressAndSend(\n req: http.ClientRequest,\n compression: 'gzip' | 'none',\n data: Uint8Array,\n onError: (error: Error) => void\n) {\n let dataStream = readableFromUint8Array(data);\n\n if (compression === 'gzip') {\n req.setHeader('Content-Encoding', 'gzip');\n dataStream = dataStream\n .on('error', onError)\n .pipe(zlib.createGzip())\n .on('error', onError);\n }\n\n dataStream.pipe(req).on('error', onError);\n}\n\nfunction readableFromUint8Array(buff: string | Uint8Array): Readable {\n const readable = new Readable();\n readable.push(buff);\n readable.push(null);\n\n return readable;\n}\n\nfunction isHttpTransportNetworkErrorRetryable(error: Error): boolean {\n const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]);\n\n if ('code' in error && typeof error.code === 'string') {\n return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n return (\n statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504\n );\n}\n\nexport function parseRetryAfterToMills(\n retryAfter?: string | undefined | null\n): number | undefined {\n if (retryAfter == null) {\n return undefined;\n }\n\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.214.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type * as https from 'https';\nimport type * as http from 'http';\nimport type { ExportResponse } from '../export-response';\nimport type { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport type { NodeHttpRequestParameters } from './node-http-transport-types';\n\ninterface Utils {\n agent: http.Agent | https.Agent;\n request: typeof http.request | typeof https.request;\n}\n\nclass HttpExporterTransport implements IExporterTransport {\n private _utils: Utils | null = null;\n private _parameters: NodeHttpRequestParameters;\n\n constructor(parameters: NodeHttpRequestParameters) {\n this._parameters = parameters;\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n const { agent, request } = await this._loadUtils();\n const headers = await this._parameters.headers();\n\n return sendWithHttp(\n request,\n this._parameters.url,\n headers,\n this._parameters.compression,\n this._parameters.userAgent,\n agent,\n data,\n timeoutMillis\n );\n }\n\n shutdown() {\n // intentionally left empty, nothing to do.\n }\n\n private async _loadUtils(): Promise<Utils> {\n let utils = this._utils;\n\n if (utils === null) {\n const protocol = new URL(this._parameters.url).protocol;\n const [agent, request] = await Promise.all([\n this._parameters.agentFactory(protocol),\n requestFunctionFactory(protocol),\n ]);\n utils = this._utils = { agent, request };\n }\n\n return utils;\n }\n}\n\nasync function requestFunctionFactory(\n protocol: string\n): Promise<typeof http.request | typeof https.request> {\n const module = protocol === 'http:' ? import('http') : import('https');\n const { request } = await module;\n return request;\n}\n\nexport function createHttpExporterTransport(\n parameters: NodeHttpRequestParameters\n): IExporterTransport {\n return new HttpExporterTransport(parameters);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from './exporter-transport';\nimport type { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n private _transport: IExporterTransport;\n\n constructor(transport: IExporterTransport) {\n this._transport = transport;\n }\n\n private retry(\n data: Uint8Array,\n timeoutMillis: number,\n inMillis: number\n ): Promise<ExportResponse> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(\n Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n 0\n );\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(\n `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n remainingTimeoutMillis\n )}ms, not retrying further.`\n );\n return result;\n }\n\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n\n if (result.status === 'success') {\n diag.verbose(\n `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n );\n } else if (result.status === 'retryable') {\n diag.info(\n `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n );\n } else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n\n return result;\n }\n\n shutdown() {\n return this._transport.shutdown();\n }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n // Underlying transport to wrap.\n transport: IExporterTransport;\n}): IExporterTransport {\n return new RetryingTransport(options.transport);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createOtlpExportDelegate } from './otlp-export-delegate';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nimport type { OtlpNodeHttpConfiguration } from './configuration/otlp-node-http-configuration';\n\nexport function createOtlpHttpExportDelegate<Internal, Response>(\n options: OtlpNodeHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpExportDelegate(\n {\n transport: createRetryingTransport({\n transport: createHttpExporterTransport(options),\n }),\n serializer: serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n },\n { timeout: options.timeoutMillis }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport { diag } from '@opentelemetry/api';\n\nfunction parseAndValidateTimeoutFromEnv(\n timeoutEnvVar: string\n): number | undefined {\n const envTimeout = getNumberFromEnv(timeoutEnvVar);\n if (envTimeout != null) {\n if (Number.isFinite(envTimeout) && envTimeout > 0) {\n return envTimeout;\n }\n diag.warn(\n `Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`\n );\n }\n\n return undefined;\n}\n\nfunction getTimeoutFromEnv(signalIdentifier: string) {\n const specificTimeout = parseAndValidateTimeoutFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`\n );\n const nonSpecificTimeout = parseAndValidateTimeoutFromEnv(\n 'OTEL_EXPORTER_OTLP_TIMEOUT'\n );\n\n return specificTimeout ?? nonSpecificTimeout;\n}\n\nfunction parseAndValidateCompressionFromEnv(\n compressionEnvVar: string\n): 'none' | 'gzip' | undefined {\n const compression = getStringFromEnv(compressionEnvVar)?.trim();\n\n if (compression == null || compression === 'none' || compression === 'gzip') {\n return compression;\n }\n\n diag.warn(\n `Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`\n );\n return undefined;\n}\n\nfunction getCompressionFromEnv(\n signalIdentifier: string\n): 'none' | 'gzip' | undefined {\n const specificCompression = parseAndValidateCompressionFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`\n );\n const nonSpecificCompression = parseAndValidateCompressionFromEnv(\n 'OTEL_EXPORTER_OTLP_COMPRESSION'\n );\n\n return specificCompression ?? nonSpecificCompression;\n}\n\nexport function getSharedConfigurationFromEnvironment(\n signalIdentifier: string\n): Partial<OtlpSharedConfiguration> {\n return {\n timeoutMillis: getTimeoutFromEnv(signalIdentifier),\n compression: getCompressionFromEnv(signalIdentifier),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStringFromEnv, parseKeyPairsIntoRecord } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { getSharedConfigurationFromEnvironment } from './shared-env-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { OtlpNodeHttpConfiguration } from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from './otlp-node-http-configuration';\n\nfunction getStaticHeadersFromEnv(\n signalIdentifier: string\n): Record<string, string> | undefined {\n const signalSpecificRawHeaders = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`\n );\n const nonSignalSpecificRawHeaders = getStringFromEnv(\n 'OTEL_EXPORTER_OTLP_HEADERS'\n );\n\n const signalSpecificHeaders = parseKeyPairsIntoRecord(\n signalSpecificRawHeaders\n );\n const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(\n nonSignalSpecificRawHeaders\n );\n\n if (\n Object.keys(signalSpecificHeaders).length === 0 &&\n Object.keys(nonSignalSpecificHeaders).length === 0\n ) {\n return undefined;\n }\n\n // headers are combined instead of overwritten, with the specific headers taking precedence over\n // the non-specific ones.\n return Object.assign(\n {},\n parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders),\n parseKeyPairsIntoRecord(signalSpecificRawHeaders)\n );\n}\n\nfunction appendRootPathToUrlIfNeeded(url: string): string | undefined {\n try {\n const parsedUrl = new URL(url);\n // This will automatically append '/' if there's no root path.\n return parsedUrl.toString();\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n}\n\nfunction appendResourcePathToUrl(\n url: string,\n path: string\n): string | undefined {\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n\n if (!url.endsWith('/')) {\n url = url + '/';\n }\n url += path;\n\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`\n );\n return undefined;\n }\n\n return url;\n}\n\nfunction getNonSpecificUrlFromEnv(\n signalResourcePath: string\n): string | undefined {\n const envUrl = getStringFromEnv('OTEL_EXPORTER_OTLP_ENDPOINT');\n if (envUrl === undefined) {\n return undefined;\n }\n return appendResourcePathToUrl(envUrl, signalResourcePath);\n}\n\nfunction getSpecificUrlFromEnv(signalIdentifier: string): string | undefined {\n const envUrl = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`\n );\n if (envUrl === undefined) {\n return undefined;\n }\n return appendRootPathToUrlIfNeeded(envUrl);\n}\n\nfunction readFileFromEnv(\n signalSpecificEnvVar: string,\n nonSignalSpecificEnvVar: string,\n warningMessage: string\n): Buffer | undefined {\n const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);\n const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);\n const filePath = signalSpecificPath ?? nonSignalSpecificPath;\n\n if (filePath != null) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), filePath));\n } catch {\n diag.warn(warningMessage);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction getClientCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n 'Failed to read client certificate chain file'\n );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n 'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n 'Failed to read client certificate private key file'\n );\n}\n\nfunction getRootCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CERTIFICATE',\n 'Failed to read root certificate file'\n );\n}\n\n/**\n * Reads and returns configuration from the environment\n *\n * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS)\n * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs)\n */\nexport function getNodeHttpConfigurationFromEnvironment(\n signalIdentifier: string,\n signalResourcePath: string\n): Partial<OtlpNodeHttpConfiguration> {\n return {\n ...getSharedConfigurationFromEnvironment(signalIdentifier),\n url:\n getSpecificUrlFromEnv(signalIdentifier) ??\n getNonSpecificUrlFromEnv(signalResourcePath),\n headers: wrapStaticHeadersInFunction(\n getStaticHeadersFromEnv(signalIdentifier)\n ),\n agentFactory: httpAgentFactoryFromOptions({\n keepAlive: true,\n ca: getRootCertificateFromEnv(signalIdentifier),\n cert: getClientCertificateFromEnv(signalIdentifier),\n key: getClientKeyFromEnv(signalIdentifier),\n }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n if (typeof config.headers === 'function') {\n return config.headers;\n }\n return wrapStaticHeadersInFunction(config.headers);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport type {\n HttpAgentFactory,\n OtlpNodeHttpConfiguration,\n} from './otlp-node-http-configuration';\nimport {\n getNodeHttpConfigurationDefaults,\n mergeOtlpNodeHttpConfigurationWithDefaults,\n} from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from '../index-node-http';\nimport { getNodeHttpConfigurationFromEnvironment } from './otlp-node-http-env-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\nfunction convertLegacyAgentOptions(\n config: OTLPExporterNodeConfigBase\n): HttpAgentFactory | undefined {\n if (typeof config.httpAgentOptions === 'function') {\n return config.httpAgentOptions;\n }\n\n let legacy = config.httpAgentOptions;\n if (config.keepAlive != null) {\n legacy = { keepAlive: config.keepAlive, ...legacy };\n }\n\n if (legacy != null) {\n return httpAgentFactoryFromOptions(legacy);\n } else {\n return undefined;\n }\n}\n\n/**\n * @deprecated this will be removed in 2.0\n * @param config\n * @param signalIdentifier\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyHttpOptions(\n config: OTLPExporterNodeConfigBase,\n signalIdentifier: string,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): OtlpNodeHttpConfiguration {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((config as any).metadata) {\n diag.warn('Metadata cannot be set when using http');\n }\n\n return mergeOtlpNodeHttpConfigurationWithDefaults(\n {\n url: config.url,\n headers: convertLegacyHeaders(config),\n concurrencyLimit: config.concurrencyLimit,\n timeoutMillis: config.timeoutMillis,\n compression: config.compression,\n agentFactory: convertLegacyAgentOptions(config),\n userAgent: config.userAgent,\n },\n getNodeHttpConfigurationFromEnvironment(\n signalIdentifier,\n signalResourcePath\n ),\n getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport {\n convertLegacyHttpOptions,\n createOtlpHttpExportDelegate,\n} from '@opentelemetry/otlp-exporter-base/node-http';\n\n/**\n * Collector Trace Exporter for Node\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBase<ReadableSpan[]>\n implements SpanExporter\n{\n constructor(config: OTLPExporterNodeConfigBase = {}) {\n super(\n createOtlpHttpExportDelegate(\n convertLegacyHttpOptions(config, 'TRACES', 'v1/traces', {\n 'Content-Type': 'application/json',\n }),\n JsonTraceSerializer\n )\n );\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n}\n","/**\n * SDK Lifecycle State Machine\n *\n * Provides a single source of truth for SDK state across three runtime\n * layers: core, auth, and OTel coexistence. (The CLI layer is handled\n * separately via the runtime state file bridge in SDK-026.)\n *\n * The core layer provides a shared typed event emitter that other layers\n * and SDK modules use for cross-layer communication.\n *\n * This module imports only from `./signal-handler.js`, which itself has no\n * imports, so the dependency graph remains acyclic. The logger is still\n * injected via initLifecycle() to avoid coupling to console-capture.\n *\n * @see docs/component-designs/sdk-lifecycle.md\n */\n\nimport { EventEmitter } from \"node:events\";\nimport { getCoexistenceState } from \"./signal-handler.js\";\n\n// ---------------------------------------------------------------------------\n// State Enums\n// ---------------------------------------------------------------------------\n\nexport const CoreState = {\n IDLE: \"IDLE\",\n REGISTERING: \"REGISTERING\",\n KEY_PENDING: \"KEY_PENDING\",\n KEY_RESOLVED: \"KEY_RESOLVED\",\n ACTIVE: \"ACTIVE\",\n ACTIVE_DEGRADED: \"ACTIVE_DEGRADED\",\n SHUTTING_DOWN: \"SHUTTING_DOWN\",\n SHUTDOWN: \"SHUTDOWN\",\n PRODUCTION_DISABLED: \"PRODUCTION_DISABLED\",\n REGISTRATION_FAILED: \"REGISTRATION_FAILED\",\n} as const;\nexport type CoreState = (typeof CoreState)[keyof typeof CoreState];\n\nexport const AuthState = {\n ANONYMOUS: \"ANONYMOUS\",\n AUTHENTICATED: \"AUTHENTICATED\",\n CLAIMING: \"CLAIMING\",\n CLAIMED: \"CLAIMED\",\n} as const;\nexport type AuthState = (typeof AuthState)[keyof typeof AuthState];\n\nexport const OtelState = {\n UNCONFIGURED: \"UNCONFIGURED\",\n CONFIGURING: \"CONFIGURING\",\n OWNS_PROVIDER: \"OWNS_PROVIDER\",\n AUTO_ATTACHED: \"AUTO_ATTACHED\",\n PROCESSOR_PRESENT: \"PROCESSOR_PRESENT\",\n COEXISTENCE_FAILED: \"COEXISTENCE_FAILED\",\n} as const;\nexport type OtelState = (typeof OtelState)[keyof typeof OtelState];\n\n// ---------------------------------------------------------------------------\n// Valid Transitions\n// ---------------------------------------------------------------------------\n\nconst VALID_CORE_TRANSITIONS: Record<CoreState, readonly CoreState[]> = {\n [CoreState.IDLE]: [CoreState.REGISTERING, CoreState.REGISTRATION_FAILED, CoreState.SHUTTING_DOWN],\n [CoreState.REGISTERING]: [\n CoreState.KEY_PENDING,\n CoreState.PRODUCTION_DISABLED,\n CoreState.REGISTRATION_FAILED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.KEY_PENDING]: [\n CoreState.KEY_RESOLVED,\n CoreState.REGISTRATION_FAILED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.KEY_RESOLVED]: [\n CoreState.ACTIVE,\n CoreState.ACTIVE_DEGRADED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.ACTIVE]: [\n CoreState.ACTIVE_DEGRADED,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.ACTIVE_DEGRADED]: [\n CoreState.ACTIVE,\n CoreState.SHUTTING_DOWN,\n ],\n [CoreState.SHUTTING_DOWN]: [CoreState.SHUTDOWN],\n [CoreState.SHUTDOWN]: [],\n [CoreState.PRODUCTION_DISABLED]: [],\n [CoreState.REGISTRATION_FAILED]: [],\n};\n\nconst VALID_AUTH_TRANSITIONS: Record<AuthState, readonly AuthState[]> = {\n [AuthState.ANONYMOUS]: [AuthState.CLAIMING],\n [AuthState.AUTHENTICATED]: [AuthState.CLAIMING],\n [AuthState.CLAIMING]: [AuthState.CLAIMED],\n [AuthState.CLAIMED]: [AuthState.CLAIMING],\n};\n\nconst VALID_OTEL_TRANSITIONS: Record<OtelState, readonly OtelState[]> = {\n [OtelState.UNCONFIGURED]: [OtelState.CONFIGURING],\n [OtelState.CONFIGURING]: [\n OtelState.OWNS_PROVIDER,\n OtelState.AUTO_ATTACHED,\n OtelState.PROCESSOR_PRESENT,\n OtelState.COEXISTENCE_FAILED,\n ],\n [OtelState.OWNS_PROVIDER]: [],\n [OtelState.AUTO_ATTACHED]: [],\n [OtelState.PROCESSOR_PRESENT]: [],\n [OtelState.COEXISTENCE_FAILED]: [],\n};\n\n// ---------------------------------------------------------------------------\n// Event Types\n// ---------------------------------------------------------------------------\n\nexport interface SdkLifecycleEvents {\n \"core:state_changed\": { from: CoreState; to: CoreState };\n \"core:ready\": Record<string, never>;\n \"core:shutdown_started\": Record<string, never>;\n \"core:shutdown_completed\": Record<string, never>;\n\n \"auth:key_resolved\": { key: string; mode: \"anonymous\" | \"dev\" };\n \"auth:claim_started\": { accountId: string };\n \"auth:claim_completed\": { newKey: string; accountId: string };\n\n \"otel:configured\": { state: OtelState; scenario?: string };\n \"otel:injection_succeeded\": { method: string };\n \"otel:injection_failed\": { reason: string };\n \"otel:shutdown_started\": Record<string, never>;\n \"otel:shutdown_completed\": Record<string, never>;\n\n \"health:init_succeeded\": Record<string, never>;\n \"health:init_failed\": { error: string };\n \"health:heartbeat_tick\": Record<string, never>;\n \"health:config_refreshed\": Record<string, never>;\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _coreState: CoreState = CoreState.IDLE;\nlet _authState: AuthState = AuthState.ANONYMOUS;\nlet _otelState: OtelState = OtelState.UNCONFIGURED;\nlet _emitter: EventEmitter = new EventEmitter();\nlet _logger: ((level: \"warn\" | \"info\" | \"error\", message: string) => void) | null = null;\nlet _initialized = false;\nlet _initWarned = false;\nlet _coreReadyEmitted = false;\nlet _authInitialized = false;\nlet _emitting = false;\n\n// ---------------------------------------------------------------------------\n// Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Initialize the lifecycle module. Must be called before any state\n * transitions. Accepts a logger function to avoid importing SDK modules.\n *\n * Calling this twice logs a warning and is ignored.\n */\nexport function initLifecycle(options: {\n logger: (level: \"warn\" | \"info\" | \"error\", message: string) => void;\n}): void {\n if (_initialized) {\n options.logger(\"warn\", \"[glasstrace] initLifecycle() called twice — ignored.\");\n return;\n }\n _logger = options.logger;\n _initialized = true;\n}\n\n// ---------------------------------------------------------------------------\n// State Transitions\n// ---------------------------------------------------------------------------\n\n/** Warn once if lifecycle functions are called before initLifecycle(). */\nfunction warnIfNotInitialized(): void {\n if (!_initialized && !_initWarned) {\n _initWarned = true;\n // Use console.warn directly since _logger is null\n console.warn(\n \"[glasstrace] Lifecycle state changed before initLifecycle() was called. \" +\n \"Logger not available — errors will be silent.\",\n );\n }\n}\n\n/**\n * Transition the core lifecycle state. Invalid transitions are logged\n * and ignored — the state does not change.\n *\n * Guards against reentrant calls: if a listener calls setCoreState()\n * during emission, the inner transition completes first. The outer\n * call's post-transition events (core:ready, shutdown) check the\n * current state before emitting to avoid stale signals.\n */\nexport function setCoreState(to: CoreState): void {\n warnIfNotInitialized();\n\n const from = _coreState;\n if (from === to) return;\n\n const valid = VALID_CORE_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid core state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _coreState = to;\n\n // Guard against reentrant emission: if a listener calls setCoreState(),\n // the inner call will complete (including its own events). The outer call\n // skips its post-transition events to avoid stale/duplicate signals.\n if (_emitting) return;\n\n _emitting = true;\n try {\n emitSafe(\"core:state_changed\", { from, to });\n\n // Check current state (not `to`) in case a listener changed it\n const current = _coreState;\n\n if (!_coreReadyEmitted && (current === CoreState.ACTIVE || current === CoreState.ACTIVE_DEGRADED)) {\n _coreReadyEmitted = true;\n emitSafe(\"core:ready\", {});\n }\n\n if (current === CoreState.SHUTTING_DOWN) {\n emitSafe(\"core:shutdown_started\", {});\n }\n if (current === CoreState.SHUTDOWN) {\n emitSafe(\"core:shutdown_completed\", {});\n }\n } finally {\n _emitting = false;\n }\n}\n\n/**\n * Set the initial auth state. Must be called exactly once during\n * registration, before any auth transitions. This bypasses transition\n * validation because the initial state (ANONYMOUS vs AUTHENTICATED)\n * is determined by configuration, not by a runtime transition.\n *\n * Subsequent calls log a warning and are ignored.\n */\nexport function initAuthState(state: AuthState): void {\n if (_authInitialized) {\n _logger?.(\n \"warn\",\n \"[glasstrace] initAuthState() called after auth state already initialized. Ignored.\",\n );\n return;\n }\n _authInitialized = true;\n _authState = state;\n}\n\n/**\n * Transition the auth lifecycle state. Invalid transitions are logged\n * and ignored.\n */\nexport function setAuthState(to: AuthState): void {\n warnIfNotInitialized();\n\n const from = _authState;\n if (from === to) return;\n\n const valid = VALID_AUTH_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid auth state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _authState = to;\n}\n\n/**\n * Transition the OTel coexistence state. Invalid transitions are logged\n * and ignored.\n */\nexport function setOtelState(to: OtelState): void {\n warnIfNotInitialized();\n\n const from = _otelState;\n if (from === to) return;\n\n const valid = VALID_OTEL_TRANSITIONS[from];\n if (!valid.includes(to)) {\n _logger?.(\n \"warn\",\n `[glasstrace] Invalid OTel state transition: ${from} → ${to}. Ignored.`,\n );\n return;\n }\n\n _otelState = to;\n}\n\n// ---------------------------------------------------------------------------\n// State Queries\n// ---------------------------------------------------------------------------\n\n/** Returns the current core lifecycle state. */\nexport function getCoreState(): CoreState {\n return _coreState;\n}\n\n/** Returns the current auth lifecycle state. */\nexport function getAuthState(): AuthState {\n return _authState;\n}\n\n/** Returns the current OTel coexistence state. */\nexport function getOtelState(): OtelState {\n return _otelState;\n}\n\n/** Returns the full internal state across all layers. */\nexport function getSdkState(): {\n core: CoreState;\n auth: AuthState;\n otel: OtelState;\n} {\n return {\n core: _coreState,\n auth: _authState,\n otel: _otelState,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Event Emitter\n// ---------------------------------------------------------------------------\n\n/**\n * Subscribe to a lifecycle event. The listener is synchronous.\n * Errors in listeners are caught and logged.\n */\nexport function onLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n _emitter.on(event, listener);\n}\n\n/**\n * Emit a typed lifecycle event. Exported so that other SDK modules\n * (auth, OTel, health) can emit their layer-specific events through\n * the shared emitter with type safety.\n */\nexport function emitLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n payload: SdkLifecycleEvents[K],\n): void {\n emitSafe(event, payload);\n}\n\n/**\n * Unsubscribe from a lifecycle event.\n */\nexport function offLifecycleEvent<K extends keyof SdkLifecycleEvents>(\n event: K,\n listener: (payload: SdkLifecycleEvents[K]) => void,\n): void {\n _emitter.off(event, listener);\n}\n\n/**\n * Emit a lifecycle event. Each listener is called individually so that\n * an error in one listener does not prevent subsequent listeners from\n * running. Both synchronous throws and async rejections are caught and\n * logged via the lifecycle logger.\n */\nfunction emitSafe<K extends keyof SdkLifecycleEvents>(\n event: K,\n payload: SdkLifecycleEvents[K],\n): void {\n const listeners = _emitter.listeners(event);\n for (const listener of listeners) {\n try {\n const result = (listener as (p: SdkLifecycleEvents[K]) => unknown)(payload);\n // Catch async listeners that return a rejected promise\n if (result && typeof (result as Promise<unknown>).catch === \"function\") {\n (result as Promise<unknown>).catch((err: unknown) => {\n _logger?.(\n \"error\",\n `[glasstrace] Async error in lifecycle event listener for \"${event}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n }\n } catch (err) {\n _logger?.(\n \"error\",\n `[glasstrace] Error in lifecycle event listener for \"${event}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Readiness API\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true when the SDK is in ACTIVE or ACTIVE_DEGRADED state.\n */\nexport function isReady(): boolean {\n return _coreState === CoreState.ACTIVE || _coreState === CoreState.ACTIVE_DEGRADED;\n}\n\n/**\n * Resolves when the SDK reaches ACTIVE or ACTIVE_DEGRADED.\n * Rejects on PRODUCTION_DISABLED, REGISTRATION_FAILED, or timeout.\n *\n * Checks current state synchronously first — resolves/rejects immediately\n * if the SDK has already reached a terminal or ready state.\n */\nexport function waitForReady(timeoutMs = 30000): Promise<void> {\n // Check current state synchronously\n if (isReady()) {\n return Promise.resolve();\n }\n if (\n _coreState === CoreState.PRODUCTION_DISABLED ||\n _coreState === CoreState.REGISTRATION_FAILED ||\n _coreState === CoreState.SHUTTING_DOWN ||\n _coreState === CoreState.SHUTDOWN\n ) {\n return Promise.reject(new Error(`SDK is in terminal state: ${_coreState}`));\n }\n\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const listener = ({ to }: { from: CoreState; to: CoreState }) => {\n if (settled) return;\n if (to === CoreState.ACTIVE || to === CoreState.ACTIVE_DEGRADED) {\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n resolve();\n } else if (\n to === CoreState.PRODUCTION_DISABLED ||\n to === CoreState.REGISTRATION_FAILED ||\n to === CoreState.SHUTTING_DOWN ||\n to === CoreState.SHUTDOWN\n ) {\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n reject(new Error(`SDK reached terminal state: ${to}`));\n }\n };\n\n onLifecycleEvent(\"core:state_changed\", listener);\n\n if (timeoutMs > 0) {\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n offLifecycleEvent(\"core:state_changed\", listener);\n reject(new Error(`waitForReady timed out after ${timeoutMs}ms (state: ${_coreState})`));\n }, timeoutMs);\n // unref() so this timer doesn't prevent process exit\n if (typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n }\n });\n}\n\n/**\n * Simplified public state query for external consumers.\n * Hides implementation details like coexistence scenarios.\n */\nexport function getStatus(): {\n ready: boolean;\n mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n} {\n let mode: \"anonymous\" | \"authenticated\" | \"claiming\" | \"disabled\";\n if (_coreState === CoreState.PRODUCTION_DISABLED) {\n mode = \"disabled\";\n } else if (_authState === AuthState.CLAIMING || _authState === AuthState.CLAIMED) {\n mode = \"claiming\";\n } else if (_authState === AuthState.AUTHENTICATED) {\n mode = \"authenticated\";\n } else {\n mode = \"anonymous\";\n }\n\n let tracing: \"active\" | \"degraded\" | \"not-configured\" | \"coexistence\";\n if (_otelState === OtelState.COEXISTENCE_FAILED || _otelState === OtelState.UNCONFIGURED || _otelState === OtelState.CONFIGURING) {\n tracing = \"not-configured\";\n } else if (_coreState === CoreState.ACTIVE_DEGRADED) {\n tracing = \"degraded\";\n } else if (_otelState === OtelState.AUTO_ATTACHED || _otelState === OtelState.PROCESSOR_PRESENT) {\n tracing = \"coexistence\";\n } else {\n tracing = \"active\";\n }\n\n return {\n ready: isReady(),\n mode,\n tracing,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shutdown Coordinator\n//\n// IMPORTANT: The shutdown system has two parts that must stay in sync:\n// 1. HOOKS — registered via registerShutdownHook() by each module\n// 2. TRIGGERS — registerSignalHandlers() for signal-based exit, or\n// registerBeforeExitTrigger() for event-loop-drain exit. Both\n// call executeShutdown() which is idempotent.\n//\n// Rules for agents modifying shutdown behavior:\n// - When registering a hook, verify its trigger exists in the same PR.\n// A hook without a trigger is dead code.\n// - When removing a trigger, verify no hooks depend on it.\n// A trigger removal without hook cleanup drops spans on exit.\n// - Scenario A (bare path): register BOTH signal handlers AND\n// beforeExit trigger. Signals cover SIGTERM/SIGINT, beforeExit\n// covers clean event loop drain (all timers unref'd).\n// - Scenario B (coexistence): signal handlers are ALWAYS installed\n// (DISC-1265) but do NOT re-raise (coexistenceState=\"coexisting\").\n// The beforeExit trigger also fires for event-loop-drain exit.\n// The existing provider owns signal re-raise and its own flush.\n// ---------------------------------------------------------------------------\n\nexport interface ShutdownHook {\n name: string;\n priority: number;\n fn: () => Promise<void>;\n}\n\nlet _shutdownHooks: ShutdownHook[] = [];\nlet _signalHandlersRegistered = false;\nlet _signalHandler: ((signal: NodeJS.Signals) => void) | null = null;\nlet _beforeExitRegistered = false;\nlet _beforeExitHandler: (() => void) | null = null;\nlet _shutdownExecuted = false;\n\n/**\n * Register a shutdown hook. Hooks are executed in priority order\n * (lower number = earlier execution) during shutdown.\n */\nexport function registerShutdownHook(hook: ShutdownHook): void {\n _shutdownHooks.push(hook);\n _shutdownHooks.sort((a, b) => a.priority - b.priority);\n}\n\n/**\n * Execute all registered shutdown hooks in priority order.\n * Each hook runs with a timeout. Errors in individual hooks are caught\n * and logged — remaining hooks still execute.\n *\n * Idempotent: calling this multiple times has no effect after the first.\n */\nexport async function executeShutdown(timeoutMs = 5000): Promise<void> {\n if (_shutdownExecuted) return;\n _shutdownExecuted = true;\n\n setCoreState(CoreState.SHUTTING_DOWN);\n\n for (const hook of _shutdownHooks) {\n try {\n // Suppress unhandled rejection on the hook promise if the timeout wins the race.\n const hookPromise = hook.fn();\n hookPromise.catch(() => {});\n\n await Promise.race([\n hookPromise,\n new Promise<void>((_, reject) => {\n const timer = setTimeout(() => reject(new Error(`Shutdown hook \"${hook.name}\" timed out`)), timeoutMs);\n if (typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n }),\n ]);\n } catch (err) {\n _logger?.(\n \"warn\",\n `[glasstrace] Shutdown hook \"${hook.name}\" failed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n setCoreState(CoreState.SHUTDOWN);\n}\n\n/**\n * Register SIGTERM and SIGINT handlers that trigger the shutdown coordinator.\n * Always installed by registerGlasstrace(), regardless of whether another\n * OTel provider exists (DISC-1265). The re-raise decision is deferred to\n * delivery time: the handler checks coexistenceState (set by configureOtel()\n * once its async provider probe completes) and only re-raises when NOT\n * \"coexisting\". In coexistence mode, hooks still run but the existing\n * provider is responsible for re-raising the signal.\n */\nexport function registerSignalHandlers(): void {\n if (_signalHandlersRegistered) return;\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n _signalHandlersRegistered = true;\n\n // Snapshot listener counts BEFORE we install our own handlers. A non-zero\n // count means another party (Sentry, Datadog, the existing provider) already\n // owns SIGTERM/SIGINT and will re-raise when it is done flushing. Zero means\n // nobody else handles the signal — if we don't re-raise, the process hangs.\n // This check is needed because `coexistenceState === \"coexisting\"` only tells\n // us that ANOTHER OTEL PROVIDER exists, not that it installed signal handlers.\n // A bare BasicTracerProvider has no signal handlers, so we must still re-raise.\n const otherSigtermListeners = process.listenerCount(\"SIGTERM\");\n const otherSigintListeners = process.listenerCount(\"SIGINT\");\n\n const handler = (signal: NodeJS.Signals) => {\n void executeShutdown().finally(() => {\n // Remove our handler to avoid re-entry on re-raise.\n if (_signalHandler) {\n process.removeListener(\"SIGTERM\", _signalHandler);\n process.removeListener(\"SIGINT\", _signalHandler);\n }\n // Re-raise the signal to restore default OS behavior UNLESS we are in\n // coexistence mode AND the other provider had its own signal handlers at\n // registration time. When both conditions hold, that provider owns signal\n // re-raise and will terminate the process on its own schedule; re-raising\n // here would race against its async flush and could kill the process\n // before buffered spans are delivered.\n //\n // When coexisting but NO pre-existing signal listeners were detected, we\n // must still re-raise — the other provider (e.g. a bare BasicTracerProvider)\n // has no signal ownership, so OS default termination will not happen\n // otherwise and the process would hang indefinitely.\n //\n // During the async-window (\"unknown\"), re-raise is the safe default because\n // it preserves standard process termination semantics when we have no\n // information about provider ownership.\n const otherListeners = signal === \"SIGTERM\" ? otherSigtermListeners : otherSigintListeners;\n const otherProviderOwnsSignal = getCoexistenceState() === \"coexisting\" && otherListeners > 0;\n if (!otherProviderOwnsSignal) {\n process.kill(process.pid, signal);\n }\n });\n };\n\n _signalHandler = handler;\n process.once(\"SIGTERM\", handler);\n process.once(\"SIGINT\", handler);\n}\n\n/**\n * Register a beforeExit handler that triggers the shutdown coordinator.\n * beforeExit fires when the event loop drains (not on signals).\n *\n * For Scenario B (coexistence): Glasstrace installs signal handlers (DISC-1265)\n * but does not re-raise — the existing provider owns signal re-raise. This\n * beforeExit trigger covers the edge case where the process exits without\n * signals (event loop drains naturally).\n *\n * Both signal handlers and beforeExit triggers call the same executeShutdown(),\n * which is idempotent — if signals already ran shutdown, beforeExit is a no-op.\n */\nexport function registerBeforeExitTrigger(): void {\n if (_beforeExitRegistered) return;\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") return;\n\n _beforeExitRegistered = true;\n\n const handler = () => {\n void executeShutdown();\n };\n\n _beforeExitHandler = handler;\n process.once(\"beforeExit\", handler);\n}\n\n// ---------------------------------------------------------------------------\n// Testing\n// ---------------------------------------------------------------------------\n\n/**\n * Reset all lifecycle state to initial values. For testing only.\n * Removes all event listeners, resets all state enums, and clears\n * the initialized flag.\n */\nexport function resetLifecycleForTesting(): void {\n _coreState = CoreState.IDLE;\n _authState = AuthState.ANONYMOUS;\n _otelState = OtelState.UNCONFIGURED;\n _emitter.removeAllListeners();\n _emitter = new EventEmitter();\n _logger = null;\n _initialized = false;\n _initWarned = false;\n _coreReadyEmitted = false;\n _authInitialized = false;\n _emitting = false;\n _shutdownHooks = [];\n _shutdownExecuted = false;\n if (_signalHandler && typeof process !== \"undefined\") {\n process.removeListener(\"SIGTERM\", _signalHandler);\n process.removeListener(\"SIGINT\", _signalHandler);\n }\n _signalHandler = null;\n _signalHandlersRegistered = false;\n if (_beforeExitHandler && typeof process !== \"undefined\") {\n process.removeListener(\"beforeExit\", _beforeExitHandler);\n }\n _beforeExitHandler = null;\n _beforeExitRegistered = false;\n}\n","/**\n * Coexistence state for the signal handler.\n *\n * Set by configureOtel() once the async provider probe completes:\n * - \"sole-owner\" — Glasstrace owns the OTel provider (Scenarios A / E).\n * The signal handler re-raises after draining hooks.\n * - \"coexisting\" — Another provider exists (Scenario B / C / F).\n * The signal handler drains our hooks but does NOT\n * re-raise, so the existing provider's shutdown can\n * complete at its own pace.\n * - \"unknown\" — The async probe has not completed yet (startup window).\n * Treated the same as \"sole-owner\" — re-raise is the\n * safe default because it preserves the process's default\n * signal semantics when we have no information.\n */\ntype CoexistenceState = \"unknown\" | \"sole-owner\" | \"coexisting\";\n\nlet coexistenceState: CoexistenceState = \"unknown\";\n\n/**\n * Called by configureOtel() once the async provider probe completes.\n * \"sole-owner\" when Glasstrace owns the provider; \"coexisting\" otherwise.\n */\nexport function setCoexistenceState(s: CoexistenceState): void {\n coexistenceState = s;\n}\n\n/**\n * Returns the current coexistence state.\n * \"unknown\" until configureOtel() completes its async provider probe.\n */\nexport function getCoexistenceState(): CoexistenceState {\n return coexistenceState;\n}\n\n/**\n * Resets coexistence state to \"unknown\". For testing only.\n */\nexport function _resetCoexistenceStateForTesting(): void {\n coexistenceState = \"unknown\";\n}\n","/**\n * OTel Coexistence Public API\n *\n * Provides createGlasstraceSpanProcessor() for developers who want to\n * manually integrate Glasstrace with their existing OTel provider\n * (e.g., Sentry's openTelemetrySpanProcessors config option).\n *\n * Also provides the auto-attach path (tryAutoAttachGlasstraceProcessor)\n * that configureOtel() uses when it detects a pre-registered provider\n * at runtime (Next.js 16 production, Sentry, Datadog, New Relic). Both\n * entry points reuse the same span-processor factory so the manual and\n * automatic paths stay in lockstep.\n *\n * Design: sdk-otel-coexistence.md Sections 3, 4, 5, 6\n */\n\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport type * as otelApi from \"@opentelemetry/api\";\nimport type { GlasstraceOptions } from \"@glasstrace/protocol\";\nimport { GlasstraceExporter } from \"./enriching-exporter.js\";\nimport { getResolvedApiKey, registerExporterForKeyNotification } from \"./otel-config.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { getSessionManager } from \"./register.js\";\nimport { resolveConfig } from \"./env-detection.js\";\nimport { getOtelState, OtelState } from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\n\n/** Branded symbol used to identify Glasstrace's exporter across bundled copies. */\nconst GLASSTRACE_EXPORTER_BRAND = Symbol.for(\"glasstrace.exporter\");\n\n/**\n * Creates a Glasstrace span processor for manual integration with an\n * existing OTel provider.\n *\n * Use this when another tool (e.g., Sentry) owns the OTel provider and\n * you want to add Glasstrace to their processor list:\n *\n * @example\n * ```ts\n * import * as Sentry from \"@sentry/nextjs\";\n * import { createGlasstraceSpanProcessor } from \"@glasstrace/sdk\";\n *\n * Sentry.init({\n * dsn: \"...\",\n * openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\n * });\n * ```\n *\n * **Important:** `registerGlasstrace()` is still required even when using\n * this function. The processor handles span transport (enrichment and\n * export). `registerGlasstrace()` handles everything else: init calls,\n * config sync, session management, anonymous key generation, discovery\n * endpoint, and health reporting.\n *\n * @param options - Optional SDK configuration. If omitted, uses the same\n * config as registerGlasstrace() (environment variables).\n * @returns A BatchSpanProcessor wrapping a GlasstraceExporter with the\n * branded Symbol.for('glasstrace.exporter') for coexistence detection.\n */\nexport function createGlasstraceSpanProcessor(\n options?: GlasstraceOptions,\n): SpanProcessor {\n const config = resolveConfig(options);\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n const exporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager: getSessionManager(),\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n // Propagate verbose so exporter-level enrichment and export logs\n // stay observable whether the processor is built automatically by\n // the coexistence path or wired manually by the developer.\n verbose: config.verbose,\n });\n\n // Register for key-resolution notification so buffered spans flush\n // immediately when the key resolves (not waiting for BSP timer tick).\n registerExporterForKeyNotification(exporter);\n\n return new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: 1000,\n });\n}\n\n/**\n * Result returned by {@link tryAutoAttachGlasstraceProcessor}.\n *\n * - `{ method, processor }` — a Glasstrace span processor was successfully\n * injected into the existing provider's processor list. The caller MUST\n * retain the returned processor so it can be flushed on shutdown.\n * - `\"already_present\"` — a Glasstrace-branded processor was already in\n * the provider's list (e.g., the developer already registered one via\n * `createGlasstraceSpanProcessor()`). No additional processor was added.\n * - `null` — injection was not possible (provider internals inaccessible\n * or `addSpanProcessor` threw). The caller should emit guidance.\n */\nexport type AutoAttachResult =\n | { method: \"v1_public\" | \"v2_private\"; processor: SpanProcessor }\n | \"already_present\"\n | null;\n\n/**\n * Checks whether a Glasstrace-branded span processor is already present\n * in the existing provider's processor list.\n *\n * Uses the branded symbol {@link GLASSTRACE_EXPORTER_BRAND} so detection\n * works across bundled copies of `@glasstrace/sdk` (hoisted vs. nested\n * `node_modules`). `Symbol.for()` uses a global registry, so every copy\n * resolves to the same symbol.\n *\n * Fully defensive — any error or missing internal structure returns\n * `false` and lets the caller fall through to injection or guidance.\n */\nexport function isGlasstraceProcessorPresent(\n tracerProvider: otelApi.TracerProvider,\n): boolean {\n try {\n const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n const delegate = typeof proxy.getDelegate === \"function\"\n ? proxy.getDelegate()\n : tracerProvider;\n\n // Path 1: v2 internal (_activeSpanProcessor._spanProcessors)\n const v2 = delegate as unknown as {\n _activeSpanProcessor?: {\n _spanProcessors?: Array<{ _exporter?: unknown }>;\n };\n };\n const v2Processors = v2._activeSpanProcessor?._spanProcessors;\n if (Array.isArray(v2Processors) && hasBrandedProcessor(v2Processors)) {\n return true;\n }\n\n // Path 2: v1 getActiveSpanProcessor()\n const v1 = delegate as unknown as {\n getActiveSpanProcessor?: () => { _spanProcessors?: Array<{ _exporter?: unknown }> };\n };\n if (typeof v1.getActiveSpanProcessor === \"function\") {\n const active = v1.getActiveSpanProcessor();\n const processors = active?._spanProcessors;\n if (Array.isArray(processors) && hasBrandedProcessor(processors)) {\n return true;\n }\n }\n\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Attempts to inject a Glasstrace span processor into an existing\n * provider's processor pipeline.\n *\n * Tiered approach:\n * 1. Feature-detect `addSpanProcessor` (OTel v1 public API) → call it\n * 2. Feature-detect `_activeSpanProcessor._spanProcessors` (OTel v2\n * internal) → push the processor\n *\n * The processor is constructed via {@link createGlasstraceSpanProcessor}\n * so the auto-attach path and the manual integration path share identical\n * configuration (including the branded exporter for\n * {@link isGlasstraceProcessorPresent} detection and key-notification\n * registration).\n *\n * **Idempotence:** {@link isGlasstraceProcessorPresent} is consulted\n * before construction; if a Glasstrace-branded processor is already\n * attached, this function returns `\"already_present\"` without creating\n * a second exporter.\n *\n * **Defensive:** all errors are swallowed and return `null`. The SDK\n * falls back to emitting guidance rather than crashing.\n *\n * @param tracerProvider - The existing global provider returned by\n * `otelApi.trace.getTracerProvider()`.\n * @param options - Optional SDK configuration passed through to\n * `createGlasstraceSpanProcessor()`.\n * @returns See {@link AutoAttachResult}.\n */\nexport function tryAutoAttachGlasstraceProcessor(\n tracerProvider: otelApi.TracerProvider,\n options?: GlasstraceOptions,\n): AutoAttachResult {\n try {\n // Short-circuit: if a Glasstrace-branded processor is already present,\n // never create a second exporter. Covers the duplicate\n // registerGlasstrace() case (idempotence) and the B-clean scenario\n // where the user wired createGlasstraceSpanProcessor() into their\n // provider config manually.\n if (isGlasstraceProcessorPresent(tracerProvider)) {\n return \"already_present\";\n }\n\n // Unwrap ProxyTracerProvider to reach the concrete delegate.\n const proxy = tracerProvider as unknown as { getDelegate?: () => unknown };\n const delegate = typeof proxy.getDelegate === \"function\"\n ? proxy.getDelegate()\n : tracerProvider;\n\n // Attempt 1: OTel v1 public API (addSpanProcessor).\n const withAdd = delegate as unknown as {\n addSpanProcessor?: (p: SpanProcessor) => void;\n };\n if (typeof withAdd.addSpanProcessor === \"function\") {\n const processor = createGlasstraceSpanProcessor(options);\n withAdd.addSpanProcessor(processor);\n return { method: \"v1_public\", processor };\n }\n\n // Attempt 2: OTel v2 internals (_activeSpanProcessor._spanProcessors).\n // Accessing a private field is justified in the design doc\n // (sdk-otel-coexistence.md Section 4). Same pattern Sentry uses.\n const v2 = delegate as unknown as {\n _activeSpanProcessor?: { _spanProcessors?: unknown[] };\n };\n const multiProcessor = v2._activeSpanProcessor;\n if (!multiProcessor || !Array.isArray(multiProcessor._spanProcessors)) {\n return null;\n }\n\n const processor = createGlasstraceSpanProcessor(options);\n multiProcessor._spanProcessors.push(processor);\n return { method: \"v2_private\", processor };\n } catch {\n return null;\n }\n}\n\n/**\n * Emits a nudge message guiding the developer toward the clean\n * createGlasstraceSpanProcessor() integration path.\n *\n * Called by configureOtel() when auto-attach succeeds (Scenarios B-auto, D1, D2).\n * NOT called when the processor is already present (Scenario B-clean).\n */\nexport function emitNudgeMessage(): void {\n const isSentry = detectSentry();\n\n if (isSentry) {\n sdkLog(\"info\",\n `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n `For a cleaner setup, add Glasstrace to your Sentry config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` Sentry.init({\\n` +\n ` dsn: '...',\\n` +\n ` openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n ` });\\n\\n` +\n `This message will not appear once Glasstrace is added to your provider config.`,\n );\n } else {\n sdkLog(\"info\",\n `[glasstrace] Detected existing OTel provider — auto-attached Glasstrace span processor.\\n` +\n `For a cleaner setup, add Glasstrace to your provider config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` const provider = new BasicTracerProvider({\\n` +\n ` spanProcessors: [\\n` +\n ` // ... your existing processors,\\n` +\n ` createGlasstraceSpanProcessor(),\\n` +\n ` ],\\n` +\n ` });\\n\\n` +\n `This message will not appear once Glasstrace is added to your provider config.`,\n );\n }\n}\n\n/**\n * Emits a guidance message when auto-attach fails (Scenarios C, F).\n */\nexport function emitGuidanceMessage(): void {\n const isSentry = detectSentry();\n\n if (isSentry) {\n sdkLog(\"warn\",\n `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n `could not auto-attach its span processor.\\n` +\n `Add Glasstrace to your Sentry config:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` Sentry.init({\\n` +\n ` dsn: '...',\\n` +\n ` openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],\\n` +\n ` });`,\n );\n } else {\n sdkLog(\"warn\",\n `[glasstrace] An existing OTel TracerProvider is registered but Glasstrace ` +\n `could not auto-attach its span processor.\\n` +\n `Add Glasstrace to your provider configuration:\\n\\n` +\n ` import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';\\n\\n` +\n ` const provider = new BasicTracerProvider({\\n` +\n ` spanProcessors: [\\n` +\n ` // ... your existing processors,\\n` +\n ` createGlasstraceSpanProcessor(),\\n` +\n ` ],\\n` +\n ` });`,\n );\n }\n}\n\n/**\n * Returns true if the nudge message should be shown.\n * Only show when auto-attach was used (not when the user already\n * configured the processor manually).\n */\nexport function shouldShowNudge(): boolean {\n return getOtelState() === OtelState.AUTO_ATTACHED;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n/**\n * Scans a processor list for one whose exporter carries the Glasstrace\n * brand symbol. Defensive — missing fields or non-object exporters return\n * `false`.\n */\nfunction hasBrandedProcessor(\n processors: Array<{ _exporter?: unknown }>,\n): boolean {\n return processors.some((p) => {\n const exporter = p._exporter as Record<symbol, unknown> | undefined;\n return exporter?.[GLASSTRACE_EXPORTER_BRAND] === true;\n });\n}\n\nfunction detectSentry(): boolean {\n try {\n // Check if @sentry/node or @sentry/nextjs is installed\n // Use require.resolve which checks module resolution without importing\n require.resolve(\"@sentry/node\");\n return true;\n } catch {\n try {\n require.resolve(\"@sentry/nextjs\");\n return true;\n } catch {\n return false;\n }\n }\n}\n","import type { ResolvedConfig } from \"./env-detection.js\";\nimport type { SessionManager } from \"./session.js\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { BasicTracerProvider, BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport type { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GlasstraceExporter, API_KEY_PENDING } from \"./enriching-exporter.js\";\nimport { getActiveConfig } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { setOtelState, OtelState, getCoreState, CoreState, setCoreState, emitLifecycleEvent, registerShutdownHook, registerBeforeExitTrigger } from \"./lifecycle.js\";\nimport {\n emitNudgeMessage,\n emitGuidanceMessage,\n tryAutoAttachGlasstraceProcessor,\n} from \"./coexistence.js\";\nimport { setCoexistenceState, _resetCoexistenceStateForTesting } from \"./signal-handler.js\";\n\n/** Module-level resolved API key, updated when the anon key resolves. */\nlet _resolvedApiKey: string = API_KEY_PENDING;\n\n/** Module-level reference to the active exporter for key-resolution notification. */\nlet _activeExporter: GlasstraceExporter | null = null;\n\n/** Additional exporters that need key-resolution notification (from createGlasstraceSpanProcessor). */\nconst _additionalExporters: GlasstraceExporter[] = [];\n\n/** Injected processor in coexistence mode, tracked for flush on exit. */\nlet _injectedProcessor: SpanProcessor | null = null;\n\n/**\n * Sets the resolved API key for OTel export authentication.\n * Called once the anonymous key or dev key is available.\n * @param key - The resolved API key (anonymous or developer).\n */\nexport function setResolvedApiKey(key: string): void {\n _resolvedApiKey = key;\n}\n\n/**\n * Returns the current resolved API key.\n * Returns the {@link API_KEY_PENDING} sentinel if the key has not yet resolved.\n */\nexport function getResolvedApiKey(): string {\n return _resolvedApiKey;\n}\n\n/**\n * Notifies the active exporter that the API key has transitioned from\n * \"pending\" to a resolved value. This triggers flushing of any buffered spans.\n */\nexport function notifyApiKeyResolved(): void {\n _activeExporter?.notifyKeyResolved();\n for (const exporter of _additionalExporters) {\n exporter.notifyKeyResolved();\n }\n}\n\n/**\n * Register an additional exporter for key-resolution notification.\n * Used by createGlasstraceSpanProcessor() so its exporter gets notified\n * when the API key resolves (flushing buffered spans immediately rather\n * than waiting for the next BSP timer tick).\n */\nexport function registerExporterForKeyNotification(exporter: GlasstraceExporter): void {\n _additionalExporters.push(exporter);\n}\n\n/**\n * Resets OTel configuration state to initial values. For testing only.\n */\nexport function resetOtelConfigForTesting(): void {\n _resolvedApiKey = API_KEY_PENDING;\n _activeExporter = null;\n _injectedProcessor = null;\n _additionalExporters.length = 0;\n // Signal and beforeExit handler cleanup is handled by resetLifecycleForTesting()\n // via the shutdown coordinator.\n // Reset coexistence state here as well so that test suites that call\n // resetOtelConfigForTesting() without _resetRegistrationForTesting() do\n // not leak coexistenceState (\"coexisting\" / \"sole-owner\") between tests.\n _resetCoexistenceStateForTesting();\n}\n\n/**\n * Dynamically imports an optional peer dependency at runtime.\n *\n * Uses `Function()` constructor to build the `import()` expression so that\n * bundlers (webpack, esbuild, turbopack) do not attempt to resolve the module\n * at compile time. This is intentional -- the SDK's peer dependencies are\n * optional, and static analysis would cause missing-module build errors for\n * users who have not installed them.\n *\n * **CSP note:** The `Function()` constructor is semantically equivalent to\n * `eval()` and will trigger Content Security Policy violations in environments\n * that disallow `unsafe-eval`. If your CSP blocks this, install the OTel peer\n * dependencies explicitly so they resolve via normal `import` statements, or\n * use the `@vercel/otel` path which does not rely on `tryImport` for its own\n * module.\n *\n * @param moduleId - The npm package name to import (e.g. \"@vercel/otel\").\n * @returns The module namespace object, or `null` if the module is not installed.\n */\nasync function tryImport(moduleId: string): Promise<Record<string, unknown> | null> {\n try {\n return await (Function(\"id\", \"return import(id)\")(moduleId) as Promise<Record<string, unknown>>);\n } catch {\n return null;\n }\n}\n\n/**\n * Configures OpenTelemetry with the GlasstraceExporter.\n *\n * Detection flow (per sdk-otel-coexistence.md v8+):\n * 1. Yield one tick (let synchronous Sentry.init() complete)\n * 2. Probe for existing provider\n * 3. If provider exists → shared coexistence path via\n * {@link tryAutoAttachGlasstraceProcessor} (resolves DISC-493 Issues 2\n * and 4 — Next.js 16 production pre-registration and Sentry hoisting)\n * 4. If no provider → registration path (Vercel or bare)\n */\nexport async function configureOtel(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n setOtelState(OtelState.CONFIGURING);\n\n // Step 1: Yield one tick to let synchronous Sentry.init() (or other tools)\n // complete before probing for an existing provider (DISC-1202).\n await new Promise<void>((resolve) => {\n if (typeof setImmediate === \"function\") {\n setImmediate(resolve);\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n // Step 2: Probe for an existing OTel provider BEFORE the Vercel/bare split.\n // This unified detection ensures coexistence works regardless of whether\n // @vercel/otel is installed (sdk-otel-coexistence.md Section 2.4).\n const existingProvider = otelApi.trace.getTracerProvider();\n const probeTracer = existingProvider.getTracer(\"glasstrace-probe\");\n const anotherProviderRegistered = probeTracer.constructor.name !== \"ProxyTracer\";\n\n // Step 3: If another provider exists → shared coexistence path.\n // This is the DISC-493 Issues 2 and 4 fix: instead of silently giving up\n // when a Next.js 16 production build or a Sentry import has already\n // registered a provider, auto-attach our span processor onto it.\n if (anotherProviderRegistered) {\n // Inform the signal handler that it should NOT re-raise — the existing\n // provider owns signal-based shutdown (DISC-1265).\n setCoexistenceState(\"coexisting\");\n await runCoexistencePath(existingProvider, config);\n return;\n }\n\n // Step 4: No existing provider → registration path.\n // Inform the signal handler that Glasstrace owns the provider and should\n // re-raise after draining its hooks (DISC-1265).\n setCoexistenceState(\"sole-owner\");\n await runRegistrationPath(config, sessionManager);\n}\n\n/**\n * Shared coexistence path for DISC-493 Issues 2 and 4.\n *\n * Used whenever `configureOtel()` detects a pre-registered OTel provider.\n * Delegates processor construction to {@link tryAutoAttachGlasstraceProcessor}\n * which reuses the `createGlasstraceSpanProcessor()` public primitive, so\n * the auto-attach path and the manual integration path stay in lockstep.\n *\n * Idempotence: if a Glasstrace-branded processor is already attached (from\n * a prior `registerGlasstrace()` call or a manual `createGlasstraceSpanProcessor()`\n * wiring), the auto-attach path returns `\"already_present\"` and no second\n * processor is created.\n */\nasync function runCoexistencePath(\n existingProvider: ReturnType<typeof otelApi.trace.getTracerProvider>,\n config: ResolvedConfig,\n): Promise<void> {\n // Attempt to auto-attach via the shared primitive.\n //\n // tryAutoAttachGlasstraceProcessor() performs its own \"already present\"\n // check against the branded Symbol BEFORE constructing an exporter, so\n // idempotent registration does not create a wasted exporter instance.\n // It also reuses createGlasstraceSpanProcessor() for construction, so\n // the processor wiring (branded exporter, key-notification registration,\n // BSP flush interval) matches the documented manual path exactly.\n //\n // Pass through the subset of resolved config that `GlasstraceOptions`\n // accepts. `environment` is not in `GlasstraceOptions` (it's derived\n // from env vars inside `resolveConfig`), so the primitive picks it up\n // from the same environment variables `configureOtel()` sees.\n const result = tryAutoAttachGlasstraceProcessor(existingProvider, {\n endpoint: config.endpoint,\n verbose: config.verbose,\n });\n\n if (result === \"already_present\") {\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Existing provider detected — Glasstrace processor already present.\");\n }\n setOtelState(OtelState.PROCESSOR_PRESENT);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.PROCESSOR_PRESENT, scenario: \"B-clean\" });\n return;\n }\n\n if (result !== null) {\n // Success: processor was attached. Retain a reference for the\n // coexistence flush hook (Section 7.2) so beforeExit drains buffered\n // spans even if the existing provider's shutdown does not propagate.\n _injectedProcessor = result.processor;\n\n if (config.verbose) {\n sdkLog(\n \"info\",\n \"[glasstrace] Existing provider detected — auto-attached Glasstrace span processor.\",\n );\n }\n\n // Register coexistence flush hook via the lifecycle coordinator, and\n // wire the beforeExit trigger so the coordinator runs on event loop drain.\n // The existing provider handles signal-based shutdown (its MultiSpanProcessor\n // propagates shutdown() to our injected processor). The beforeExit trigger\n // covers the edge case where the process exits without signals. Both\n // triggers (signals and beforeExit) call executeShutdown() which is\n // idempotent — if one already ran, the other is a no-op.\n registerShutdownHook({\n name: \"coexistence-flush\",\n priority: 5,\n fn: async () => {\n if (_injectedProcessor) {\n await _injectedProcessor.forceFlush();\n }\n },\n });\n registerBeforeExitTrigger();\n\n const scenario = result.method === \"v1_public\" ? \"D1\" : \"B-auto\";\n setOtelState(OtelState.AUTO_ATTACHED);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.AUTO_ATTACHED, scenario });\n emitLifecycleEvent(\"otel:injection_succeeded\", { method: result.method });\n emitNudgeMessage();\n return;\n }\n\n // Injection failed (Scenario C/F) — emit guidance.\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Existing provider detected — could not auto-attach.\");\n }\n emitGuidanceMessage();\n setOtelState(OtelState.COEXISTENCE_FAILED);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.COEXISTENCE_FAILED, scenario: \"C/F\" });\n emitLifecycleEvent(\"otel:injection_failed\", { reason: \"provider internals inaccessible\" });\n // Cross-layer effect: trigger ACTIVE_DEGRADED if core state permits it\n // (per DISC-1247, KEY_PENDING → ACTIVE_DEGRADED is not valid, so we guard).\n const coreState = getCoreState();\n if (coreState === CoreState.ACTIVE || coreState === CoreState.KEY_RESOLVED) {\n setCoreState(CoreState.ACTIVE_DEGRADED);\n }\n}\n\n/**\n * Registration path when no existing OTel provider is detected.\n *\n * Tries `@vercel/otel` first (Scenario E). Falls back to constructing a\n * bare `BasicTracerProvider` (Scenario A). In both sub-scenarios,\n * Glasstrace owns the provider and installs its own shutdown hooks.\n */\nasync function runRegistrationPath(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n // Build OTLP exporter configuration\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n // OTLP exporter factory — always available since OTel is bundled.\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n // Create the GlasstraceExporter that enriches + buffers + delegates\n const glasstraceExporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager,\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n verbose: config.verbose,\n });\n _activeExporter = glasstraceExporter;\n\n // Try @vercel/otel first (Scenario E)\n const vercelOtel = await tryImport(\"@vercel/otel\");\n if (vercelOtel && typeof vercelOtel.registerOTel === \"function\") {\n const otelConfig: Record<string, unknown> = {\n serviceName: \"glasstrace-sdk\",\n traceExporter: glasstraceExporter,\n };\n\n // Try @prisma/instrumentation\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown) | undefined;\n if (PrismaInstrumentation) {\n otelConfig.instrumentations = [new PrismaInstrumentation()];\n }\n }\n\n (vercelOtel.registerOTel as (opts: Record<string, unknown>) => void)(otelConfig);\n\n // Register a shutdown hook so buffered spans are flushed on SIGTERM.\n // @vercel/otel does not install its own signal or beforeExit handlers\n // (verified empirically in DISC-1250 / vercel-shutdown.test.ts): it\n // constructs an internal Sdk instance and discards the reference, making\n // provider.shutdown() unreachable via any ambient mechanism. Without this\n // hook, spans buffered in the BatchSpanProcessor are lost when the Vercel\n // runtime delivers SIGTERM to the function worker (DISC-1263).\n //\n // Signal handlers are registered earlier in registerGlasstrace() via\n // registerSignalHandlers() (DISC-1249). This hook plugs into the existing\n // coordinator; registerBeforeExitTrigger() covers the event-loop-drain path.\n // Capture the concrete provider now (registration time) rather than at hook\n // execution time. If something replaced the global provider between now and\n // shutdown, we still flush the correct one — matching the pattern Scenario A\n // uses when capturing `provider` in a lexical closure.\n // @vercel/otel wraps its provider in a ProxyTracerProvider; unwrap once\n // to reach the concrete BasicTracerProvider that exposes shutdown().\n const vercelProxy = otelApi.trace.getTracerProvider() as unknown as {\n getDelegate?: () => { shutdown?: () => Promise<void> };\n };\n const vercelConcreteProvider = typeof vercelProxy.getDelegate === \"function\"\n ? vercelProxy.getDelegate()\n : (vercelProxy as { shutdown?: () => Promise<void> });\n registerShutdownHook({\n name: \"vercel-otel-shutdown\",\n priority: 0,\n fn: async () => {\n try {\n await vercelConcreteProvider.shutdown?.();\n } catch {\n // best-effort: provider may already be shut down or not support shutdown\n }\n },\n });\n registerBeforeExitTrigger();\n\n setOtelState(OtelState.OWNS_PROVIDER);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"E\" });\n return;\n }\n\n // Bare OTel SDK fallback (Scenario A)\n\n // Enable OTel diagnostic logging in verbose mode so OTLP exporter\n // errors (auth failures, network issues) are surfaced to the developer.\n // Routes through sdkLog to avoid console-capture recording OTel internals.\n if (config.verbose) {\n otelApi.diag.setLogger(\n {\n verbose: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n debug: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n info: (msg) => sdkLog(\"info\", `[otel] ${msg}`),\n warn: (msg) => sdkLog(\"warn\", `[otel] ${msg}`),\n error: (msg) => sdkLog(\"error\", `[otel] ${msg}`),\n },\n otelApi.DiagLogLevel.WARN,\n );\n }\n\n const processor = new BatchSpanProcessor(glasstraceExporter, {\n scheduledDelayMillis: 1000,\n });\n const provider = new BasicTracerProvider({\n spanProcessors: [processor],\n });\n\n // Context manager is registered synchronously in registerGlasstrace()\n // before configureOtel() is called (DISC-1183). By this point, it's\n // already active and propagating trace context across async boundaries.\n\n otelApi.trace.setGlobalTracerProvider(provider);\n\n // Register OTel shutdown via lifecycle coordinator.\n // Signal handlers are installed upfront by registerGlasstrace() so they\n // exist during this async setup window (DISC-1249). beforeExit is still\n // wired here because Scenario A owns the provider and the coexistence\n // path registers its own beforeExit trigger independently.\n registerShutdownHook({\n name: \"otel-provider-shutdown\",\n priority: 0,\n fn: async () => {\n await provider.shutdown();\n },\n });\n registerBeforeExitTrigger();\n\n // Register Prisma instrumentation on the bare path (DISC-1223).\n // The Vercel path handles this via registerOTel({ instrumentations: [...] }).\n // The coexistence path gets Prisma from the existing provider (e.g., Sentry).\n // Only the bare path was missing it.\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown & { setTracerProvider: (p: unknown) => void; enable: () => void }) | undefined;\n if (PrismaInstrumentation) {\n try {\n const inst = new PrismaInstrumentation();\n inst.setTracerProvider(provider);\n inst.enable();\n } catch {\n // Prisma instrumentation is optional — failure is not fatal\n }\n }\n }\n\n setOtelState(OtelState.OWNS_PROVIDER);\n emitLifecycleEvent(\"otel:configured\", { state: OtelState.OWNS_PROVIDER, scenario: \"A\" });\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport * as otelApi from \"@opentelemetry/api\";\n\n/**\n * Registers an AsyncLocalStorage-based context manager with the OTel API.\n *\n * This MUST be called synchronously before any spans are created —\n * otherwise, spans created before registration have no parent context\n * and each gets a fresh traceId (DISC-1183).\n *\n * Uses a static import of `node:async_hooks` (synchronous, no race\n * condition). This means the module cannot be evaluated in non-Node\n * environments (Edge Runtime, browser) — but the SDK is a server-side\n * package and non-Node environments are guarded by the `sideEffects: false`\n * flag in package.json (browser bundlers tree-shake it) and the browser\n * import check CI step externalizes `async_hooks`.\n *\n * @returns `true` if the context manager was installed, `false` if\n * another tool already registered a context manager.\n */\nexport function installContextManager(): boolean {\n try {\n const als = new AsyncLocalStorage<otelApi.Context>();\n\n const contextManager: otelApi.ContextManager = {\n active: () => als.getStore() ?? otelApi.ROOT_CONTEXT,\n with: <A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: otelApi.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> => als.run(context, () => fn.apply(thisArg, args)),\n bind: <T>(context: otelApi.Context, target: T): T => {\n if (typeof target === \"function\") {\n const bound = (...fnArgs: unknown[]) =>\n als.run(context, () => (target as (...a: unknown[]) => unknown)(...fnArgs));\n return bound as T;\n }\n return target;\n },\n enable: () => contextManager,\n disable: () => contextManager,\n };\n\n const success = otelApi.context.setGlobalContextManager(contextManager);\n if (!success) {\n console.warn(\n \"[glasstrace] Another context manager is already registered. \" +\n \"Trace context propagation may not work as expected.\",\n );\n }\n return success;\n } catch {\n return false;\n }\n}\n","import type { AnonApiKey } from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { collectHealthReport } from \"./health-collector.js\";\nimport { performInit, consumeRateLimitFlag } from \"./init-client.js\";\nimport { sdkLog } from \"./console-capture.js\";\nimport { registerShutdownHook, executeShutdown } from \"./lifecycle.js\";\n\nconst HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nconst BACKOFF_BASE_MS = HEARTBEAT_INTERVAL_MS; // 5 minutes\nconst BACKOFF_MAX_MS = 30 * 60 * 1000; // 30 minutes\nconst BACKOFF_JITTER = 0.2; // ±20%\n\n/**\n * Shutdown hook priority for the final heartbeat report.\n *\n * Per docs/component-designs/sdk-lifecycle.md Section 8.3:\n * 0 — OTel flush (must run first so spans are exported)\n * 10 — Heartbeat final report (includes final span counts)\n * 20 — Runtime state write (terminal state persisted last)\n */\nconst HEARTBEAT_SHUTDOWN_PRIORITY = 10;\n\nconst SHUTDOWN_MARKER_RELPATH = \".glasstrace/shutdown-requested\";\n\n// --- Module-level state ---\n\nlet heartbeatTimer: ReturnType<typeof setInterval> | null = null;\nlet heartbeatGeneration = 0;\nlet backoffAttempts = 0;\nlet backoffUntil = 0;\nlet tickInProgress = false;\n\n/**\n * Ensures the shutdown hook is only registered once per process and that\n * the final report is only sent once even if the hook runs more than once.\n */\nlet shutdownHookRegistered = false;\nlet shutdownFired = false;\n\n// --- Public API ---\n\n/**\n * Starts the periodic health heartbeat after successful init.\n * Timer is unref()'d so it doesn't prevent process exit.\n *\n * Registers a shutdown hook with the lifecycle coordinator (priority 10)\n * so the final health report runs after OTel flush (priority 0) and before\n * runtime state write (priority 20). The hook is registered once per\n * process; subsequent `startHeartbeat` calls do not re-register.\n *\n * @param onClaimTransition - Callback for claim key rotation, avoiding\n * circular dependency with otel-config.ts.\n */\nexport function startHeartbeat(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n generation: number,\n onClaimTransition: (newApiKey: string, accountId: string) => void,\n): void {\n // Prevent double-start\n if (heartbeatTimer !== null) return;\n\n heartbeatGeneration = generation;\n\n heartbeatTimer = setInterval(() => {\n void heartbeatTick(config, anonKey, sdkVersion, generation, onClaimTransition);\n }, HEARTBEAT_INTERVAL_MS);\n\n // unref() so the timer doesn't prevent Node.js process exit\n heartbeatTimer.unref();\n\n // Register the final health-report hook with the lifecycle coordinator.\n // Signal handling is owned by the coordinator (registerSignalHandlers in\n // otel-config.ts), so the heartbeat module no longer attaches directly to\n // SIGTERM/SIGINT.\n registerHeartbeatShutdownHook(config, anonKey, sdkVersion);\n\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat started (5-minute interval).\");\n }\n}\n\n/**\n * Stops the heartbeat timer.\n *\n * The shutdown hook is intentionally not unregistered — the lifecycle\n * coordinator does not expose a removal API. Stopping the heartbeat here\n * suppresses future periodic ticks by clearing the timer, but it does not\n * prevent the already-registered shutdown hook from sending its final\n * health report once during process shutdown. The hook's internal\n * `shutdownFired` guard ensures it runs at most once regardless.\n */\nexport function stopHeartbeat(): void {\n if (heartbeatTimer !== null) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * Resets all heartbeat state. For testing only.\n */\nexport function _resetHeartbeatForTesting(): void {\n stopHeartbeat();\n heartbeatGeneration = 0;\n backoffAttempts = 0;\n backoffUntil = 0;\n tickInProgress = false;\n shutdownHookRegistered = false;\n shutdownFired = false;\n}\n\n/**\n * Checks for the presence of the `.glasstrace/shutdown-requested` marker\n * file and, if present, triggers the lifecycle shutdown coordinator and\n * removes the marker (DISC-1247 Scenario 1).\n *\n * Returns `true` when the marker was found and the shutdown coordinator\n * was scheduled, `false` otherwise. The marker is removed synchronously\n * BEFORE executeShutdown() is scheduled so a crash during shutdown does\n * not cause the marker to be re-detected on restart.\n *\n * The filesystem lookup itself is synchronous, but `node:fs`/`node:path`\n * are loaded lazily via `require()` inside this helper rather than via\n * top-level imports. This keeps the helper usable from fake-timer-driven\n * heartbeat ticks without introducing extra microtask boundaries, while\n * also avoiding unconditional top-level built-in imports on module\n * load. The downstream `executeShutdown()` call can be awaited by the\n * caller when desired.\n *\n * Self-contained so it can be called from either the heartbeat tick\n * (current location) or a dedicated lifecycle hook after DISC-1248 lands.\n *\n * @param projectRoot - Optional project root; defaults to `process.cwd()`.\n * @returns An object describing the outcome. When `triggered` is true,\n * `shutdown` is the promise returned by `executeShutdown()` so the\n * caller can optionally await full shutdown completion.\n */\nexport function checkShutdownMarker(projectRoot?: string): {\n triggered: boolean;\n shutdown?: Promise<void>;\n} {\n // node:fs and node:path are imported lazily via require to remain\n // compatible with non-Node bundlers that externalize node:* modules.\n // Errors are swallowed — a non-Node environment simply reports\n // \"no marker\".\n let fsSync: typeof import(\"node:fs\") | null = null;\n let pathSync: typeof import(\"node:path\") | null = null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n fsSync = require(\"node:fs\") as typeof import(\"node:fs\");\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n pathSync = require(\"node:path\") as typeof import(\"node:path\");\n } catch {\n return { triggered: false };\n }\n\n const root = projectRoot ?? (typeof process !== \"undefined\" ? process.cwd() : \".\");\n const markerPath = pathSync.join(root, SHUTDOWN_MARKER_RELPATH);\n\n if (!fsSync.existsSync(markerPath)) return { triggered: false };\n\n // Remove the marker BEFORE scheduling shutdown. If we removed it\n // afterwards, a crashed process would leave the marker in place and\n // cause the next start to shut down immediately.\n try {\n fsSync.unlinkSync(markerPath);\n } catch {\n // Best-effort — proceed with shutdown even if removal fails.\n }\n\n // executeShutdown is idempotent and never throws; fire-and-track the\n // returned promise so the caller can optionally await completion.\n const shutdown = executeShutdown().catch(() => {\n // executeShutdown is designed not to throw; swallow defensively.\n });\n return { triggered: true, shutdown };\n}\n\n// --- Internal: heartbeat tick ---\n\nasync function heartbeatTick(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n generation: number,\n onClaimTransition: (newApiKey: string, accountId: string) => void,\n): Promise<void> {\n // Prevent concurrent ticks (setInterval doesn't await async callbacks)\n if (tickInProgress) return;\n tickInProgress = true;\n\n try {\n // Generation check — stop if registration was reset\n if (generation !== heartbeatGeneration) {\n stopHeartbeat();\n return;\n }\n\n // DISC-1247 Scenario 1: check for the shutdown-requested marker at\n // the top of each tick. If `sdk uninit` has been run, the marker\n // exists and we trigger shutdown immediately. Moved into a dedicated\n // lifecycle hook once DISC-1248 lands — the helper is module-exported\n // to keep that migration mechanical.\n //\n // The check itself is synchronous (fs.existsSync) so fake-timer tests\n // stay deterministic; we do await the shutdown promise once it has\n // been scheduled so the tick does not race its own cleanup.\n const markerResult = checkShutdownMarker();\n if (markerResult.triggered) {\n stopHeartbeat();\n if (markerResult.shutdown) {\n await markerResult.shutdown;\n }\n return;\n }\n\n // Backoff check — skip this tick if in backoff window\n if (Date.now() < backoffUntil) {\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat skipped (rate-limit backoff).\");\n }\n return;\n }\n\n // Collect and send health report (same pattern as backgroundInit)\n const healthReport = collectHealthReport(sdkVersion);\n const initResult = await performInit(config, anonKey, sdkVersion, healthReport);\n\n // Generation re-check after async work\n if (generation !== heartbeatGeneration) return;\n\n // Handle 429 backoff via consumeRateLimitFlag\n if (initResult === null && consumeRateLimitFlag()) {\n backoffAttempts++;\n const delay = Math.min(\n BACKOFF_BASE_MS * Math.pow(2, backoffAttempts - 1),\n BACKOFF_MAX_MS,\n );\n const jitter = delay * BACKOFF_JITTER * (Math.random() * 2 - 1);\n backoffUntil = Date.now() + delay + jitter;\n if (config.verbose) {\n sdkLog(\"info\", `[glasstrace] Heartbeat backing off for ${Math.round((delay + jitter) / 1000)}s.`);\n }\n } else {\n // Success or non-429 failure — reset backoff\n backoffAttempts = 0;\n backoffUntil = 0;\n }\n\n // Handle claim transition via callback (no otel-config import needed)\n if (initResult?.claimResult) {\n onClaimTransition(initResult.claimResult.newApiKey, initResult.claimResult.accountId);\n }\n\n if (config.verbose) {\n sdkLog(\"info\", \"[glasstrace] Heartbeat completed.\");\n }\n } finally {\n tickInProgress = false;\n }\n}\n\n// --- Internal: shutdown health report ---\n\n/**\n * Registers the heartbeat's final-report hook exactly once per process.\n *\n * The hook:\n * - Is idempotent (`shutdownFired` guard) so a duplicate invocation by\n * the coordinator cannot double-report.\n * - Stops the timer first so no further ticks race with the final report.\n * - Preserves the exact payload that the previous direct-handler code\n * sent (`collectHealthReport` + `performInit`), so consumers observe\n * identical shutdown telemetry before and after this refactor.\n * - Does NOT re-raise the signal. The lifecycle coordinator's signal\n * handler owns signal propagation and calls process.kill() after all\n * hooks complete.\n */\nfunction registerHeartbeatShutdownHook(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n): void {\n if (shutdownHookRegistered) return;\n shutdownHookRegistered = true;\n\n registerShutdownHook({\n name: \"heartbeat-final-report\",\n priority: HEARTBEAT_SHUTDOWN_PRIORITY,\n fn: async () => {\n if (shutdownFired) return;\n shutdownFired = true;\n\n // Stop the heartbeat timer — no more ticks after this\n if (heartbeatTimer !== null) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n\n // Best-effort final report. Errors are swallowed so they don't\n // prevent the remainder of the shutdown sequence from completing.\n try {\n const healthReport = collectHealthReport(sdkVersion);\n await performInit(config, anonKey, sdkVersion, healthReport);\n } catch {\n // Intentionally swallow final-report failures to avoid adding\n // shutdown noise or interrupting the remaining shutdown hooks.\n }\n },\n });\n}\n","/**\n * Runtime State Bridge\n *\n * Writes the SDK's lifecycle state to `.glasstrace/runtime-state.json`\n * so that CLI commands (npx @glasstrace/sdk status) can report runtime\n * state without a live process connection.\n *\n * Design: sdk-lifecycle.md Section 14 (Runtime State File)\n * Task brief: SDK-026\n */\n\nimport { writeFileSync, renameSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n getSdkState,\n onLifecycleEvent,\n CoreState,\n} from \"./lifecycle.js\";\nimport { sdkLog } from \"./console-capture.js\";\n\n/** Schema for the runtime state file. */\nexport interface RuntimeState {\n updatedAt: string;\n pid: number;\n sdkVersion: string;\n core: { state: string };\n auth: { state: string };\n otel: { state: string; scenario?: string };\n}\n\n// ---------------------------------------------------------------------------\n// Module State\n// ---------------------------------------------------------------------------\n\nlet _projectRoot: string | null = null;\nlet _sdkVersion: string = \"unknown\";\nlet _lastScenario: string | undefined;\nlet _debounceTimer: ReturnType<typeof setTimeout> | null = null;\nlet _started = false;\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start writing runtime state to disk on every lifecycle state transition.\n * Must be called after initLifecycle() and after the project root is known.\n *\n * Writes are debounced to max once per second. The final SHUTDOWN state\n * bypasses debounce to ensure it's always persisted.\n */\nexport function startRuntimeStateWriter(options: {\n projectRoot: string;\n sdkVersion: string;\n}): void {\n if (_started) return;\n _started = true;\n\n _projectRoot = options.projectRoot;\n _sdkVersion = options.sdkVersion;\n\n // Listen for state changes across all layers\n onLifecycleEvent(\"core:state_changed\", ({ to }) => {\n if (to === CoreState.SHUTDOWN) {\n // Bypass debounce for terminal state — write immediately\n writeStateNow();\n } else {\n debouncedWrite();\n }\n });\n\n onLifecycleEvent(\"otel:configured\", ({ scenario }) => {\n _lastScenario = scenario;\n debouncedWrite();\n });\n\n // Auth events — write when key resolves or claim transitions occur\n onLifecycleEvent(\"auth:key_resolved\", () => debouncedWrite());\n onLifecycleEvent(\"auth:claim_started\", () => debouncedWrite());\n onLifecycleEvent(\"auth:claim_completed\", () => debouncedWrite());\n\n // No shutdown hook needed — the SHUTDOWN bypass in the core:state_changed\n // listener writes the final state synchronously during setCoreState(SHUTDOWN).\n // A hook would write SHUTTING_DOWN (before SHUTDOWN) and be immediately\n // overwritten by the listener. The listener is simpler and correct.\n\n // Write initial state immediately\n writeStateNow();\n}\n\n/**\n * Reset runtime state writer. For testing only.\n */\nexport function _resetRuntimeStateForTesting(): void {\n if (_debounceTimer) {\n clearTimeout(_debounceTimer);\n _debounceTimer = null;\n }\n _projectRoot = null;\n _sdkVersion = \"unknown\";\n _lastScenario = undefined;\n _started = false;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\nfunction debouncedWrite(): void {\n if (_debounceTimer) return; // Already scheduled\n\n _debounceTimer = setTimeout(() => {\n _debounceTimer = null;\n writeStateNow();\n }, 1000);\n\n // unref so the timer doesn't prevent process exit\n if (typeof _debounceTimer === \"object\" && \"unref\" in _debounceTimer) {\n _debounceTimer.unref();\n }\n}\n\nfunction writeStateNow(): void {\n if (!_projectRoot) return;\n\n try {\n const state = getSdkState();\n const runtimeState: RuntimeState = {\n updatedAt: new Date().toISOString(),\n pid: process.pid,\n sdkVersion: _sdkVersion,\n core: { state: state.core },\n auth: { state: state.auth },\n otel: { state: state.otel, scenario: _lastScenario },\n };\n\n const dir = join(_projectRoot, \".glasstrace\");\n const filePath = join(dir, \"runtime-state.json\");\n const tmpPath = join(dir, \"runtime-state.json.tmp\");\n\n // Ensure directory exists (may not if uninit deleted it)\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n\n // Atomic write: write to temp file then rename to avoid partial reads\n writeFileSync(tmpPath, JSON.stringify(runtimeState, null, 2) + \"\\n\", {\n mode: 0o600,\n });\n renameSync(tmpPath, filePath);\n } catch (err) {\n // Fire-and-forget — never block state transitions for a file write failure\n sdkLog(\n \"warn\",\n `[glasstrace] Failed to write runtime state: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n}\n","declare const __SDK_VERSION__: string;\n\nimport type { GlasstraceOptions, AnonApiKey } from \"@glasstrace/protocol\";\nimport { resolveConfig, isProductionDisabled, isAnonymousMode } from \"./env-detection.js\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { SessionManager } from \"./session.js\";\nimport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\nimport { loadCachedConfig, performInit, _setCurrentConfig, getActiveConfig, getLinkedAccountId, getClaimResult, didLastInitSucceed } from \"./init-client.js\";\nimport { createDiscoveryHandler } from \"./discovery-endpoint.js\";\nimport { configureOtel, setResolvedApiKey, getResolvedApiKey, notifyApiKeyResolved, resetOtelConfigForTesting } from \"./otel-config.js\";\nimport { installContextManager } from \"./context-manager.js\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { installConsoleCapture, uninstallConsoleCapture, sdkLog } from \"./console-capture.js\";\nimport { collectHealthReport, _resetHealthForTesting } from \"./health-collector.js\";\nimport { startHeartbeat, _resetHeartbeatForTesting } from \"./heartbeat.js\";\nimport { initLifecycle, setCoreState, CoreState, getCoreState, initAuthState, AuthState, setAuthState, emitLifecycleEvent, registerSignalHandlers, resetLifecycleForTesting } from \"./lifecycle.js\";\nimport { setCoexistenceState } from \"./signal-handler.js\";\nimport { startRuntimeStateWriter, _resetRuntimeStateForTesting } from \"./runtime-state.js\";\n\n/** Mask an API key for safe event emission — shows prefix + last 4 chars. */\nfunction maskKey(key: string): string {\n if (key.length <= 12) return key.slice(0, 4) + \"...\";\n return key.slice(0, 8) + \"...\" + key.slice(-4);\n}\n\n/** Whether console capture has been installed in this registration cycle. */\nlet consoleCaptureInstalled = false;\n\n/** Module-level state tracking for the registered discovery handler. */\nlet discoveryHandler: ((request: Request) => Promise<Response | null>) | null = null;\n\n/** Generation counter to invalidate stale background promises after reset. */\nlet registrationGeneration = 0;\n\n/** Module-level session manager, shared with createGlasstraceSpanProcessor(). */\nlet _sessionManager: SessionManager | null = null;\n\n/** Returns the shared SessionManager. Creates a new one if registerGlasstrace() hasn't run yet. */\nexport function getSessionManager(): SessionManager {\n if (!_sessionManager) {\n _sessionManager = new SessionManager();\n }\n return _sessionManager;\n}\n\n/**\n * The primary SDK entry point called by developers in their `instrumentation.ts`.\n * Orchestrates OTel setup, span processor, init client, anon key, and discovery endpoint.\n *\n * This function is synchronous and MUST NOT throw. The developer's server is never blocked.\n * Background work (key resolution, init call) happens via fire-and-forget promises.\n *\n * @param options - Optional SDK configuration. Environment variables are used as fallbacks.\n *\n * @example\n * ```ts\n * // instrumentation.ts\n * import { registerGlasstrace } from \"@glasstrace/sdk\";\n * registerGlasstrace(); // uses env vars\n * ```\n */\nexport function registerGlasstrace(options?: GlasstraceOptions): void {\n try {\n // Prevent double registration (lifecycle state check replaces isRegistered flag)\n if (getCoreState() !== CoreState.IDLE) {\n return;\n }\n\n // Initialize lifecycle state machine before any state transitions.\n initLifecycle({ logger: sdkLog });\n\n // Guard: SDK requires Node.js runtime. Some environments (e.g. Bun,\n // Deno with partial Node compat) resolve node: imports but lack full\n // Node.js APIs. This guard prevents cryptic failures deeper in the\n // SDK by detecting these environments early and returning a no-op.\n //\n // Note: environments that cannot resolve node: imports at all (pure\n // Edge Runtime, Cloudflare Workers) will fail at module evaluation\n // before this guard runs. Those cases are mitigated by the package's\n // `sideEffects: false` flag and bundler externalization of node: modules.\n if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n console.warn(\n \"[glasstrace] SDK requires a Node.js runtime. \" +\n \"Edge Runtime, browser, and Deno without Node compat are not supported. \" +\n \"Glasstrace is disabled in this environment.\",\n );\n return;\n }\n\n setCoreState(CoreState.REGISTERING);\n\n // Start runtime state writer — writes lifecycle state to\n // .glasstrace/runtime-state.json for CLI status reporting (SDK-026).\n // Must be after initLifecycle() and Node.js guard.\n startRuntimeStateWriter({\n projectRoot: process.cwd(),\n sdkVersion: __SDK_VERSION__,\n });\n\n // Resolve config\n const config = resolveConfig(options);\n if (config.verbose) {\n console.info(\"[glasstrace] Config resolved.\");\n }\n\n // Production check\n if (isProductionDisabled(config)) {\n setCoreState(CoreState.PRODUCTION_DISABLED);\n console.warn(\n \"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override.\",\n );\n return;\n }\n if (config.verbose) {\n console.info(\"[glasstrace] Not production-disabled.\");\n }\n\n // Synchronous probe for an existing OTel provider. Used to gate\n // context manager installation below. If another tracing tool (Datadog,\n // Sentry, New Relic) has already registered a provider, the SDK must\n // NOT claim the global context manager slot — doing so would break\n // the other tool's context propagation. The ProxyTracer check is\n // synchronous; it sees any provider installed before registerGlasstrace()\n // was called (the standard instrumentation order).\n const existingProbe = otelApi.trace.getTracerProvider().getTracer(\"glasstrace-probe\");\n const anotherProviderRegistered = existingProbe.constructor.name !== \"ProxyTracer\";\n\n // When another provider is already present, set coexistenceState BEFORE\n // installing the signal handler. Without this, the handler would see\n // \"unknown\" during the configureOtel() async tick/probe window and would\n // re-raise the signal — terminating the process before the existing\n // provider's async flush completes (Codex review on #168).\n //\n // configureOtel() calls setCoexistenceState() again after its own async\n // probe for precision (e.g. a new provider appears in that tick window),\n // but the synchronous probe is authoritative for any signal arriving\n // between registerGlasstrace() returning and configureOtel() completing.\n if (anotherProviderRegistered) {\n setCoexistenceState(\"coexisting\");\n }\n\n // Register SIGTERM/SIGINT handlers BEFORE any async work (DISC-1249).\n // configureOtel() yields a tick and awaits the @vercel/otel probe;\n // without an early handler a signal arriving in that window would find\n // no coordinator and silently drop buffered spans.\n //\n // The handler is now always installed regardless of whether another\n // provider exists (DISC-1265). Whether the signal is re-raised after our\n // hooks drain is decided at delivery time by checking coexistenceState:\n // - \"unknown\" → re-raise (safe default during the startup window)\n // - \"sole-owner\" → re-raise (Glasstrace owns the provider)\n // - \"coexisting\" → do NOT re-raise (existing provider owns shutdown)\n //\n // Registered AFTER the production check so PRODUCTION_DISABLED processes\n // don't retain a handler that would log invalid-transition warnings if\n // signaled.\n registerSignalHandlers();\n\n // Determine auth mode\n const anonymous = isAnonymousMode(config);\n let effectiveKey: string | undefined = config.apiKey;\n\n // Set initial auth lifecycle state based on configuration\n initAuthState(anonymous ? AuthState.ANONYMOUS : AuthState.AUTHENTICATED);\n\n if (effectiveKey) {\n setResolvedApiKey(effectiveKey);\n emitLifecycleEvent(\"auth:key_resolved\", {\n key: maskKey(effectiveKey),\n mode: anonymous ? \"anonymous\" : \"dev\",\n });\n }\n\n if (config.verbose) {\n console.info(\n `[glasstrace] Auth mode = ${anonymous ? \"anonymous\" : \"dev-key\"}.`,\n );\n }\n\n // Load cached config and apply to in-memory store\n const cachedInitResponse = loadCachedConfig();\n if (cachedInitResponse) {\n _setCurrentConfig(cachedInitResponse);\n }\n if (config.verbose) {\n console.info(\n `[glasstrace] Cached config ${cachedInitResponse ? \"loaded and applied\" : \"not found\"}.`,\n );\n }\n\n // Create or reuse SessionManager (shared with createGlasstraceSpanProcessor)\n const sessionManager = getSessionManager();\n if (config.verbose) {\n console.info(\"[glasstrace] SessionManager created.\");\n }\n\n setCoreState(CoreState.KEY_PENDING);\n const currentGeneration = registrationGeneration;\n\n if (anotherProviderRegistered) {\n if (config.verbose) {\n console.info(\"[glasstrace] Another OTel provider detected — using existing context manager.\");\n }\n } else {\n // Register the context manager SYNCHRONOUSLY before any spans are\n // created. Without this, each span starts a new root trace with a\n // fresh traceId because there's no parent context to inherit from.\n // Must happen before configureOtel (which is async) — Next.js may\n // create spans between registerGlasstrace() returning and\n // configureOtel() completing (DISC-1183).\n const contextManagerInstalled = installContextManager();\n if (config.verbose) {\n console.info(\n contextManagerInstalled\n ? \"[glasstrace] Context manager installed.\"\n : \"[glasstrace] Context manager not available — trace context propagation disabled.\",\n );\n }\n }\n\n // Configure OTel IMMEDIATELY in all modes.\n // OTel is registered before the anon key resolves so that\n // spans are captured from cold start. GlasstraceExporter buffers spans\n // while the key is \"pending\" and flushes them once notifyApiKeyResolved()\n // is called after anonymous key resolution.\n // This is fire-and-forget -- OTel failure must not block init.\n void configureOtel(config, sessionManager).then(\n () => {\n // Check cached config for consoleErrors (may be stale or absent).\n // Re-checked after performInit completes with the authoritative config.\n maybeInstallConsoleCapture();\n\n if (config.verbose) {\n console.info(\"[glasstrace] OTel configured.\");\n }\n },\n (err: unknown) => {\n console.warn(\n `[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`,\n );\n },\n );\n\n // Background work: anonymous key resolution, discovery endpoint, init\n if (anonymous) {\n // Register discovery endpoint IMMEDIATELY with async key resolution\n if (isDiscoveryEnabled(config)) {\n let resolvedAnonKey: AnonApiKey | null = null;\n const anonKeyPromise = getOrCreateAnonKey();\n\n // Derive claim state from the init response.\n // Called on every discovery request so it reflects the latest state.\n // Two sources indicate a claimed account:\n // 1. linkedAccountId — key was already linked to an account\n // 2. claimResult — a claim just completed during this init call\n const getClaimState = () => {\n if (getLinkedAccountId()) return { claimed: true as const };\n if (getClaimResult()) return { claimed: true as const };\n return null;\n };\n\n // Use getResolvedApiKey() for session ID instead of\n // capturing the mutable effectiveKey closure variable.\n discoveryHandler = createDiscoveryHandler(\n async () => resolvedAnonKey,\n () => sessionManager.getSessionId(getResolvedApiKey()),\n getClaimState,\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Discovery endpoint registered (key pending).\");\n }\n\n // Background: resolve key, update API key, then init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await anonKeyPromise;\n resolvedAnonKey = anonKey;\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n // Update the discovery handler to serve the resolved key\n // Use getResolvedApiKey() for canonical key state\n discoveryHandler = createDiscoveryHandler(\n () => Promise.resolve(anonKey),\n () => sessionManager.getSessionId(getResolvedApiKey()),\n getClaimState,\n );\n\n await backgroundInit(config, anonKey, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n } else {\n // Anonymous + non-dev: no discovery endpoint, just background init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await getOrCreateAnonKey();\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n emitLifecycleEvent(\"auth:key_resolved\", { key: maskKey(anonKey), mode: \"anonymous\" });\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n await backgroundInit(config, anonKey, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n } else {\n // Dev key mode: read straggler anon key, then fire init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n let anonKeyForInit: AnonApiKey | null = null;\n try {\n anonKeyForInit = await readAnonKey();\n } catch {\n // Expected when no prior anon key file exists on disk (first run).\n }\n\n if (currentGeneration !== registrationGeneration) return;\n\n await backgroundInit(config, anonKeyForInit, currentGeneration);\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n\n // Import graph (coverageMapEnabled) -- placeholder\n if (config.coverageMapEnabled && config.verbose) {\n console.info(\"[glasstrace] Import graph building skipped.\");\n }\n } catch (err) {\n setCoreState(CoreState.REGISTRATION_FAILED);\n console.warn(\n `[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Shared background init logic for all auth modes.\n *\n * Fires the init request, handles account claim transitions (updating\n * the exporter key), and re-checks console capture config. The anonymous\n * paths pass the anon key as `anonKeyForInit`; the dev-key path passes\n * the straggler anon key (or null).\n */\nasync function backgroundInit(\n config: ResolvedConfig,\n anonKeyForInit: AnonApiKey | null,\n generation: number,\n): Promise<void> {\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n const healthReport = collectHealthReport(__SDK_VERSION__);\n const initResult = await performInit(config, anonKeyForInit, __SDK_VERSION__, healthReport);\n\n if (generation !== registrationGeneration) return;\n\n // Bail if shutdown was initiated while backgroundInit was in flight.\n const currentState = getCoreState();\n if (currentState === CoreState.SHUTTING_DOWN || currentState === CoreState.SHUTDOWN) {\n return;\n }\n\n // Advance core lifecycle: KEY_PENDING → KEY_RESOLVED → ACTIVE/ACTIVE_DEGRADED.\n // In the full lifecycle (SDK-024), KEY_RESOLVED is triggered by auth:key_resolved.\n // For now, drive both transitions here since the auth layer isn't wired yet.\n if (currentState === CoreState.KEY_PENDING) {\n setCoreState(CoreState.KEY_RESOLVED);\n }\n if (getCoreState() === CoreState.KEY_RESOLVED) {\n setCoreState(didLastInitSucceed() ? CoreState.ACTIVE : CoreState.ACTIVE_DEGRADED);\n }\n\n // If the backend reported an account claim, update the exporter\n // key so subsequent span exports authenticate with the dev key.\n if (initResult?.claimResult) {\n const { newApiKey, accountId } = initResult.claimResult;\n setAuthState(AuthState.CLAIMING);\n emitLifecycleEvent(\"auth:claim_started\", { accountId });\n setResolvedApiKey(newApiKey);\n notifyApiKeyResolved();\n setAuthState(AuthState.CLAIMED);\n emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n }\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n\n // Start the periodic health heartbeat if init succeeded.\n // The heartbeat re-calls performInit every 5 minutes to report health\n // metrics and refresh config. Only starts after first successful init.\n if (didLastInitSucceed()) {\n startHeartbeat(config, anonKeyForInit, __SDK_VERSION__, generation, (newApiKey, accountId) => {\n setAuthState(AuthState.CLAIMING);\n emitLifecycleEvent(\"auth:claim_started\", { accountId });\n setResolvedApiKey(newApiKey);\n notifyApiKeyResolved();\n setAuthState(AuthState.CLAIMED);\n emitLifecycleEvent(\"auth:claim_completed\", { newKey: maskKey(newApiKey), accountId });\n });\n }\n}\n\n/**\n * Returns the registered discovery handler, or null if not registered.\n */\nexport function getDiscoveryHandler(): ((request: Request) => Promise<Response | null>) | null {\n return discoveryHandler;\n}\n\n/**\n * Checks the active config and installs console capture if enabled.\n * Idempotent — safe to call multiple times (after OTel config, after init).\n * This ensures console capture is installed whenever authoritative config\n * becomes available, whether from the file cache or the init response.\n */\nfunction maybeInstallConsoleCapture(): void {\n if (consoleCaptureInstalled) return;\n if (getActiveConfig().consoleErrors) {\n consoleCaptureInstalled = true;\n void installConsoleCapture();\n }\n}\n\n/**\n * Returns `true` if the discovery endpoint should be enabled for this environment.\n *\n * Tightened from \"not production\" to explicit development conditions:\n * 1. `GLASSTRACE_DISCOVERY_ENABLED=true` -- explicit override (highest priority)\n * 2. `GLASSTRACE_DISCOVERY_ENABLED=false` -- explicit disable (highest priority)\n * 3. `NODE_ENV` is `\"development\"` or unset, AND `VERCEL_ENV` is not `\"production\"`\n *\n * Environments like `staging`, `test`, and `ci` do not expose the discovery\n * endpoint by default, since it serves the anonymous API key over CORS.\n *\n * @param config - The resolved SDK configuration.\n * @returns Whether the discovery endpoint should be registered.\n */\nfunction isDiscoveryEnabled(config: ResolvedConfig): boolean {\n // Explicit flag takes precedence\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"true\") return true;\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"false\") return false;\n\n // Block production environments\n if (config.nodeEnv === \"production\") return false;\n if (config.vercelEnv === \"production\") return false;\n\n // Only allow in development or when NODE_ENV is unset\n if (config.nodeEnv === \"development\" || config.nodeEnv === undefined) return true;\n\n return false;\n}\n\n/**\n * Resets registration state. For testing only.\n */\nexport function _resetRegistrationForTesting(): void {\n discoveryHandler = null;\n consoleCaptureInstalled = false;\n registrationGeneration++;\n _resetHealthForTesting();\n _resetHeartbeatForTesting();\n uninstallConsoleCapture();\n resetOtelConfigForTesting(); // also resets coexistenceState via signal-handler\n _resetRuntimeStateForTesting();\n _sessionManager = null;\n resetLifecycleForTesting();\n}\n","import { isBuiltin as isNodeBuiltin } from \"node:module\";\n\n/**\n * Structural view of Next.js's `NextConfig`. The SDK does not import Next's\n * type directly because Next is not a peer dependency — this wrapper must\n * type-check regardless of which Next.js version the consumer has installed.\n *\n * The constraint is `object` rather than `Record<string, unknown>` because\n * Next's actual `NextConfig` is an interface *without* a string index\n * signature. Requiring `[key: string]: unknown` would fail the assignability\n * check that caused DISC-1256, reported by Next 16 consumers as:\n * > Argument of type 'NextConfig' is not assignable to parameter of type\n * > 'NextConfig'. Index signature for type 'string' is missing in type\n * > 'NextConfig'.\n *\n * `object` accepts every non-primitive value, which is what the wrapper\n * actually handles at runtime (it shallow-copies the input and reads a few\n * known properties defensively). Combined with the generic signature on\n * `withGlasstraceConfig`, callers preserve their exact config subtype.\n */\ntype NextConfig = object;\ntype WebpackConfigFn = (config: Record<string, unknown>, context: Record<string, unknown>) => Record<string, unknown>;\n\n/** Subset of the webpack context object passed by Next.js to the webpack config function. */\ninterface WebpackContext {\n isServer: boolean;\n dev: boolean;\n [key: string]: unknown;\n}\n\n/** Minimal webpack compiler shape for the afterEmit hook. */\ninterface WebpackCompiler {\n hooks?: {\n afterEmit?: {\n tapPromise?: (name: string, fn: (compilation: unknown) => Promise<void>) => void;\n };\n };\n}\n\n/**\n * Detects whether the current `next build` invocation is using Turbopack.\n *\n * Next 16 made Turbopack the default bundler for `next build`. We detect it\n * via `process.argv` (the `--turbopack` flag or the absence of `--webpack`\n * on Next 16) and the `TURBOPACK` environment variable that Next sets\n * internally. Falls back to `false` in non-Node environments.\n */\nfunction isTurbopackBuild(): boolean {\n if (typeof process === \"undefined\") return false;\n\n const argv = Array.isArray(process.argv) ? process.argv : [];\n if (argv.includes(\"--webpack\")) return false;\n if (argv.includes(\"--turbopack\")) return true;\n\n // Next sets TURBOPACK=1 when running its Turbopack pipeline.\n if (process.env?.TURBOPACK === \"1\") return true;\n\n return false;\n}\n\n/**\n * Package name the wrapper adds to Next's server-external-packages list.\n * Kept as a module-level constant so tests can reference the exact string\n * without risk of drift between implementation and assertion.\n */\nconst SDK_PACKAGE_NAME = \"@glasstrace/sdk\";\n\n/**\n * Signature of a webpack 5 externals function in the array-of-entries form.\n * The `data` argument carries the import request; the `callback` signals\n * either an externalization decision (`\"commonjs <specifier>\"`) or a\n * pass-through (no second argument).\n *\n * Typed structurally rather than importing from `webpack` to keep the SDK\n * free of a webpack peer dependency.\n */\ntype WebpackExternalsFn = (\n data: { request?: string; context?: string; contextInfo?: unknown; getResolve?: unknown },\n callback: (err: Error | null, result?: string) => void,\n) => void;\n\n/**\n * Appends an externals entry to a webpack config that rewrites every\n * Node.js built-in import into a runtime CommonJS `require()`. This is\n * the piece of DISC-1257 that actually fixes `next dev --webpack`:\n * webpack dev-mode ships no default handler for the `node:` URI scheme\n * AND does not auto-externalize bare built-ins pulled through transitive\n * SDK dependencies (e.g. `import * as zlib from \"zlib\"` inside an OTel\n * exporter). Either form crashes the first render — `UnhandledSchemeError`\n * for `node:*`, `Can't resolve 'zlib'` for bare built-ins — unless the\n * wrapper tells webpack to treat them as runtime externals.\n *\n * Membership is decided by Node's own `isBuiltin` helper\n * (`node:module`, available since Node 18.6; SDK `engines` floor is\n * Node >= 20), so the list of built-ins stays authoritative across\n * Node versions — no hand-maintained allowlist to drift out of date.\n *\n * Webpack 5 accepts externals as a string, RegExp, object, function, or\n * array of any mixture of those. Next.js itself uses the array form. The\n * helper preserves whatever the user (or Next) already supplied:\n * - Array: append the new entry, user entries keep their positions.\n * - Function or object: wrap in an array with the user entry first so it\n * takes precedence over the SDK's handler.\n * - Missing / nullish: initialise as a single-entry array.\n *\n * The emitted `commonjs <request>` form preserves whichever specifier the\n * caller used (prefixed or bare), which Node resolves natively on Node\n * >= 14.18 — well below the SDK's `engines` floor of Node >= 20.\n */\nfunction appendNodeSchemeExternal(webpackConfig: Record<string, unknown>): void {\n const nodeBuiltinExternal: WebpackExternalsFn = (data, callback) => {\n const request = data.request;\n if (typeof request === \"string\" && isNodeBuiltin(request)) {\n callback(null, \"commonjs \" + request);\n return;\n }\n callback(null);\n };\n\n const existing = webpackConfig.externals;\n if (Array.isArray(existing)) {\n webpackConfig.externals = [...existing, nodeBuiltinExternal];\n } else if (existing == null) {\n webpackConfig.externals = [nodeBuiltinExternal];\n } else {\n // Function, object-map, RegExp, or string form — preserve as the first\n // array entry so user/Next externals resolve before the SDK's fallback.\n webpackConfig.externals = [existing, nodeBuiltinExternal];\n }\n}\n\n/**\n * Pushes `@glasstrace/sdk` onto Next.js's `serverExternalPackages` list so\n * the package is loaded via Node's `require()` at runtime instead of\n * bundled through webpack/Turbopack.\n *\n * Only the Next 15+ stable top-level key is written. The Next 14 legacy\n * `experimental.serverComponentsExternalPackages` key was dropped because\n * Next 16 logs a deprecation warning for it on every build. Next 14 is\n * EOL; webpack-dev users on Next 14 are covered by the companion\n * `node:*` externals function installed below, and Turbopack users on\n * Next 14 were already unaffected.\n *\n * Dedupe is intentional: if the user already added `@glasstrace/sdk` to\n * the array, the entry is not duplicated. User entries are preserved in\n * their original order; the SDK entry is appended.\n *\n * Note that `serverExternalPackages` only affects RSC and Route Handler\n * bundling — it does NOT externalize the instrumentation path under\n * `next dev --webpack` (see vercel/next.js#58003, #28774). The full fix\n * for DISC-1257 pairs this write with the `node:*` externals function.\n *\n * Mutates the `config` bag in place; callers pass the shallow-copied bag\n * owned by `withGlasstraceConfig`, so the user's original reference is not\n * affected.\n */\nfunction ensureServerExternal(config: Record<string, unknown>): void {\n // Next 15+ stable key: top-level `serverExternalPackages`.\n const existingStable = config.serverExternalPackages;\n const stable: string[] = Array.isArray(existingStable)\n ? // Clone so we never mutate a caller-owned array in place.\n existingStable.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n if (!stable.includes(SDK_PACKAGE_NAME)) {\n stable.push(SDK_PACKAGE_NAME);\n }\n config.serverExternalPackages = stable;\n}\n\n/**\n * Wraps the developer's Next.js config to enable source map generation\n * and upload .map files to the ingestion API at build time.\n *\n * The build NEVER fails because of Glasstrace — all errors are caught\n * and logged as warnings.\n *\n * ## What the wrapper configures for you\n *\n * - `experimental.serverSourceMaps: true` — enables server-side source maps\n * so Glasstrace can resolve stack traces back to your source.\n * - `serverExternalPackages: [\"@glasstrace/sdk\"]` — tells Next to load the\n * SDK via Node's `require()` at runtime instead of bundling it through\n * webpack or Turbopack on the RSC / Route Handler paths. This is the same\n * pattern Prisma, `@vercel/otel`, Sentry, `sharp`, and `bcrypt` ship with.\n * - A webpack `externals` entry that marks every Node.js built-in import\n * (both `node:*` and bare forms like `zlib` or `stream`) as a runtime\n * `commonjs` require. `serverExternalPackages` does not apply to the\n * instrumentation path under `next dev --webpack`\n * (vercel/next.js#58003, #28774), so any bundled SDK chunk that imports\n * `node:child_process` or the bare `zlib` specifier used by\n * `@opentelemetry/otlp-exporter-base` would otherwise crash with\n * `UnhandledSchemeError` or `Can't resolve 'zlib'`. This entry is the\n * actual DISC-1257 fix for the dev-webpack path. Turbopack is\n * unaffected — it ignores `config.webpack` and resolves Node built-ins\n * natively.\n * - An empty `turbopack: {}` when none is set, so Next 16 does not reject\n * the config for setting `webpack` without a companion `turbopack` key\n * (DISC-1256).\n * - A `webpack` hook that collects and uploads `.map` files on client-side\n * production builds.\n *\n * ## Turbopack\n *\n * Next.js 16 made Turbopack the default bundler for `next build`, and Next\n * rejects configs that set `webpack` without also setting `turbopack`. This\n * wrapper therefore seeds an empty `turbopack: {}` when the user has not set\n * one themselves, preserving existing behaviour for explicit Turbopack configs.\n *\n * **Source-map upload is currently webpack-only.** Under Turbopack the build\n * succeeds, but the afterEmit hook that collects and uploads `.map` files does\n * not fire. Run `next build --webpack` to get source-map uploads, or wait for\n * a follow-up release that ports the plugin to Turbopack.\n *\n * @param nextConfig - The developer's existing Next.js configuration object.\n * @returns A new config object with source map generation and upload enabled.\n * The return type mirrors the input type so that caller-side config\n * properties are preserved. The `object` constraint (rather than\n * `Record<string, unknown>`) is what makes the wrapper accept Next's\n * real `NextConfig` interface (DISC-1256).\n */\nexport function withGlasstraceConfig<T extends NextConfig>(nextConfig: T): T {\n // Guard: config wrapper requires Node.js for source map instrumentation.\n // In non-Node environments (Edge Runtime, browser), return config unchanged.\n if (typeof process === \"undefined\" || typeof process.versions?.node !== \"string\") {\n return (nextConfig != null ? { ...nextConfig } : ({} as T));\n }\n\n // Handle null/undefined gracefully\n const config: T = nextConfig != null ? { ...nextConfig } : ({} as T);\n // Mutable bag-of-props view of the same object. Using `object` as the\n // constraint (see the `NextConfig` type alias above) means `T` does not\n // declare the keys we touch — `experimental`, `turbopack`, `distDir`,\n // `webpack` — so we interact with them through this looser view while the\n // public return type stays faithfully `T`.\n const bag = config as Record<string, unknown>;\n\n // Enable server-side source map generation for Glasstrace uploads.\n // Intentionally does NOT set productionBrowserSourceMaps — that exposes\n // full source code publicly via browser DevTools. Users who want public\n // browser source maps can set it explicitly in their Next.js config.\n\n // Enable server-side source maps (Next.js experimental feature)\n const existingExperimental = (bag.experimental as Record<string, unknown>) ?? {};\n bag.experimental = {\n ...existingExperimental,\n serverSourceMaps: true,\n };\n\n // Mark the SDK as a server-external package (DISC-1257). This covers the\n // RSC and Route Handler bundlers on Next 15+. The companion `node:*`\n // externals entry inside the `config.webpack` hook below is what actually\n // unblocks `next dev --webpack`.\n ensureServerExternal(bag);\n\n // Seed an empty Turbopack config when the user has not set one. Next 16\n // refuses builds that set `webpack` without a companion `turbopack` key\n // (DISC-1256). Merging preserves any existing Turbopack config the user\n // supplied — we only fill in the default.\n if (bag.turbopack == null) {\n bag.turbopack = {};\n }\n\n // One-time warning: source-map upload does not run under Turbopack yet.\n // Log at most once per process to avoid spamming repeated builds (dev mode,\n // watch mode). The warning goes to stderr via console.warn — intentionally\n // not using sdkLog so the message surfaces during the build even if SDK\n // logging is otherwise suppressed.\n if (isTurbopackBuild()) {\n warnTurbopackLimitationOnce();\n }\n\n // Capture distDir for source map collection (default: .next)\n const distDir = typeof bag.distDir === \"string\" ? bag.distDir : \".next\";\n\n // Capture existing webpack config if any\n const existingWebpack = bag.webpack as WebpackConfigFn | undefined;\n\n // Register webpack config modifier\n bag.webpack = (\n webpackConfig: Record<string, unknown>,\n context: Record<string, unknown>,\n ): Record<string, unknown> => {\n // Call existing webpack config first\n let result = webpackConfig;\n if (typeof existingWebpack === \"function\") {\n result = existingWebpack(webpackConfig, context);\n }\n\n // DISC-1257: externalize Node.js built-in imports for the webpack path.\n const webpackContext = context as WebpackContext;\n\n // Next's `serverExternalPackages` only influences RSC / Route Handler\n // bundling; the instrumentation path under `next dev --webpack` still\n // runs transitive SDK imports through the dev bundler, which crashes\n // on any built-in module — `UnhandledSchemeError` for `node:*` and\n // `Can't resolve 'zlib'` / `'stream'` / etc. for bare specifiers used\n // by OTel's exporter dependencies (vercel/next.js#58003, #28774).\n //\n // Telling webpack to externalize every Node built-in as a runtime\n // CommonJS require resolves the crash on every SERVER webpack code\n // path — production build, dev server, instrumentation hook. We\n // scope it to `webpackContext.isServer` so client-side compilations\n // (where Next applies browser polyfills / fallbacks for things like\n // `buffer` / `stream` / `crypto`) are not affected. Emitting\n // `commonjs` externals on the client would bypass those fallbacks\n // and inject `require(...)` at runtime, which fails in the browser.\n // Turbopack ignores this field and resolves Node built-ins natively\n // on both client and server.\n if (webpackContext.isServer) {\n appendNodeSchemeExternal(result);\n }\n\n // Only run source map upload on client-side production builds (not server, not dev)\n if (!webpackContext.isServer && webpackContext.dev === false) {\n // Register a plugin to collect and upload source maps after compilation\n const plugins = (result.plugins as Array<Record<string, unknown>>) ?? [];\n plugins.push({\n apply(compiler: Record<string, unknown>) {\n const typedCompiler = compiler as WebpackCompiler;\n if (typedCompiler.hooks?.afterEmit?.tapPromise) {\n typedCompiler.hooks.afterEmit.tapPromise(\n \"GlasstraceSourceMapUpload\",\n async () => {\n await handleSourceMapUpload(distDir);\n },\n );\n }\n },\n });\n result.plugins = plugins;\n }\n\n return result;\n };\n\n return config;\n}\n\nlet _turbopackWarningEmitted = false;\nfunction warnTurbopackLimitationOnce(): void {\n if (_turbopackWarningEmitted) return;\n _turbopackWarningEmitted = true;\n console.warn(\n \"[glasstrace] Turbopack detected. Source-map upload currently runs only under webpack — \" +\n \"run `next build --webpack` to upload source maps, or wait for the Turbopack port in a future SDK release.\",\n );\n}\n\n/**\n * Resets the one-shot Turbopack warning flag. For test use only.\n *\n * @internal\n */\nexport function _resetTurbopackWarningForTesting(): void {\n _turbopackWarningEmitted = false;\n}\n\n/**\n * Collects source map files from the build output directory and uploads\n * them to the Glasstrace ingestion API. Never throws — all errors are\n * caught and logged as warnings so the build is never blocked.\n *\n * Exported for testing only; not part of the public API.\n *\n * @param distDir - The Next.js build output directory (e.g. \".next\").\n */\nexport async function handleSourceMapUpload(distDir: string): Promise<void> {\n try {\n const apiKey = process.env.GLASSTRACE_API_KEY;\n const endpoint =\n process.env.GLASSTRACE_ENDPOINT ?? \"https://api.glasstrace.dev\";\n\n // Anonymous mode: skip upload\n if (!apiKey || apiKey.trim() === \"\") {\n console.info(\n \"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations.\",\n );\n return;\n }\n\n // Dynamic import: source-map-uploader uses node:fs, node:path, node:crypto,\n // and node:child_process. Deferring the import avoids a module-evaluation\n // crash when config-wrapper.ts is loaded in a non-Node bundler context.\n const { discoverSourceMapFiles, computeBuildHash, uploadSourceMaps } =\n await import(\"./source-map-uploader.js\");\n\n const files = await discoverSourceMapFiles(distDir);\n\n if (files.length === 0) {\n console.info(\"[glasstrace] No source map files found. Skipping upload.\");\n return;\n }\n\n const buildHash = await computeBuildHash(files);\n\n await uploadSourceMaps(apiKey, endpoint, buildHash, files);\n console.info(\n `[glasstrace] Uploaded ${String(files.length)} source map(s) for build ${buildHash}.`,\n );\n } catch (error: unknown) {\n // Build must NEVER fail because of Glasstrace\n const message =\n error instanceof Error ? error.message : \"Unknown error\";\n console.warn(\n `[glasstrace] Source map upload failed: ${message}. Build continues normally.`,\n );\n }\n}\n","/**\n * Manual error capture API.\n *\n * Provides a simple function for developers to manually record errors\n * as span events, independent of the `consoleErrors` config flag.\n */\n\nimport * as otelApi from \"@opentelemetry/api\";\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Records an error as a span event on the currently active OTel span.\n *\n * Works regardless of the `consoleErrors` configuration — this is an\n * explicit, opt-in API for manual error reporting. If no span is active\n * or OTel is not available, the call is silently ignored.\n *\n * On the first captured error, may display a one-time diagnostic nudge\n * to stderr if the MCP connection marker is absent (dev environments only).\n *\n * @param error - The error to capture. Accepts `Error` objects, strings, or any value.\n *\n * @example\n * ```ts\n * import { captureError } from \"@glasstrace/sdk\";\n *\n * try {\n * await riskyOperation();\n * } catch (err) {\n * captureError(err);\n * // handle error normally...\n * }\n * ```\n */\nexport function captureError(error: unknown): void {\n try {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (!span) return;\n\n const attributes: Record<string, string> = {\n \"error.message\": String(error),\n };\n\n if (error instanceof Error) {\n attributes[\"error.type\"] = error.constructor.name;\n if (error.stack) {\n attributes[\"error.stack\"] = error.stack;\n }\n }\n\n span.addEvent(\"glasstrace.error\", attributes);\n\n // Show one-time MCP connection nudge on first captured error\n maybeShowMcpNudge(String(error));\n } catch {\n // Silently ignore failures\n }\n}\n\n/**\n * Eagerly loads the OTel API module. Previously required for async resolution;\n * now a no-op since OTel is statically imported. Retained for test compatibility.\n *\n * @internal\n */\nexport async function _preloadOtelApi(): Promise<void> {\n // No-op: OTel API is now statically imported and always available.\n}\n\n/**\n * Resets internal state. For testing only.\n * @internal\n */\nexport function _resetCaptureErrorForTesting(): void {\n // No-op: OTel API is now statically imported and always available.\n // Kept for backward compatibility with existing tests.\n}\n","import { trace } from \"@opentelemetry/api\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\nconst HEADER_NAME = \"x-gt-cid\";\n\n/**\n * Hard cap on the correlation ID length we accept from the wire. Our\n * own extension emits ULIDs (26 characters); 128 is a generous ceiling\n * that still prevents a hostile client from ballooning span payloads.\n */\nconst MAX_CID_LENGTH = 128;\n\n/**\n * Minimal Fetch-API `Headers`-like interface supporting case-insensitive\n * single-value lookup. Matches `Headers` from `undici` / the Web Fetch API.\n */\ninterface FetchHeadersLike {\n get(name: string): string | null;\n}\n\n/**\n * Minimal Node `IncomingMessage.headers`-like shape: a dictionary mapping\n * (typically lower-cased) header names to a value, a list of values, or\n * `undefined`.\n */\ntype NodeHeadersLike = Record<\n string,\n string | string[] | undefined\n>;\n\n/**\n * Accepted request shape for {@link captureCorrelationId}. Intentionally\n * loose so callers can pass either a Fetch `Request` (or `NextRequest`)\n * or a Node `IncomingMessage` without adapting the type.\n */\nexport interface CorrelationIdRequest {\n headers: FetchHeadersLike | NodeHeadersLike | undefined;\n}\n\n/**\n * Captures the Glasstrace correlation ID header (`x-gt-cid`) from an\n * incoming request and materializes it as the\n * `glasstrace.correlation.id` attribute on the currently active OTel span\n * (DISC-1253).\n *\n * The SDK does not own any HTTP instrumentation, so it cannot read this\n * header itself. Users opt in by calling this helper from a hook that\n * runs inside the request's OTel context — typically a Next.js\n * `middleware.ts` or a custom server request handler.\n *\n * The function is intentionally forgiving:\n * - No active span → no-op.\n * - Missing / empty header → no-op.\n * - Array header values (Node IncomingMessage) → the first non-empty\n * value is used; subsequent values are ignored because a correlation\n * ID is a single logical value.\n * - Malformed or unexpected `headers` shapes → caught and ignored; the\n * helper never throws.\n *\n * @example\n * ```ts\n * // Next.js middleware.ts\n * import { captureCorrelationId } from \"@glasstrace/sdk\";\n *\n * export function middleware(req: Request) {\n * captureCorrelationId(req);\n * return NextResponse.next();\n * }\n * ```\n */\nexport function captureCorrelationId(req: CorrelationIdRequest | null | undefined): void {\n try {\n if (!req || !req.headers) {\n return;\n }\n\n const value = readHeader(req.headers);\n if (!value) {\n return;\n }\n\n const span = trace.getActiveSpan();\n if (!span) {\n return;\n }\n\n span.setAttribute(ATTR.CORRELATION_ID, value);\n } catch {\n // Never throw from a request hook — correlation is a best-effort\n // enrichment and must not break the user's request pipeline.\n }\n}\n\n/**\n * Reads the `x-gt-cid` header from either a Fetch-API `Headers` object\n * or a Node-style dictionary. Returns a trimmed single value, or\n * `undefined` if the header is missing or empty.\n */\nfunction readHeader(\n headers: FetchHeadersLike | NodeHeadersLike,\n): string | undefined {\n // Fetch-API Headers: duck-type on `.get(name)` being a function.\n const asFetch = headers as FetchHeadersLike;\n if (typeof asFetch.get === \"function\") {\n const raw = asFetch.get(HEADER_NAME);\n return firstToken(raw);\n }\n\n // Node IncomingMessage headers: case-insensitive dictionary lookup.\n // Node normalizes to lower-case but some frameworks preserve case, so\n // scan keys defensively.\n const dict = headers as NodeHeadersLike;\n const direct = dict[HEADER_NAME];\n if (direct !== undefined) {\n return firstValue(direct);\n }\n\n for (const key of Object.keys(dict)) {\n if (key.toLowerCase() === HEADER_NAME) {\n return firstValue(dict[key]);\n }\n }\n\n return undefined;\n}\n\n/**\n * Picks the first value from a possibly-array header and trims it.\n * Correlation IDs are logically single-valued; when duplicated we keep\n * the first occurrence and drop the rest.\n *\n * Also handles the comma-joined form that intermediaries (and some\n * Node.js HTTP stacks) produce when the same header is sent multiple\n * times — `x-gt-cid: cid1, x-gt-cid: cid2` may surface as the single\n * string `\"cid1, cid2\"` via `Headers.get()` or `IncomingMessage.headers`.\n * Storing that raw merged value would both fail correlation and\n * silently suppress the DISC-1253 Server Action nudge (which only\n * checks attribute presence, not validity). We split on commas and\n * keep the first non-empty token.\n */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n if (Array.isArray(value)) {\n for (const entry of value) {\n const token = firstToken(entry);\n if (token) return token;\n }\n return undefined;\n }\n return firstToken(value);\n}\n\n/**\n * Extracts the first comma-separated token from a header-like string\n * and normalizes it. Returns undefined when no non-empty token exists\n * within the length bound.\n */\nfunction firstToken(value: string | null | undefined): string | undefined {\n if (typeof value !== \"string\") return undefined;\n // Split on commas (HTTP list-header separator). Trim each token and\n // return the first non-empty one that fits within MAX_CID_LENGTH.\n // A single un-merged header has no commas and this reduces to the\n // previous normalize() behavior.\n const parts = value.split(\",\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n if (trimmed.length > MAX_CID_LENGTH) return undefined;\n return trimmed;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,IAAM,WAAN,cA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nC,WAAO,WAAW,GAAG;AAAA,EACvB;AAKA,QAAM,OAAO;AACb,QAAM,SAAS,KAAK,WAAW;AAC/B,MAAI,WAAW,QAAW;AACxB,WAAO,WAAW,MAAM;AAAA,EAC1B;AAEA,aAAW,OAAO,OAAO,KAAK,IAAI,GAAG;AACnC,QAAI,IAAI,YAAY,MAAM,aAAa;AACrC,aAAO,WAAW,KAAK,GAAG,CAAC;AAAA,IAC7B;AAAA,EACF;AAEA,SAAO;AACT;AAgBA,SAAS,WAAW,OAA0D;AAC5E,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,SAAS,OAAO;AACzB,YAAM,QAAQ,WAAW,KAAK;AAC9B,UAAI,MAAO,QAAO;AAAA,IACpB;AACA,WAAO;AAAA,EACT;AACA,SAAO,WAAW,KAAK;AACzB;AAOA,SAAS,WAAW,OAAsD;AACxE,MAAI,OAAO,UAAU,SAAU,QAAO;AAKtC,QAAM,QAAQ,MAAM,MAAM,GAAG;AAC7B,aAAW,QAAQ,OAAO;AACxB,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,QAAQ,WAAW,EAAG;AAC1B,QAAI,QAAQ,SAAS,eAAgB,QAAO;AAC5C,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":["cachedPort","cachedPort","_sessionManager","context","context","ExportResultCode","resolve","hrTime","hrTime","VERSION","VERSION","resolve","resolve","path","SamplingDecision","SamplingDecision","SamplingDecision","context","context","SamplingDecision","TracesSamplerValues","resolve","SamplingDecision","VERSION","VERSION","context","resolve","context","ForceFlushState","resolve","resolve","processor","resolve","prismaModule","context","context","discoverSourceMapFiles","computeBuildHash","uploadSourceMaps","ATTR"]}