@sentry/server-utils 11.17.0 → 11.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.
Files changed (95) hide show
  1. package/build/cjs/chunks/config.js +2 -2
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +115 -10
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/index.js +148 -31
  6. package/build/cjs/index.js.map +1 -1
  7. package/build/cjs/index.no-diagnostic-channels.js +1 -0
  8. package/build/cjs/index.request-handler.js +48 -3
  9. package/build/cjs/index.request-handler.js.map +1 -1
  10. package/build/esm/ai/langchain/utils.js +1 -5
  11. package/build/esm/ai/langchain/utils.js.map +1 -1
  12. package/build/esm/ai/mistral/streaming.js.map +1 -1
  13. package/build/esm/exports.js +2 -1
  14. package/build/esm/index.js +3 -1
  15. package/build/esm/index.js.map +1 -1
  16. package/build/esm/index.no-diagnostic-channels.js +2 -1
  17. package/build/esm/index.request-handler.js +3 -1
  18. package/build/esm/integrations/amqplib.js.map +1 -1
  19. package/build/esm/integrations/anthropic.js.map +1 -1
  20. package/build/esm/integrations/bullmq/tracer.js.map +1 -1
  21. package/build/esm/integrations/graphql/utils.js.map +1 -1
  22. package/build/esm/integrations/hapi/hapi-utils.js +6 -9
  23. package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
  24. package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
  25. package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
  26. package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
  27. package/build/esm/integrations/hono/patchRoute.js +2 -1
  28. package/build/esm/integrations/hono/patchRoute.js.map +1 -1
  29. package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
  30. package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
  31. package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
  32. package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
  33. package/build/esm/integrations/pino.js +2 -2
  34. package/build/esm/integrations/pino.js.map +1 -1
  35. package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
  36. package/build/esm/integrations/serveTunnel.js +2 -2
  37. package/build/esm/integrations/serveTunnel.js.map +1 -1
  38. package/build/esm/integrations/vercel-ai/extract.js +88 -0
  39. package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
  40. package/build/esm/integrations/vercel-ai/util.js +5 -1
  41. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  42. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
  43. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  44. package/build/esm/integrations/winston.js +2 -2
  45. package/build/esm/integrations/winston.js.map +1 -1
  46. package/build/esm/orchestrion/config/hono.js +2 -2
  47. package/build/esm/orchestrion/config/hono.js.map +1 -1
  48. package/build/esm/package.json +1 -1
  49. package/build/esm/utils/installedModules.js +87 -0
  50. package/build/esm/utils/installedModules.js.map +1 -0
  51. package/build/esm/utils/module.js +29 -0
  52. package/build/esm/utils/module.js.map +1 -0
  53. package/build/esm/utils/serverTimingTraceHeader.js +49 -0
  54. package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
  55. package/build/esm/utils/sql.js +4 -3
  56. package/build/esm/utils/sql.js.map +1 -1
  57. package/build/esm/utils/tunnelServer.js +3 -3
  58. package/build/esm/utils/tunnelServer.js.map +1 -1
  59. package/build/esm/utils/wrapServerRequestHandler.js +5 -4
  60. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  61. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  62. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  63. package/build/types/exports.d.ts +1 -0
  64. package/build/types/exports.d.ts.map +1 -1
  65. package/build/types/index.d.ts +3 -2
  66. package/build/types/index.d.ts.map +1 -1
  67. package/build/types/index.request-handler.d.ts +1 -0
  68. package/build/types/index.request-handler.d.ts.map +1 -1
  69. package/build/types/integrations/amqplib.d.ts.map +1 -1
  70. package/build/types/integrations/anthropic.d.ts.map +1 -1
  71. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
  72. package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
  73. package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
  74. package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
  75. package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
  76. package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
  77. package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
  78. package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
  79. package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
  80. package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
  81. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
  82. package/build/types/integrations/vercel-ai/util.d.ts +2 -0
  83. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  84. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
  85. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  86. package/build/types/utils/installedModules.d.ts +17 -0
  87. package/build/types/utils/installedModules.d.ts.map +1 -0
  88. package/build/types/utils/module.d.ts +3 -0
  89. package/build/types/utils/module.d.ts.map +1 -0
  90. package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
  91. package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
  92. package/build/types/utils/sql.d.ts.map +1 -1
  93. package/build/types/utils/tunnelServer.d.ts.map +1 -1
  94. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  95. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { asNumber, asString, isReadableStream, type StreamedModelCallResult, sum, tapModelCallStream } from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return Object.fromEntries(\n Object.entries(answers).map(([id, answer]) => {\n if (!isObjectLike(answer)) {\n return [id, answer];\n }\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return [id, { ...answer, confidence, legend }];\n }),\n );\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgFA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IAAI,IAA4B;AAIzE,MAAM,uCAAuB,IAAI,IAAsB;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,+CAA+B,IAAI,IAAsB;CAC7D;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,MAAoC;CACnE,IAAI,CAAC,qBAAqB,IAAI,KAAK,IAAI,GACrC;CAEF,MAAM,SAAS,SAAS,KAAK,MAAM,MAAM;CACzC,IAAI,QACF,qBAAqB,MAAM;AAE/B;;;;;;;;AASA,SAAgB,q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cAAc,KAAK,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC;AAEjD;;AAGA,SAAS,0BAA0B,cAA4D;CAE7F,QADiB,MAAM,QAAQ,YAAY,IAAI,eAAe,CAAC,YAAY,EAAA,CAC3D,SAAQ,YAAW;EACjC,MAAM,UAAU,SAAS,aAAa,OAAO,IAAI,QAAQ,UAAU,OAAO;EAC1E,OAAO,UAAU,CAAC;GAAE,MAAM;GAAiB;EAAQ,CAAC,IAAI,CAAC;CAC3D,CAAC;AACH;AAEA,SAAS,4BAA4B,OAA6E;CAChH,MAAM,aAA0D,CAAC;CAKjE,MAAM,eAAe,0BAA0B,MAAM,YAAY;CACjE,IAAI,aAAa,QACf,WAAW,8BAA8B,UAAU,YAAY;CAKjE,MAAM,WAAW,MAAM,YAAY,MAAM;CACzC,IAAI,CAAC,gBAAgB,QAAQ,GAC3B,WAAW,yBAAyB,UAAU,QAAQ;CAGxD,OAAO;AACT"}
1
+ {"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_EXTRACT,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { toExtractAnswers, toExtractFields, toExtractState } from './extract';\nimport {\n asNumber,\n asString,\n isReadableStream,\n mapObjectValues,\n type StreamedModelCallResult,\n sum,\n tapModelCallStream,\n} from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide'\n | 'experimental_extract';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n case 'experimental_extract':\n return startGenAiSpan('extract', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n {\n ...toExtractState(event.state).request,\n fields: toExtractFields(event.fields),\n reference_date: event.referenceDate,\n },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason, data.event);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n event: Record<string, unknown>,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n if (type === 'experimental_extract') {\n return isObjectLike(result.answers)\n ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }])\n : undefined;\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return mapObjectValues(answers, (answer, id) => {\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return { ...answer, confidence, legend };\n });\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0FA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IAAI,IAA4B;AAIzE,MAAM,uCAAuB,IAAI,IAAsB;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,+CAA+B,IAAI,IAAsB;CAC7D;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,MAAoC;CACnE,IAAI,CAAC,qBAAqB,IAAI,KAAK,IAAI,GACrC;CAEF,MAAM,SAAS,SAAS,KAAK,MAAM,MAAM;CACzC,IAAI,QACF,qBAAqB,MAAM;AAE/B;;;;;;;;AASA,SAAgB,qBAAqB,QAAsB;CACzD,oBAAoB,OAAO,MAAM;CACjC,yBAAyB,OAAO,MAA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A,eACA,eACA,UAAU,OACD;CACT,IAAI,OAAO,sBAAsB,WAC/B,OAAO;CAET,IAAI,SACF,OAAO,OAAO,kBAAkB,YAAY,gBAAgB;CAE9D,IAAI,OAAO,kBAAkB,WAC3B,OAAO;CAET,OAAO,kBAAkB;AAC3B;;AAGA,SAAS,gBAAgB,OAAyB;CAChD,OACE,UAAU,KAAA,KACV,UAAU,MACT,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,UAC/B,cAAc,KAAK,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC;AAEjD;;AAGA,SAAS,0BAA0B,cAA4D;CAE7F,QADiB,MAAM,QAAQ,YAAY,IAAI,eAAe,CAAC,YAAY,EAAA,CAC3D,SAAQ,YAAW;EACjC,MAAM,UAAU,SAAS,aAAa,OAAO,IAAI,QAAQ,UAAU,OAAO;EAC1E,OAAO,UAAU,CAAC;GAAE,MAAM;GAAiB;EAAQ,CAAC,IAAI,CAAC;CAC3D,CAAC;AACH;AAEA,SAAS,4BAA4B,OAA6E;CAChH,MAAM,aAA0D,CAAC;CAKjE,MAAM,eAAe,0BAA0B,MAAM,YAAY;CACjE,IAAI,aAAa,QACf,WAAW,8BAA8B,UAAU,YAAY;CAKjE,MAAM,WAAW,MAAM,YAAY,MAAM;CACzC,IAAI,CAAC,gBAAgB,QAAQ,GAC3B,WAAW,yBAAyB,UAAU,QAAQ;CAGxD,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { DEBUG_BUILD } from "../debug-build.js";
2
2
  import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
3
- import { _INTERNAL_captureLog, debug, isObjectLike } from "@sentry/core";
3
+ import { captureLogEvent, debug, isObjectLike } from "@sentry/core";
4
4
  // src/integrations/winston.ts
5
5
  const DEFAULT_CAPTURED_LEVELS = [
6
6
  "trace",
@@ -56,7 +56,7 @@ function createSentryWinstonTransport(TransportClass, sentryWinstonOptions) {
56
56
  const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol];
57
57
  const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol];
58
58
  const logSeverityLevel = customLevel ?? winstonLogLevel ?? "info";
59
- if (this._levels.has(logSeverityLevel)) _INTERNAL_captureLog({
59
+ if (this._levels.has(logSeverityLevel)) captureLogEvent({
60
60
  level: logSeverityLevel,
61
61
  message,
62
62
  attributes: {
@@ -1 +1 @@
1
- {"version":3,"file":"winston.js","names":[],"sources":["../../../src/integrations/winston.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\n/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type { LogSeverityLevel } from '@sentry/core';\nimport { _INTERNAL_captureLog, debug, isObjectLike } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst DEFAULT_CAPTURED_LEVELS: Array<LogSeverityLevel> = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n// See: https://github.com/winstonjs/triple-beam\nconst LEVEL_SYMBOL = Symbol.for('level');\nconst MESSAGE_SYMBOL = Symbol.for('message');\nconst SPLAT_SYMBOL = Symbol.for('splat');\n\n/**\n * Options for the Sentry Winston transport.\n */\ninterface WinstonTransportOptions {\n /**\n * Use this option to filter which levels should be captured. By default, all levels are captured.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * // Only capture error and warn logs\n * levels: ['error', 'warn'],\n * });\n * ```\n */\n levels?: Array<LogSeverityLevel>;\n\n /**\n * Use this option to map custom levels to Sentry log severity levels.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * customLevelMap: {\n * myCustomLevel: 'info',\n * customError: 'error',\n * },\n * });\n * ```\n */\n customLevelMap?: Record<string, LogSeverityLevel>;\n}\n\n/**\n * Creates a new Sentry Winston transport that fowards logs to Sentry.\n *\n * Supports Winston 3.x.x.\n *\n * @param TransportClass - The Winston transport class to extend.\n * @returns The extended transport class.\n *\n * @example\n * ```ts\n * const winston = require('winston');\n * const Transport = require('winston-transport');\n *\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);\n *\n * const logger = winston.createLogger({\n * transports: [new SentryWinstonTransport()],\n * });\n * ```\n */\nexport function createSentryWinstonTransport<TransportStreamInstance extends object>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TransportClass: new (options?: any) => TransportStreamInstance,\n sentryWinstonOptions?: WinstonTransportOptions,\n): typeof TransportClass {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n class SentryWinstonTransport extends TransportClass {\n private _levels: Set<LogSeverityLevel>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options?: any) {\n super(options);\n this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);\n }\n\n /**\n * Forwards a winston log to the Sentry SDK.\n */\n public log(info: unknown, callback: () => void): void {\n try {\n setImmediate(() => {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n this.emit('logged', info);\n });\n\n if (!isObjectLike(info)) {\n return;\n }\n\n const levelFromSymbol = info[LEVEL_SYMBOL];\n\n // See: https://github.com/winstonjs/winston?tab=readme-ov-file#streams-objectmode-and-info-objects\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, message, timestamp, ...attributes } = info;\n // Remove all symbols from the remaining attributes\n attributes[LEVEL_SYMBOL] = undefined;\n attributes[MESSAGE_SYMBOL] = undefined;\n attributes[SPLAT_SYMBOL] = undefined;\n\n const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol as string];\n const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol as string];\n const logSeverityLevel = customLevel ?? winstonLogLevel ?? 'info';\n\n if (this._levels.has(logSeverityLevel)) {\n _INTERNAL_captureLog({\n level: logSeverityLevel,\n message: message as string,\n attributes: {\n ...attributes,\n [SENTRY_ORIGIN]: 'auto.log.winston',\n },\n });\n } else if (!customLevel && !winstonLogLevel) {\n DEBUG_BUILD &&\n debug.log(\n `Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the \"customLevelMap\" option of the Sentry Winston transport.`,\n );\n }\n } catch {\n // do nothing\n }\n\n if (callback) {\n callback();\n }\n }\n }\n\n return SentryWinstonTransport as typeof TransportClass;\n}\n\n// npm\n// {\n// error: 0,\n// warn: 1,\n// info: 2,\n// http: 3,\n// verbose: 4,\n// debug: 5,\n// silly: 6\n// }\n//\n// syslog\n// {\n// emerg: 0,\n// alert: 1,\n// crit: 2,\n// error: 3,\n// warning: 4,\n// notice: 5,\n// info: 6,\n// debug: 7,\n// }\nconst WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record<string, LogSeverityLevel> = {\n // npm\n silly: 'trace',\n // npm and syslog\n debug: 'debug',\n // npm\n verbose: 'debug',\n // npm\n http: 'debug',\n // npm and syslog\n info: 'info',\n // syslog\n notice: 'info',\n // npm\n warn: 'warn',\n // syslog\n warning: 'warn',\n // npm and syslog\n error: 'error',\n // syslog\n emerg: 'fatal',\n // syslog\n alert: 'fatal',\n // syslog\n crit: 'fatal',\n};\n"],"mappings":";;;;AAMA,MAAM,0BAAmD;CAAC;CAAS;CAAS;CAAQ;CAAQ;CAAS;AAAO;AAG5G,MAAM,eAAe,OAAO,IAAI,OAAO;AACvC,MAAM,iBAAiB,OAAO,IAAI,SAAS;AAC3C,MAAM,eAAe,OAAO,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;;AAuDvC,SAAgB,6BAEd,gBACA,sBACuB;CAEvB,MAAM,+BAA+B,eAAe;EAG3C,YAAY,SAAe;GAChC,MAAM,OAAO;GACb,KAAK,UAAU,IAAI,IAAI,sBAAsB,UAAU,uBAAuB;EAChF;;;;EAKO,IAAI,MAAe,UAA4B;GACpD,IAAI;IACF,mBAAmB;KAEjB,KAAK,KAAK,UAAU,IAAI;IAC1B,CAAC;IAED,IAAI,CAAC,aAAa,IAAI,GACpB;IAGF,MAAM,kBAAkB,KAAK;IAI7B,MAAM,EAAE,OAAO,SAAS,WAAW,GAAG,eAAe;IAErD,WAAW,gBAAgB,KAAA;IAC3B,WAAW,kBAAkB,KAAA;IAC7B,WAAW,gBAAgB,KAAA;IAE3B,MAAM,cAAc,sBAAsB,iBAAiB;IAC3D,MAAM,kBAAkB,wCAAwC;IAChE,MAAM,mBAAmB,eAAe,mBAAmB;IAE3D,IAAI,KAAK,QAAQ,IAAI,gBAAgB,GACnC,qBAAqB;KACnB,OAAO;KACE;KACT,YAAY;MACV,GAAG;OACF,gBAAgB;KACnB;IACF,CAAC;SACI,IAAI,CAAC,eAAe,CAAC,iBAC1B,eACE,MAAM,IACJ,qBAAqB,gBAAgB,yCAAyC,gBAAgB,iEAChG;GAEN,QAAQ,CAER;GAEA,IAAI,UACF,SAAS;EAEb;CACF;CAEA,OAAO;AACT;AAwBA,MAAM,0CAA4E;CAEhF,OAAO;CAEP,OAAO;CAEP,SAAS;CAET,MAAM;CAEN,MAAM;CAEN,QAAQ;CAER,MAAM;CAEN,SAAS;CAET,OAAO;CAEP,OAAO;CAEP,OAAO;CAEP,MAAM;AACR"}
1
+ {"version":3,"file":"winston.js","names":[],"sources":["../../../src/integrations/winston.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\n/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type { LogSeverityLevel } from '@sentry/core';\nimport { captureLogEvent, debug, isObjectLike } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst DEFAULT_CAPTURED_LEVELS: Array<LogSeverityLevel> = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n// See: https://github.com/winstonjs/triple-beam\nconst LEVEL_SYMBOL = Symbol.for('level');\nconst MESSAGE_SYMBOL = Symbol.for('message');\nconst SPLAT_SYMBOL = Symbol.for('splat');\n\n/**\n * Options for the Sentry Winston transport.\n */\ninterface WinstonTransportOptions {\n /**\n * Use this option to filter which levels should be captured. By default, all levels are captured.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * // Only capture error and warn logs\n * levels: ['error', 'warn'],\n * });\n * ```\n */\n levels?: Array<LogSeverityLevel>;\n\n /**\n * Use this option to map custom levels to Sentry log severity levels.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * customLevelMap: {\n * myCustomLevel: 'info',\n * customError: 'error',\n * },\n * });\n * ```\n */\n customLevelMap?: Record<string, LogSeverityLevel>;\n}\n\n/**\n * Creates a new Sentry Winston transport that fowards logs to Sentry.\n *\n * Supports Winston 3.x.x.\n *\n * @param TransportClass - The Winston transport class to extend.\n * @returns The extended transport class.\n *\n * @example\n * ```ts\n * const winston = require('winston');\n * const Transport = require('winston-transport');\n *\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);\n *\n * const logger = winston.createLogger({\n * transports: [new SentryWinstonTransport()],\n * });\n * ```\n */\nexport function createSentryWinstonTransport<TransportStreamInstance extends object>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TransportClass: new (options?: any) => TransportStreamInstance,\n sentryWinstonOptions?: WinstonTransportOptions,\n): typeof TransportClass {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n class SentryWinstonTransport extends TransportClass {\n private _levels: Set<LogSeverityLevel>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options?: any) {\n super(options);\n this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);\n }\n\n /**\n * Forwards a winston log to the Sentry SDK.\n */\n public log(info: unknown, callback: () => void): void {\n try {\n setImmediate(() => {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n this.emit('logged', info);\n });\n\n if (!isObjectLike(info)) {\n return;\n }\n\n const levelFromSymbol = info[LEVEL_SYMBOL];\n\n // See: https://github.com/winstonjs/winston?tab=readme-ov-file#streams-objectmode-and-info-objects\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, message, timestamp, ...attributes } = info;\n // Remove all symbols from the remaining attributes\n attributes[LEVEL_SYMBOL] = undefined;\n attributes[MESSAGE_SYMBOL] = undefined;\n attributes[SPLAT_SYMBOL] = undefined;\n\n const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol as string];\n const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol as string];\n const logSeverityLevel = customLevel ?? winstonLogLevel ?? 'info';\n\n if (this._levels.has(logSeverityLevel)) {\n captureLogEvent({\n level: logSeverityLevel,\n message: message as string,\n attributes: {\n ...attributes,\n [SENTRY_ORIGIN]: 'auto.log.winston',\n },\n });\n } else if (!customLevel && !winstonLogLevel) {\n DEBUG_BUILD &&\n debug.log(\n `Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the \"customLevelMap\" option of the Sentry Winston transport.`,\n );\n }\n } catch {\n // do nothing\n }\n\n if (callback) {\n callback();\n }\n }\n }\n\n return SentryWinstonTransport as typeof TransportClass;\n}\n\n// npm\n// {\n// error: 0,\n// warn: 1,\n// info: 2,\n// http: 3,\n// verbose: 4,\n// debug: 5,\n// silly: 6\n// }\n//\n// syslog\n// {\n// emerg: 0,\n// alert: 1,\n// crit: 2,\n// error: 3,\n// warning: 4,\n// notice: 5,\n// info: 6,\n// debug: 7,\n// }\nconst WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record<string, LogSeverityLevel> = {\n // npm\n silly: 'trace',\n // npm and syslog\n debug: 'debug',\n // npm\n verbose: 'debug',\n // npm\n http: 'debug',\n // npm and syslog\n info: 'info',\n // syslog\n notice: 'info',\n // npm\n warn: 'warn',\n // syslog\n warning: 'warn',\n // npm and syslog\n error: 'error',\n // syslog\n emerg: 'fatal',\n // syslog\n alert: 'fatal',\n // syslog\n crit: 'fatal',\n};\n"],"m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,7 @@ const honoConfig = [{
3
3
  channelName: "context",
4
4
  module: {
5
5
  name: "hono",
6
- versionRange: ">=4.0.0 <5",
6
+ versionRange: ">=4.0.0 <6",
7
7
  filePath: /^dist\/(?:cjs\/)?context\.js$/
8
8
  },
9
9
  functionQuery: { className: "Context" }
@@ -11,7 +11,7 @@ const honoConfig = [{
11
11
  channelName: "request",
12
12
  module: {
13
13
  name: "hono",
14
- versionRange: ">=4.0.0 <5",
14
+ versionRange: ">=4.0.0 <6",
15
15
  filePath: /^dist\/(?:cjs\/)?hono-base\.js$/
16
16
  },
17
17
  astQuery: "PropertyDefinition[key.name='request'] > ArrowFunctionExpression",
@@ -1 +1 @@
1
- {"version":3,"file":"hono.js","names":[],"sources":["../../../../src/orchestrion/config/hono.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Hono is hooked through per-request internals only — never at module scope — which is what lets the\n// same config run on Cloudflare Workers, where workerd forbids `diagnostics_channel` at module scope.\n// The subscribers live in `honoIntegration`.\nconst honoInstrumentationConfig: InstrumentationConfig[] = [\n {\n // `new Context()` runs once per request: where the Sentry middleware is injected and matched\n // middleware handlers are wrapped for spans.\n // TODO(v12): Raise the minimum Hono version to 4.4.9, here and in the `@sentry/hono` peer range.\n // Before 4.4.9, Hono passes `matchResult` to `new HonoRequest()`, so this hook does nothing.\n channelName: 'context',\n module: { name: 'hono', versionRange: '>=4.0.0 <5', filePath: /^dist\\/(?:cjs\\/)?context\\.js$/ },\n functionQuery: { className: 'Context' },\n },\n {\n // `app.request(...)` — Hono's internal dispatch for sub-app-to-sub-app fetches. A class-field\n // arrow, hence `astQuery` instead of `methodName`.\n channelName: 'request',\n module: { name: 'hono', versionRange: '>=4.0.0 <5', filePath: /^dist\\/(?:cjs\\/)?hono-base\\.js$/ },\n astQuery: \"PropertyDefinition[key.name='request'] > ArrowFunctionExpression\",\n functionQuery: { kind: 'Auto' },\n },\n];\n\nexport const honoConfig = honoInstrumentationConfig satisfies InstrumentationConfig[];\n\nexport const honoModuleNames = getModuleNames(honoConfig);\n\nexport const honoChannels = {\n HONO_CONTEXT: 'orchestrion:hono:context',\n HONO_REQUEST: 'orchestrion:hono:request',\n} as const;\n"],"mappings":";AA0BA,MAAa,aAAa,CAnBxB;CAKE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAgC;CAC9F,eAAe,EAAE,WAAW,UAAU;AACxC,GACA;CAGE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAkC;CAChG,UAAU;CACV,eAAe,EAAE,MAAM,OAAO;AAChC,CAGwB;AAE1B,MAAa,kBAAkB,eAAe,UAAU;AAExD,MAAa,eAAe;CAC1B,cAAc;CACd,cAAc;AAChB"}
1
+ {"version":3,"file":"hono.js","names":[],"sources":["../../../../src/orchestrion/config/hono.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Hono is hooked through per-request internals only — never at module scope — which is what lets the\n// same config run on Cloudflare Workers, where workerd forbids `diagnostics_channel` at module scope.\n// The subscribers live in `honoIntegration`.\nconst honoInstrumentationConfig: InstrumentationConfig[] = [\n {\n // `new Context()` runs once per request: where the Sentry middleware is injected and matched\n // middleware handlers are wrapped for spans.\n // TODO(v12): Raise the minimum Hono version to 4.4.9, here and in the `@sentry/hono` peer range.\n // Before 4.4.9, Hono passes `matchResult` to `new HonoRequest()`, so this hook does nothing.\n channelName: 'context',\n module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\\/(?:cjs\\/)?context\\.js$/ },\n functionQuery: { className: 'Context' },\n },\n {\n // `app.request(...)` — Hono's internal dispatch for sub-app-to-sub-app fetches. A class-field\n // arrow, hence `astQuery` instead of `methodName`.\n channelName: 'request',\n module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\\/(?:cjs\\/)?hono-base\\.js$/ },\n astQuery: \"PropertyDefinition[key.name='request'] > ArrowFunctionExpression\",\n functionQuery: { kind: 'Auto' },\n },\n];\n\nexport const honoConfig = honoInstrumentationConfig satisfies InstrumentationConfig[];\n\nexport const honoModuleNames = getModuleNames(honoConfig);\n\nexport const honoChannels = {\n HONO_CONTEXT: 'orchestrion:hono:context',\n HONO_REQUEST: 'orchestrion:hono:request',\n} as const;\n"],"mappings":";AA0BA,MAAa,aAAa,CAnBxB;CAKE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAgC;CAC9F,eAAe,EAAE,WAAW,UAAU;AACxC,GACA;CAGE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAkC;CAChG,UAAU;CACV,eAAe,EAAE,MAAM,OAAO;AAChC,CAGwB;AAE1B,MAAa,kBAAkB,eAAe,UAAU;AAExD,MAAa,eAAe;CAC1B,cAAc;CACd,cAAc;AAChB"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.17.0","sideEffects":false}
1
+ {"type":"module","version":"11.18.0","sideEffects":false}
@@ -0,0 +1,87 @@
1
+ // src/utils/installedModules.ts
2
+ const NODE_MODULES = "/node_modules/";
3
+ /**
4
+ * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact
5
+ * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise.
6
+ */
7
+ function collectInstalledModules({ readFile, entryPath, cwd, loadedFiles = [] }) {
8
+ const read = (dir) => {
9
+ try {
10
+ return JSON.parse(readFile(join(dir, "package.json")) || "null") || void 0;
11
+ } catch {
12
+ return;
13
+ }
14
+ };
15
+ const entryDir = entryPath && dirname(toPosix(entryPath));
16
+ const cwdDir = cwd && toPosix(cwd);
17
+ const appRoot = findAppRoot(read, entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir]);
18
+ const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir) ? entryDir : appRoot || entryDir || cwdDir;
19
+ const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map((dir) => join(dir, "node_modules")) : [];
20
+ const resolve = (name) => {
21
+ for (const dir of nodeModulesDirs) {
22
+ const version = read(join(dir, name))?.version;
23
+ if (version) return version;
24
+ }
25
+ };
26
+ const pkg = appRoot ? read(appRoot) : void 0;
27
+ const declared = {
28
+ ...pkg?.dependencies,
29
+ ...pkg?.devDependencies
30
+ };
31
+ const installed = {};
32
+ const seen = /* @__PURE__ */ new Set();
33
+ for (const file of loadedFiles) {
34
+ const path = toPosix(file);
35
+ const start = path.lastIndexOf(NODE_MODULES) + 14;
36
+ const [first = "", second] = path.slice(start).split("/");
37
+ const name = first.startsWith("@") ? `${first}/${second}` : first;
38
+ const dir = path.slice(0, start) + name;
39
+ if (start < 14 || seen.has(dir) || !nodeModulesDirs.some((d) => isIn(path, d))) continue;
40
+ seen.add(dir);
41
+ const version = read(dir)?.version;
42
+ if (version && installed[name] !== version) installed[name] = name in installed && resolve(name) || installed[name] || version;
43
+ }
44
+ for (const name of Object.keys(declared)) {
45
+ const version = resolve(name);
46
+ if (version) installed[name] = version;
47
+ }
48
+ return {
49
+ ...declared,
50
+ ...installed
51
+ };
52
+ }
53
+ /** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */
54
+ function findAppRoot(read, startDirs) {
55
+ for (const startDir of startDirs) {
56
+ const root = startDir && !inNodeModules(startDir) ? ancestors(startDir).find((dir) => {
57
+ const pkg = read(dir);
58
+ return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies);
59
+ }) : void 0;
60
+ if (root) return root;
61
+ }
62
+ }
63
+ function inNodeModules(dir) {
64
+ return `${dir}/`.includes(NODE_MODULES);
65
+ }
66
+ /** `dir` and its parents, up to the root. */
67
+ function ancestors(dir) {
68
+ const dirs = [dir];
69
+ for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) dirs.push(parent);
70
+ return dirs;
71
+ }
72
+ function dirname(path) {
73
+ const index = path.lastIndexOf("/");
74
+ return index > 0 ? path.slice(0, index) : index === 0 ? "/" : path;
75
+ }
76
+ function join(dir, name) {
77
+ return dir.endsWith("/") ? dir + name : `${dir}/${name}`;
78
+ }
79
+ function isIn(path, dir) {
80
+ return path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`);
81
+ }
82
+ function toPosix(path) {
83
+ return path.replace(/\\/g, "/");
84
+ }
85
+ export { collectInstalledModules };
86
+
87
+ //# sourceMappingURL=installedModules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installedModules.js","names":[],"sources":["../../../src/utils/installedModules.ts"],"sourcesContent":["type ModuleInfo = Record<string, string>;\ninterface PackageJson {\n name?: string;\n version?: string;\n dependencies?: ModuleInfo;\n devDependencies?: ModuleInfo;\n}\n\nconst NODE_MODULES = '/node_modules/';\n\n/**\n * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact\n * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise.\n */\nexport function collectInstalledModules({\n readFile,\n entryPath,\n cwd,\n loadedFiles = [],\n}: {\n readFile: (path: string) => string | undefined;\n entryPath?: string;\n cwd?: string;\n /**\n * Paths of files the process has already loaded, such as the keys of the CommonJS module cache. Packages these files\n * belong to are added too, which covers transitive dependencies that are not in `package.json`.\n */\n loadedFiles?: string[];\n}): ModuleInfo {\n const read = (dir: string): PackageJson | undefined => {\n try {\n return JSON.parse(readFile(join(dir, 'package.json')) || 'null') || undefined;\n } catch {\n return undefined;\n }\n };\n\n const entryDir = entryPath && dirname(toPosix(entryPath));\n const cwdDir = cwd && toPosix(cwd);\n // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime.\n const appRoot = findAppRoot(\n read,\n entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir],\n );\n\n const resolveFrom =\n entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir)\n ? entryDir\n : appRoot || entryDir || cwdDir;\n const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : [];\n const resolve = (name: string): string | undefined => {\n for (const dir of nodeModulesDirs) {\n const version = read(join(dir, name))?.version;\n if (version) {\n return version;\n }\n }\n return undefined;\n };\n\n const pkg = appRoot ? read(appRoot) : undefined;\n const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies };\n const installed: ModuleInfo = {};\n const seen = new Set<string>();\n\n for (const file of loadedFiles) {\n const path = toPosix(file);\n const start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length;\n const [first = '', second] = path.slice(start).split('/');\n const name = first.startsWith('@') ? `${first}/${second}` : first;\n const dir = path.slice(0, start) + name;\n if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) {\n continue;\n }\n seen.add(dir);\n const version = read(dir)?.version;\n if (version && installed[name] !== version) {\n // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves.\n installed[name] = (name in installed && resolve(name)) || installed[name] || version;\n }\n }\n\n for (const name of Object.keys(declared)) {\n const version = resolve(name);\n if (version) {\n installed[name] = version;\n }\n }\n\n return { ...declared, ...installed };\n}\n\n/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `\"type\"`. */\nfunction findAppRoot(\n read: (dir: string) => PackageJson | undefined,\n startDirs: Array<string | undefined>,\n): string | undefined {\n for (const startDir of startDirs) {\n const root =\n startDir && !inNodeModules(startDir)\n ? ancestors(startDir).find(dir => {\n const pkg = read(dir);\n return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies);\n })\n : undefined;\n if (root) {\n return root;\n }\n }\n return undefined;\n}\n\nfunction inNodeModules(dir: string): boolean {\n return `${dir}/`.includes(NODE_MODULES);\n}\n\n/** `dir` and its parents, up to the root. */\nfunction ancestors(dir: string): string[] {\n const dirs = [dir];\n for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) {\n dirs.push(parent);\n }\n return dirs;\n}\n\n// Minimal POSIX helpers: all paths are converted with `toPosix` first.\nfunction dirname(path: string): string {\n const index = path.lastIndexOf('/');\n return index > 0 ? path.slice(0, index) : index === 0 ? '/' : path;\n}\n\nfunction join(dir: string, name: string): string {\n return dir.endsWith('/') ? dir + name : `${dir}/${name}`;\n}\n\nfunction isIn(path: string, dir: string): boolean {\n return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`);\n}\n\nfunction toPosix(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n"],"mappings":";AAQA,MAAM,eAAe;;;;;AAMrB,SAAgB,wBAAwB,EACtC,UACA,WACA,KACA,cAAc,CAAC,KAUF;CACb,MAAM,QAAQ,QAAyC;EACrD,IAAI;GACF,OAAO,KAAK,MAAM,SAAS,KAAK,KAAK,cAAc,CAAC,KAAK,MAAM,KAAK,KAAA;EACtE,QAAQ;GACN;EACF;CACF;CAEA,MAAM,WAAW,aAAa,QAAQ,QAAQ,SAAS,CAAC;CACxD,MAAM,SAAS,OAAO,QAAQ,GAAG;CAEjC,MAAM,UAAU,YACd,MACA,YAAY,UAAU,CAAC,KAAK,UAAU,MAAM,IAAI,CAAC,QAAQ,QAAQ,IAAI,CAAC,UAAU,MAAM,CACxF;CAEA,MAAM,cACJ,YAAY,WAAW,KAAK,UAAU,OAAO,KAAK,CAAC,cAAc,QAAQ,IACrE,WACA,WAAW,YAAY;CAC7B,MAAM,kBAAkB,cAAc,UAAU,WAAW,CAAC,CAAC,KAAI,QAAO,KAAK,KAAK,cAAc,CAAC,IAAI,CAAC;CACtG,MAAM,WAAW,SAAqC;EACpD,KAAK,MAAM,OAAO,iBAAiB;GACjC,MAAM,UAAU,KAAK,KAAK,KAAK,IAAI,CAAC,CAAC,EAAE;GACvC,IAAI,SACF,OAAO;EAEX;CAEF;CAEA,MAAM,MAAM,UAAU,KAAK,OAAO,IAAI,KAAA;CACtC,MAAM,WAAuB;EAAE,GAAG,KAAK;EAAc,GAAG,KAAK;CAAgB;CAC7E,MAAM,YAA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S,QAAQ,GAAG,GAAG,WAAW,KAAK,KAAK,SAAS,IAAI,SAAS,QAAQ,MAAM,GACvF,KAAK,KAAK,MAAM;CAElB,OAAO;AACT;AAGA,SAAS,QAAQ,MAAsB;CACrC,MAAM,QAAQ,KAAK,YAAY,GAAG;CAClC,OAAO,QAAQ,IAAI,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,IAAI,MAAM;AAChE;AAEA,SAAS,KAAK,KAAa,MAAsB;CAC/C,OAAO,IAAI,SAAS,GAAG,IAAI,MAAM,OAAO,GAAG,IAAI,GAAG;AACpD;AAEA,SAAS,KAAK,MAAc,KAAsB;CAChD,OAAO,SAAS,OAAO,KAAK,WAAW,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,IAAI,EAAE;AAC5E;AAEA,SAAS,QAAQ,MAAsB;CACrC,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC"}
@@ -0,0 +1,29 @@
1
+ import { dirname } from "@sentry/core";
2
+ import { posix, sep } from "node:path";
3
+ // src/utils/module.ts
4
+ /** normalizes Windows paths */
5
+ function normalizeWindowsPath(path) {
6
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
7
+ }
8
+ /** Creates a function that gets the module name from a filename */
9
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
10
+ const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
11
+ return (filename) => {
12
+ if (!filename) return;
13
+ const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
14
+ let { dir, base: file, ext } = posix.parse(normalizedFilename);
15
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs") file = file.slice(0, ext.length * -1);
16
+ const decodedFile = decodeURIComponent(file);
17
+ if (!dir) dir = ".";
18
+ const n = dir.lastIndexOf("/node_modules");
19
+ if (n > -1) return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`;
20
+ if (dir.startsWith(normalizedBase)) {
21
+ const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
22
+ return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
23
+ }
24
+ return decodedFile;
25
+ };
26
+ }
27
+ export { createGetModuleFromFilename };
28
+
29
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","names":[],"sources":["../../../src/utils/module.ts"],"sourcesContent":["import { posix, sep } from 'node:path';\nimport { dirname } from '@sentry/core';\n\n/** normalizes Windows paths */\nfunction normalizeWindowsPath(path: string): string {\n return path\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/'); // replace all `\\` instances with `/`\n}\n\n/** Creates a function that gets the module name from a filename */\nexport function createGetModuleFromFilename(\n basePath: string = process.argv[1] ? dirname(process.argv[1]) : process.cwd(),\n isWindows: boolean = sep === '\\\\',\n): (filename: string | undefined) => string | undefined {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n\n return (filename: string | undefined) => {\n if (!filename) {\n return;\n }\n\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n\n // eslint-disable-next-line prefer-const\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n\n if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {\n file = file.slice(0, ext.length * -1);\n }\n\n // The file name might be URI-encoded which we want to decode to\n // the original file name.\n const decodedFile = decodeURIComponent(file);\n\n if (!dir) {\n // No dirname whatsoever\n dir = '.';\n }\n\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) {\n return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n }\n\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n\n return decodedFile;\n };\n}\n"],"mappings":";;;;AAIA,SAAS,qBAAqB,MAAsB;CAClD,OAAO,KACJ,QAAQ,WAAW,EAAE,CAAC,CACtB,QAAQ,OAAO,GAAG;AACvB;;AAGA,SAAgB,4BACd,WAAmB,QAAQ,KAAK,KAAK,QAAQ,QAAQ,KAAK,EAAE,IAAI,QAAQ,IAAI,GAC5E,YAAqB,QAAQ,MACyB;CACtD,MAAM,iBAAiB,YAAY,qBAAqB,QAAQ,IAAI;CAEpE,QAAQ,aAAiC;EACvC,IAAI,CAAC,UACH;EAGF,MAAM,qBAAqB,YAAY,qBAAqB,QAAQ,IAAI;EAGxE,IAAI,EAAE,KAAK,MAAM,MAAM,QAAQ,MAAM,MAAM,kBAAkB;EAE7D,IAAI,QAAQ,SAAS,QAAQ,UAAU,QAAQ,QAC7C,OAAO,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE;EAKtC,MAAM,cAAc,mBAAmB,IAAI;EAE3C,IAAI,CAAC,KAEH,MAAM;EAGR,MAAM,IAAI,IAAI,YAAY,eAAe;EACzC,IAAI,IAAI,IACN,OAAO,GAAG,IAAI,MAAM,IAAI,EAAE,CAAC,CAAC,QAAQ,OAAO,GAAG,EAAE,GAAG;EAKrD,IAAI,IAAI,WAAW,cAAc,GAAG;GAClC,MAAM,aAAa,IAAI,MAAM,eAAe,SAAS,CAAC,CAAC,CAAC,QAAQ,OAAO,GAAG;GAC1E,OAAO,aAAa,GAAG,WAAW,GAAG,gBAAgB;EACvD;EAEA,OAAO;CACT;AACF"}
@@ -0,0 +1,49 @@
1
+ import { DEBUG_BUILD } from "../debug-build.js";
2
+ import { debug, getTraceServerTimingHeader, isSharedCacheable } from "@sentry/core";
3
+ // src/utils/serverTimingTraceHeader.ts
4
+ const SERVER_TIMING_HEADER = "server-timing";
5
+ const enabledClients = /* @__PURE__ */ new WeakSet();
6
+ /**
7
+ * Sends the trace of the request in a `Server-Timing` header of the document responses that
8
+ * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The
9
+ * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`
10
+ * handlers. Framework SDKs turn it on; it is off by default.
11
+ */
12
+ function addServerTimingTraceHeader(client) {
13
+ enabledClients.add(client);
14
+ }
15
+ /**
16
+ * Adds the trace of the current context to the `Server-Timing` header of a document response that
17
+ * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling
18
+ * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of
19
+ * the app is left alone.
20
+ *
21
+ * A `fetch` response has immutable headers, so it is copied then.
22
+ */
23
+ function withServerTimingTraceHeader(client, response) {
24
+ if (!response || !enabledClients.has(client)) return response;
25
+ try {
26
+ const headers = response.headers;
27
+ const getHeader = (name) => headers.get(name) ?? void 0;
28
+ if (!getHeader("content-type")?.toLowerCase().startsWith("text/html") || isSharedCacheable(getHeader)) return response;
29
+ const existingValue = getHeader(SERVER_TIMING_HEADER);
30
+ if (existingValue?.includes("sentry-trace")) return response;
31
+ const traceHeader = getTraceServerTimingHeader();
32
+ if (!traceHeader) return response;
33
+ const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;
34
+ try {
35
+ headers.set(SERVER_TIMING_HEADER, value);
36
+ return response;
37
+ } catch {
38
+ const copy = new Response(response.body, response);
39
+ copy.headers.set(SERVER_TIMING_HEADER, value);
40
+ return copy;
41
+ }
42
+ } catch (e) {
43
+ DEBUG_BUILD && debug.warn("Failed to add the trace to the Server-Timing header", e);
44
+ return response;
45
+ }
46
+ }
47
+ export { addServerTimingTraceHeader, withServerTimingTraceHeader };
48
+
49
+ //# sourceMappingURL=serverTimingTraceHeader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverTimingTraceHeader.js","names":[],"sources":["../../../src/utils/serverTimingTraceHeader.ts"],"sourcesContent":["import type { Client } from '@sentry/core';\nimport { debug, getTraceServerTimingHeader, isSharedCacheable } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst SERVER_TIMING_HEADER = 'server-timing';\n\nconst enabledClients = new WeakSet<Client>();\n\n/**\n * Sends the trace of the request in a `Server-Timing` header of the document responses that\n * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The\n * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`\n * handlers. Framework SDKs turn it on; it is off by default.\n */\nexport function addServerTimingTraceHeader(client: Client): void {\n enabledClients.add(client);\n}\n\n/**\n * Adds the trace of the current context to the `Server-Timing` header of a document response that\n * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling\n * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of\n * the app is left alone.\n *\n * A `fetch` response has immutable headers, so it is copied then.\n */\nexport function withServerTimingTraceHeader<R extends Response | undefined>(client: Client, response: R): R {\n if (!response || !enabledClients.has(client)) {\n return response;\n }\n\n try {\n const headers = response.headers;\n const getHeader = (name: string): string | undefined => headers.get(name) ?? undefined;\n if (!getHeader('content-type')?.toLowerCase().startsWith('text/html') || isSharedCacheable(getHeader)) {\n return response;\n }\n\n const existingValue = getHeader(SERVER_TIMING_HEADER);\n if (existingValue?.includes('sentry-trace')) {\n return response;\n }\n\n const traceHeader = getTraceServerTimingHeader();\n if (!traceHeader) {\n return response;\n }\n\n const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;\n try {\n headers.set(SERVER_TIMING_HEADER, value);\n return response;\n } catch {\n // Passing the original response as the init keeps its status, status text and headers.\n const copy = new Response(response.body, response);\n copy.headers.set(SERVER_TIMING_HEADER, value);\n return copy as R;\n }\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to add the trace to the Server-Timing header', e);\n return response;\n }\n}\n"],"mappings":";;;AAIA,MAAM,uBAAuB;AAE7B,MAAM,iCAAiB,IAAI,QAAgB;;;;;;;AAQ3C,SAAgB,2BAA2B,QAAsB;CAC/D,eAAe,IAAI,MAAM;AAC3B;;;;;;;;;AAUA,SAAgB,4BAA4D,QAAgB,UAAgB;CAC1G,IAAI,CAAC,YAAY,CAAC,eAAe,IAAI,MAAM,GACzC,OAAO;CAGT,IAAI;EACF,MAAM,UAAU,SAAS;EACzB,MAAM,aAAa,SAAqC,QAAQ,IAAI,IAAI,KAAK,KAAA;EAC7E,IAAI,CAAC,UAAU,cAAc,CAAC,EAAE,YAAY,CAAC,CAAC,WAAW,WAAW,KAAK,kBAAkB,SAAS,GAClG,OAAO;EAGT,MAAM,gBAAgB,UAAU,oBAAoB;EACpD,IAAI,eAAe,SAAS,cAAc,GACxC,OAAO;EAGT,MAAM,cAAc,2BAA2B;EAC/C,IAAI,CAAC,aACH,OAAO;EAGT,MAAM,QAAQ,gBAAgB,GAAG,cAAc,IAAI,gBAAgB;EACnE,IAAI;GACF,QAAQ,IAAI,sBAAsB,KAAK;GACvC,OAAO;EACT,QAAQ;GAEN,MAAM,OAAO,IAAI,SAAS,SAAS,MAAM,QAAQ;GACjD,KAAK,QAAQ,IAAI,sBAAsB,KAAK;GAC5C,OAAO;EACT;CACF,SAAS,GAAG;EACV,eAAe,MAAM,KAAK,uDAAuD,CAAC;EAClF,OAAO;CACT;AACF"}