@sentry/server-utils 11.13.0 → 11.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/config.js +19 -5
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +593 -238
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +6 -5
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +1186 -182
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/orchestrion/bundler/rollup.js +4 -4
- package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +24 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/constants.js +2 -1
- package/build/esm/ai/google-genai/constants.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +25 -0
- package/build/esm/ai/google-genai/decisions.js.map +1 -0
- package/build/esm/ai/google-genai/index.js +35 -11
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +28 -13
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +6 -8
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/mistral/utils.js +9 -1
- package/build/esm/ai/mistral/utils.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/vercel-ai/index.js +3 -1
- package/build/esm/ai/vercel-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +32 -14
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +8 -10
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/cron.js +2 -2
- package/build/esm/integrations/cron.js.map +1 -1
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +26 -14
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +15 -5
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/node-cron.js +5 -4
- package/build/esm/integrations/node-cron.js.map +1 -1
- package/build/esm/integrations/node-schedule.js +2 -2
- package/build/esm/integrations/node-schedule.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +53 -18
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +6 -5
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
- package/build/esm/orchestrion/bundler/rollup.js +4 -4
- package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
- package/build/esm/orchestrion/config/google-genai.js +19 -5
- package/build/esm/orchestrion/config/google-genai.js.map +1 -1
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/cronMonitoring.js +128 -50
- package/build/esm/utils/cronMonitoring.js.map +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/constants.d.ts +3 -0
- package/build/types/ai/google-genai/constants.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts +8 -0
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -0
- package/build/types/ai/google-genai/index.d.ts +3 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/mistral/utils.d.ts +5 -0
- package/build/types/ai/mistral/utils.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
- package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts +3 -0
- package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/cron.d.ts.map +1 -1
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +5 -4
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/node-cron.d.ts +1 -1
- package/build/types/integrations/node-cron.d.ts.map +1 -1
- package/build/types/integrations/node-schedule.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
- package/build/types/orchestrion/bundler/rollup.d.ts +3 -3
- package/build/types/orchestrion/bundler/rollup.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +1 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/google-genai.d.ts +13 -0
- package/build/types/orchestrion/config/google-genai.d.ts.map +1 -1
- package/build/types/utils/cronMonitoring.d.ts +4 -5
- package/build/types/utils/cronMonitoring.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -2,7 +2,7 @@ import { DEBUG_BUILD } from "../../debug-build.js";
|
|
|
2
2
|
import { isReadableStream } from "../../ai/core/utils.js";
|
|
3
3
|
import { CHANNELS } from "../../orchestrion/channels.js";
|
|
4
4
|
import { bindTracingChannelToSpan } from "../../tracing-channel.js";
|
|
5
|
-
import { captureToolError, clearOperationCallId, clearOperationId, createSpanFromMessage, enrichSpanOnEnd, streamedResultToChannelResult } from "./vercel-ai-dc-subscriber.js";
|
|
5
|
+
import { captureToolError, clearOperationCallId, clearOperationId, createSpanFromMessage, enrichSpanOnEnd, runVercelAiSpanEnd, streamedResultToChannelResult } from "./vercel-ai-dc-subscriber.js";
|
|
6
6
|
import { asString, tapModelCallStream } from "./util.js";
|
|
7
7
|
import { SPAN_STATUS_ERROR, addNonEnumerableProperty, debug, getActiveSpan, isObjectLike, withActiveSpan } from "@sentry/core";
|
|
8
8
|
// src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts
|
|
@@ -120,12 +120,14 @@ function bindOperation(tracingChannel, channelName, build, options) {
|
|
|
120
120
|
if (callSiteSpan && isObjectLike(data.error)) addNonEnumerableProperty(data.error, "_sentry_active_span", callSiteSpan);
|
|
121
121
|
} else {
|
|
122
122
|
message.result = message.type === "executeTool" ? { output: data.result } : data.result;
|
|
123
|
-
enrichSpanOnEnd(span, message
|
|
123
|
+
enrichSpanOnEnd(span, message);
|
|
124
124
|
}
|
|
125
|
-
|
|
125
|
+
const isStream = message.type === "streamText" || message.type === "streamObject";
|
|
126
|
+
runVercelAiSpanEnd(span, "error" in data ? { error: data.error } : { response: isStream ? void 0 : message.result });
|
|
127
|
+
if (!isStream) clearOperationId(message);
|
|
126
128
|
messages.delete(data);
|
|
127
129
|
},
|
|
128
|
-
deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end
|
|
130
|
+
deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end)
|
|
129
131
|
});
|
|
130
132
|
}
|
|
131
133
|
/**
|
|
@@ -138,7 +140,7 @@ function bindOperation(tracingChannel, channelName, build, options) {
|
|
|
138
140
|
* succeeded and `usage` resolved. It's awaited separately so that case still records the token usage on
|
|
139
141
|
* the span before ending it as an error.
|
|
140
142
|
*/
|
|
141
|
-
function deferStreamTextOperationEnd(span, data, end
|
|
143
|
+
function deferStreamTextOperationEnd(span, data, end) {
|
|
142
144
|
const message = messages.get(data);
|
|
143
145
|
const type = message?.type;
|
|
144
146
|
if (!message || type !== "streamText" && type !== "streamObject" || "error" in data || !isStreamingResult(data.result)) return false;
|
|
@@ -163,7 +165,7 @@ function deferStreamTextOperationEnd(span, data, end, options) {
|
|
|
163
165
|
finishReason,
|
|
164
166
|
response
|
|
165
167
|
};
|
|
166
|
-
enrichSpanOnEnd(span, message
|
|
168
|
+
enrichSpanOnEnd(span, message);
|
|
167
169
|
end(objectOutcome.error);
|
|
168
170
|
return;
|
|
169
171
|
}
|
|
@@ -292,34 +294,34 @@ function patchModelMethod(model, method, options) {
|
|
|
292
294
|
code: SPAN_STATUS_ERROR,
|
|
293
295
|
message: error instanceof Error ? error.message : "unknown_error"
|
|
294
296
|
});
|
|
295
|
-
span
|
|
297
|
+
endSpan(span, { error });
|
|
296
298
|
clearStreamCallId();
|
|
297
299
|
throw error;
|
|
298
300
|
};
|
|
299
301
|
try {
|
|
300
302
|
return Promise.resolve(original.apply(this, args)).then((value) => {
|
|
301
303
|
if (method === "doStream" && isObjectLike(value) && isReadableStream(value.stream)) {
|
|
302
|
-
value.stream = tapModelCallStream(value.stream, (final) => {
|
|
304
|
+
value.stream = tapModelCallStream(span, value.stream, (final) => {
|
|
303
305
|
message.result = {
|
|
304
306
|
...value,
|
|
305
307
|
...streamedResultToChannelResult(final)
|
|
306
308
|
};
|
|
307
|
-
enrichSpanOnEnd(span, message
|
|
308
|
-
span
|
|
309
|
+
enrichSpanOnEnd(span, message);
|
|
310
|
+
endSpan(span, {});
|
|
309
311
|
clearStreamCallId();
|
|
310
312
|
}, (error) => {
|
|
311
313
|
span.setStatus({
|
|
312
314
|
code: SPAN_STATUS_ERROR,
|
|
313
315
|
message: error instanceof Error ? error.message : "unknown_error"
|
|
314
316
|
});
|
|
315
|
-
span
|
|
317
|
+
endSpan(span, { error });
|
|
316
318
|
clearStreamCallId();
|
|
317
319
|
});
|
|
318
320
|
return value;
|
|
319
321
|
}
|
|
320
322
|
message.result = value;
|
|
321
|
-
enrichSpanOnEnd(span, message
|
|
322
|
-
span
|
|
323
|
+
enrichSpanOnEnd(span, message);
|
|
324
|
+
endSpan(span, { response: value });
|
|
323
325
|
clearStreamCallId();
|
|
324
326
|
return value;
|
|
325
327
|
}, failSpan);
|
|
@@ -371,14 +373,14 @@ function patchToolExecute(toolName, tool, tools, options) {
|
|
|
371
373
|
message: error instanceof Error ? error.message : "tool_error"
|
|
372
374
|
});
|
|
373
375
|
else captureToolError(span, message, error);
|
|
374
|
-
span
|
|
376
|
+
endSpan(span, { error });
|
|
375
377
|
throw error;
|
|
376
378
|
};
|
|
377
379
|
try {
|
|
378
380
|
return Promise.resolve(original.apply(this, [input, ...rest])).then((value) => {
|
|
379
381
|
message.result = { output: value };
|
|
380
|
-
enrichSpanOnEnd(span, message
|
|
381
|
-
span.
|
|
382
|
+
enrichSpanOnEnd(span, message);
|
|
383
|
+
endSpan(span, { response: message.result });
|
|
382
384
|
return value;
|
|
383
385
|
}, failSpan);
|
|
384
386
|
} catch (error) {
|
|
@@ -386,6 +388,10 @@ function patchToolExecute(toolName, tool, tools, options) {
|
|
|
386
388
|
}
|
|
387
389
|
};
|
|
388
390
|
}
|
|
391
|
+
function endSpan(span, result) {
|
|
392
|
+
runVercelAiSpanEnd(span, result);
|
|
393
|
+
span.end();
|
|
394
|
+
}
|
|
389
395
|
function buildTextMessage(type) {
|
|
390
396
|
return (options, telemetry) => ({
|
|
391
397
|
type,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vercel-ai-orchestrion-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Span } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n SPAN_STATUS_ERROR,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport {\n captureToolError,\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\n streamedResultToChannelResult,\n type VercelAiChannelMessage,\n type VercelAiChannelOptions,\n type VercelAiTracingChannelFactory,\n} from './vercel-ai-dc-subscriber';\nimport { asString, isReadableStream, tapModelCallStream } from './util';\n\n/**\n * v4, v5 & v6 channel adapter for the Vercel AI (`ai`) SDK.\n *\n * `ai` >= 7 publishes a normalized `ai:telemetry` tracing channel natively\n * (consumed by `subscribeVercelAiTracingChannel`). v4/v5/v6 have no such channel, so\n * orchestrion injects `orchestrion:ai:*` channels around the top-level\n * functions (see `orchestrion/config/index.ts`). The injected channels carry only the\n * wrapped call's `{ arguments, result, error }` — NOT v7's normalized `event`\n * object — so this adapter reconstructs an equivalent {@link VercelAiChannelMessage}\n * from each version's argument/result shapes and delegates to the SAME span-building core\n * (`createSpanFromMessage` / `enrichSpanOnEnd`) the v7 subscriber uses, so the\n * emitted spans are identical between v4, v5, v6 and v7. The shared core reads both v4-style\n * (`promptTokens`/`completionTokens`) and v5+-style (`inputTokens`/`outputTokens`) token names.\n *\n * The model call (`languageModelCall` / `generate_content` span) has no\n * injectable definition in `ai`. On v5/v6 we wrap `resolveLanguageModel` (the\n * single chokepoint every model call flows through) and monkey-patch\n * `doGenerate`/`doStream` on the returned model. v4 has no `resolveLanguageModel`\n * — the passed `LanguageModelV1` (`specificationVersion: 'v1'`) is called directly —\n * so we patch its `doGenerate`/`doStream` at the operation start instead (see\n * `buildOperationSpan`), gated on `'v1'` so it never touches v5/v6 models.\n *\n * Tool-call spans differ by version: v6 exposes a per-call `executeToolCall`\n * function orchestrion wraps into its own channel. v4/v5 have no such export (only a\n * batch `executeTools`), so instead we monkey-patch each tool's `execute` from\n * the operation's `tools`. On v6 that patch is inert: `executeToolCall` runs\n * `execute` inside its own tool-call span (the active async context), so the\n * patch sees that span as its parent and skips — only v4/v5 (where the parent is\n * the enclosing `invoke_agent` span) emit the patched span, so v6 never\n * double-counts tool spans.\n */\n\n/** Builds the normalized message for a channel from the wrapped call's first-arg options. */\ntype MessageBuilder = (options: Record<string, unknown>, telemetry: Record<string, unknown>) => VercelAiChannelMessage;\n\n/** A resolved `ai` language model — has `doGenerate`/`doStream` and identity fields. */\ninterface ResolvedModel {\n modelId?: string;\n provider?: string;\n doGenerate?: (...args: unknown[]) => Promise<unknown>;\n doStream?: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst PATCHED = Symbol('SentryVercelAiModelPatched');\nconst TOOL_PATCHED = Symbol('SentryVercelAiToolPatched');\n\n/** A resolved model with our patch bookkeeping (idempotency flag). */\ntype PatchableModel = ResolvedModel & { [PATCHED]?: boolean };\n\n/** A tool definition off an operation's `tools`, with our patch bookkeeping. */\ntype PatchableTool = { execute?: (...args: unknown[]) => unknown; [TOOL_PATCHED]?: boolean };\n\n// Per-operation correlation id. No Date/random (unavailable / non-deterministic) — a counter is enough.\nlet callIdCounter = 0;\nfunction nextCallId(): string {\n return `v6-${++callIdCounter}`;\n}\n\n// The message built on `start` for each operation, keyed by the (stable-identity) channel context, so\n// the `beforeSpanEnd` handler can enrich the span from the settled result and clear the `callId` maps.\nconst messages = new WeakMap<object, VercelAiChannelMessage>();\n// The spans we opened for top-level operations, and each one's `callId`. A model call resolves its\n// parent against this set (so it never mis-attributes to the enclosing `main`/user span) and reads the\n// parent's `callId` so its span can be named after the operation (e.g. `ai.streamText.doStream`).\nconst operationSpans = new WeakSet<Span>();\n// Tool-call spans — only v6's `executeToolCall` channel opens these. The v5 tool-`execute` patch\n// consults this to avoid double-counting: `executeToolCall` runs `execute` inside its span (which is\n// therefore the active parent), so a resolved parent in this set means v6 already spanned the call.\nconst toolCallSpans = new WeakSet<Span>();\nconst callIdBySpan = new WeakMap<Span, string>();\n// The operation's per-call recording flags (`experimental_telemetry.recordInputs/recordOutputs`), keyed by\n// its span. A model call carries no telemetry of its own, so it inherits the enclosing operation's flags —\n// otherwise a per-call `recordInputs: true` would record inputs on the `invoke_agent` span but not on the\n// child `generate_content` span (whose event would fall back to the global default). v7's channel forwards\n// these flags on every event, so this keeps v6 identical.\nconst recordingBySpan = new WeakMap<Span, ReturnType<typeof recording>>();\n// The operation's `experimental_telemetry.metadata`, keyed by its span, so the model-call span records it\n// too. The OTel integration put it on both, but not on tool-call spans.\nconst telemetryMetadataBySpan = new WeakMap<Span, unknown>();\ninterface OperationErrorInfo {\n // The span active when the operation was invoked (its call site, e.g. the enclosing request/`main` span).\n // When an operation's error bubbles out unhandled it reaches the global handler outside any span, so — as\n // the OTel path does — we stamp this span onto the error (in `beforeSpanEnd`) so the unhandled-rejection\n // handler can restore it and correlate the captured error to the operation's trace.\n callSiteSpan: Span | undefined;\n // Whether a thrown tool error bubbles out of the `ai` call (v4). On v4 a tool-`execute` rejection is\n // wrapped in `AI_ToolExecutionError` and re-thrown, so it reaches the user's own error handling (or our\n // global handlers) — capturing it at the tool span too would double-report it, matching how the OTel path\n // leaves v4 tool errors to bubble. On v5 `executeTools` swallows the rejection into `tool-error` content,\n // so it never surfaces and we must capture it ourselves (see `failSpan`).\n toolErrorsBubbleToCaller: boolean;\n}\n// Per-operation error-handling info, keyed by the operation span (see `OperationErrorInfo`).\nconst operationErrorInfoBySpan = new WeakMap<Span, OperationErrorInfo>();\n\n// The `experimental_telemetry` objects we swapped in to suppress `ai`'s native OTel spans (see\n// `suppressNativeTelemetry`). Our skip logic treats `isEnabled === false` as \"user disabled telemetry,\n// emit no span\"; without this set, a call whose options object we already neutralized — or a user-shared\n// telemetry object we replaced on a prior call — would be misread as user-disabled and lose its span.\nconst suppressedTelemetry = new WeakSet<object>();\n\nlet subscribed = false;\n\n/**\n * Subscribe the v6 orchestrion channel adapter. Safe to always call: inert on\n * `ai` >= 7 (those channels are never published) and when orchestrion injection\n * isn't active. Idempotent.\n *\n * `tracingChannel` is the platform-provided factory (the same one passed to\n * `subscribeVercelAiTracingChannel`); `options` pins the recording settings at\n * subscribe time so we never look the integration up per event.\n */\nexport function subscribeVercelAiOrchestrionChannels(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage('generateText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage('streamText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_OBJECT, buildTextMessage('streamObject'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_OBJECT, buildTextMessage('generateObject'), options);\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED,\n (callOptions, telemetry) => ({\n type: 'embed',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n value: callOptions.value,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED_MANY,\n // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the\n // embeddings input, matching the OTel path's batch `ai.embedMany` span.\n (callOptions, telemetry) => ({\n type: 'embedMany',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n values: callOptions.values,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,\n (callOptions, telemetry) => ({\n type: 'executeTool',\n // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);\n // the shared core reads the matching tool's `description` for the span.\n event: {\n callId: nextCallId(),\n toolCall: callOptions.toolCall,\n tools: callOptions.tools,\n ...recording(telemetry),\n },\n }),\n options,\n );\n subscribeResolveLanguageModel(tracingChannel, CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI channel subscription failed.');\n }\n}\n\n/**\n * Bind one operation channel: `getSpan` opens a span from the message reconstructed out of the wrapped\n * call's first argument; `beforeSpanEnd` enriches it from the settled result (tokens, output messages,\n * finish reasons, …) before the helper ends the span.\n *\n * An operation whose `experimental_telemetry.isEnabled` is explicitly `false` is skipped entirely (no\n * span): the orchestrion channel fires regardless of that flag, whereas v7's native `ai:telemetry`\n * channel is simply not published in that case — so we reproduce v7's \"no telemetry → no span\".\n */\nfunction bindOperation(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n build: MessageBuilder,\n options: VercelAiChannelOptions,\n): void {\n const channel = tracingChannel<OrchestrionChannelContext>(channelName);\n\n // Build the operation span from the wrapped call's first argument and track it (so a model call can\n // resolve it as its parent). `bindTracingChannelToSpan` calls this once at channel `start` and makes\n // the returned span the active async context for the operation's duration — that active span is what\n // `resolveModelCallParent` reads. It also sets `data._sentrySpan`, so we don't here.\n const buildOperationSpan = (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>): Span | undefined => {\n const callOptions = isObjectLike(data.arguments[0]) ? data.arguments[0] : {};\n const telemetry = isObjectLike(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};\n // `isEnabled === false` means the user opted out — emit no span. But `isEnabled` is also `false` on\n // the telemetry object we swap in to suppress native spans, so don't mistake our own object for a\n // user opt-out (which would drop the span on a call whose options we already neutralized).\n if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {\n return undefined;\n }\n const message = build(callOptions, telemetry);\n // Stop `ai` from emitting its own native OTel spans for this call — we build the equivalent spans\n // from the channels, so the SDK's would be duplicates. Reads above have already captured everything\n // we need off `telemetry`.\n suppressNativeTelemetry(callOptions, telemetry);\n // The span active here is the operation's call site — `bindTracingChannelToSpan` only makes the\n // operation span active *after* this returns — so this is the span we later restore for a bubbled error.\n const callSiteSpan = getActiveSpan();\n const span = createSpanFromMessage(message, options);\n if (span) {\n messages.set(data, message);\n operationSpans.add(span);\n // `'v1'` models are v4 (v5/v6 are `'v2'`), where a thrown tool error bubbles out of the call rather\n // than being swallowed into `tool-error` content — so its tool spans must not self-capture the error.\n const isV4 = isObjectLike(callOptions.model) && callOptions.model.specificationVersion === 'v1';\n operationErrorInfoBySpan.set(span, { callSiteSpan, toolErrorsBubbleToCaller: isV4 });\n // v6's `executeToolCall` span: tracked so the v5 tool-`execute` patch can recognize (and skip)\n // tool calls it runs, since that patch sees this span as its active parent (see `patchToolExecute`).\n if (message.type === 'executeTool') {\n toolCallSpans.add(span);\n }\n const callId = asString(message.event.callId);\n if (callId) {\n callIdBySpan.set(span, callId);\n }\n recordingBySpan.set(span, recording(telemetry));\n telemetryMetadataBySpan.set(span, telemetry.metadata);\n // v5 has no `executeToolCall` channel, so patch each tool's `execute` to emit the tool-call span.\n // Inert on v6 (guarded inside `patchToolExecute` when the parent is `executeToolCall`'s own span).\n if (isObjectLike(callOptions.tools)) {\n patchOperationTools(callOptions.tools, options);\n }\n // v4 has no `resolveLanguageModel` chokepoint — the passed `LanguageModelV1` is called directly — so\n // patch its `doGenerate`/`doStream` here, at the operation start, instead. v5/v6 models are patched via\n // `resolveLanguageModel`, so restricting to v4 keeps this strictly additive and avoids double-patching.\n // Embedding models are also `'v1'` but expose no `doGenerate`/`doStream`, so the patch is a no-op for\n // `embed`/`embedMany`.\n if (isV4) {\n patchModelMethods(callOptions.model as PatchableModel, options);\n }\n }\n return span;\n };\n\n bindTracingChannelToSpan(\n channel,\n (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>) => buildOperationSpan(data),\n {\n beforeSpanEnd: (span, data) => {\n const message = messages.get(data);\n if (!message) {\n return;\n }\n // The helper's `error` handler already set the span status; only enrich from a successful result.\n if ('error' in data) {\n // The error bubbles out of the `ai` call. If nothing handles it before our global handler, that\n // handler runs outside any span — so stamp the operation's call-site span onto the error, letting\n // the unhandled-rejection handler restore it and correlate the report to this trace. This mirrors\n // the OTel path; it's a no-op when the error is handled earlier (e.g. a framework error handler).\n const callSiteSpan = operationErrorInfoBySpan.get(span)?.callSiteSpan;\n if (callSiteSpan && isObjectLike(data.error)) {\n addNonEnumerableProperty(data.error, '_sentry_active_span', callSiteSpan);\n }\n } else {\n // v6's `executeToolCall` returns the tool result/error object directly, whereas the shared core\n // (matching v7) expects it nested under `output`; wrap it so tool-error detection works.\n message.result = message.type === 'executeTool' ? { output: data.result } : data.result;\n enrichSpanOnEnd(span, message, options);\n }\n // A `streamText`/`streamObject` model call runs after this (synchronously-returning) operation's\n // span has already ended, so its `callId` entry must outlive the operation — it's cleared once the\n // model call settles (see `patchModelMethod`). Every other operation can clear here.\n if (message.type !== 'streamText' && message.type !== 'streamObject') {\n clearOperationId(message);\n }\n messages.delete(data);\n },\n // `streamText`/`streamObject` return synchronously, so their operation span would otherwise end\n // before the stream drains — losing the aggregate usage/output. Defer the end and await the result's\n // completion promises (`totalUsage`/`text`/…, which resolve on drain), mirroring how v7's channel\n // defers the operation span on the SDK's total-usage promise.\n deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end, options),\n },\n );\n}\n\n/**\n * Keep a streamed `streamText`/`streamObject` operation span open until the stream drains, then enrich it\n * from the result's completion promises (usage/output/finish reason) and end it. `streamObject` resolves\n * `object` rather than `text`; `getOutputMessages` reads `text`, so a resolved object is stringified into\n * that field. Returns `false` for anything that isn't a streamed result, so the helper ends the span as usual.\n *\n * `streamObject`'s `object` rejects when the output fails schema validation, even though the model call\n * succeeded and `usage` resolved. It's awaited separately so that case still records the token usage on\n * the span before ending it as an error.\n */\nfunction deferStreamTextOperationEnd(\n span: Span,\n data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>,\n end: (error?: unknown) => void,\n options: VercelAiChannelOptions,\n): boolean {\n const message = messages.get(data);\n const type = message?.type;\n if (\n !message ||\n (type !== 'streamText' && type !== 'streamObject') ||\n 'error' in data ||\n !isStreamingResult(data.result)\n ) {\n return false;\n }\n\n const streamResult = data.result;\n void (async () => {\n try {\n const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([\n streamResult.totalUsage ?? streamResult.usage,\n streamResult.text,\n // Settle `object` into an outcome so a validation failure can't short-circuit the usage read.\n type === 'streamObject'\n ? Promise.resolve(streamResult.object).then(\n value => ({ value }),\n (error: unknown) => ({ value: undefined, error }),\n )\n : { value: undefined },\n streamResult.toolCalls,\n streamResult.finishReason,\n streamResult.response,\n ]);\n if ('error' in objectOutcome) {\n // The model call itself succeeded, so keep its usage on the span; `beforeSpanEnd` skips\n // enrichment once `end(error)` marks the payload as errored.\n message.result = { usage, toolCalls, finishReason, response };\n enrichSpanOnEnd(span, message, options);\n end(objectOutcome.error);\n return;\n }\n const object = objectOutcome.value;\n // Feed the resolved values back through the shared enrichment: `beforeSpanEnd` reads `data.result`.\n data.result = {\n usage,\n text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object),\n toolCalls,\n finishReason,\n response,\n };\n end();\n } catch (error) {\n end(error);\n }\n })();\n\n return true;\n}\n\n/** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */\nfunction isStreamingResult(result: unknown): result is Record<string, PromiseLike<unknown> | undefined> {\n return isObjectLike(result) && (isThenable(result.totalUsage) || isThenable(result.usage));\n}\n\nfunction isThenable(value: unknown): boolean {\n return isObjectLike(value) && typeof value.then === 'function';\n}\n\n/**\n * Neutralize `ai`'s native OpenTelemetry instrumentation for this call by pointing\n * `experimental_telemetry` at a copy with `isEnabled: false`. `ai`'s `getTracer` then returns its\n * internal no-op tracer, so it never creates (nor sets active) the duplicate `ai.*` spans we'd\n * otherwise have to drop.\n *\n * Only a call that explicitly enabled telemetry emits native spans — otherwise `ai` already uses its\n * no-op tracer, so there's nothing to suppress and we leave the user's options untouched. When\n * `isEnabled === true`, `telemetry` is `callOptions.experimental_telemetry` and `callOptions` is the\n * real first argument the SDK will read, so the reassignment takes effect for the wrapped call. We\n * replace rather than mutate in place, so a telemetry object the user shares across calls keeps its own\n * `isEnabled: true`; the replacement is tracked in `suppressedTelemetry` so our skip logic doesn't\n * later read it back as a user opt-out.\n */\nfunction suppressNativeTelemetry(callOptions: Record<string, unknown>, telemetry: Record<string, unknown>): void {\n if (telemetry.isEnabled !== true) {\n return;\n }\n const suppressed = { ...telemetry, isEnabled: false };\n suppressedTelemetry.add(suppressed);\n callOptions.experimental_telemetry = suppressed;\n}\n\n/**\n * `resolveLanguageModel` returns the model every call flows through. We don't span it — on `end` we\n * monkey-patch `doGenerate`/`doStream` on the returned model so each invocation produces a\n * `languageModelCall` span parented to the enclosing invoke_agent span.\n */\nfunction subscribeResolveLanguageModel(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n options: VercelAiChannelOptions,\n): void {\n tracingChannel<OrchestrionChannelContext>(channelName).subscribe({\n end(rawCtx) {\n const ctx = rawCtx;\n if (!isObjectLike(ctx.result)) {\n return;\n }\n // Patch the model's `doGenerate`/`doStream` once. The model call recovers its parent from the\n // active async context at call time (the operation span `bindTracingChannelToSpan` bound), which\n // propagates into the model call for `streamText` too, so there is nothing to capture on the model here.\n patchModelMethods(ctx.result, options);\n },\n start() {\n /* no-op */\n },\n asyncStart() {\n /* no-op */\n },\n asyncEnd() {\n /* no-op */\n },\n error() {\n /* no-op */\n },\n });\n}\n\n/**\n * Pick the invoke_agent span a model call should hang under: the operation span that\n * `bindTracingChannelToSpan` planted as the active async context for the enclosing operation.\n *\n * Because we suppress `ai`'s native telemetry (so it never installs its own span as active), the active\n * span inside `doGenerate`/`doStream` is our operation span. The `operationSpans` gate makes this return\n * `undefined` when the active span isn't one of ours — e.g. telemetry was disabled for the call so we\n * opened no operation span and the active span is the user's enclosing span — so the model call is\n * skipped rather than mis-parented.\n *\n * This covers `generateText`/`embed` (whose model call is awaited inside the operation body) and\n * `streamText` alike — `ai` initiates the stream synchronously within the operation's bound context, so\n * the later `doStream` continuation restores the same active span even though the operation's span has\n * already ended. The per-operation binding also disambiguates concurrent calls that share one model\n * instance (a single mutable slot on the shared model could not — it would hold whichever operation\n * resolved the model last).\n */\nfunction resolveModelCallParent(): Span | undefined {\n const active = getActiveSpan();\n return active && operationSpans.has(active) ? active : undefined;\n}\n\n/**\n * Idempotently patch a resolved model's `doGenerate`/`doStream` so each invocation emits a\n * `languageModelCall` span. Shared by the v5/v6 `resolveLanguageModel` path and the v4 path (which\n * patches the passed model at the operation start, as v4 has no `resolveLanguageModel`).\n */\nfunction patchModelMethods(model: PatchableModel, options: VercelAiChannelOptions): void {\n if (model[PATCHED]) {\n return;\n }\n model[PATCHED] = true;\n patchModelMethod(model, 'doGenerate', options);\n patchModelMethod(model, 'doStream', options);\n}\n\nfunction patchModelMethod(\n model: PatchableModel,\n method: 'doGenerate' | 'doStream',\n options: VercelAiChannelOptions,\n): void {\n const original = model[method];\n if (typeof original !== 'function') {\n return;\n }\n model[method] = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const parent = resolveModelCallParent();\n // No enclosing operation span (e.g. telemetry disabled for the call) → don't open a model-call span.\n if (!parent) {\n return Promise.resolve(original.apply(this, args));\n }\n\n const callArgs = isObjectLike(args[0]) ? args[0] : {};\n // Carry the operation's `callId` so the shared core can name the span after it\n // (`ai.generateText.doGenerate` / `ai.streamText.doStream`).\n const callId = callIdBySpan.get(parent);\n const message: VercelAiChannelMessage = {\n type: 'languageModelCall',\n event: {\n callId,\n provider: model.provider,\n modelId: model.modelId,\n // v4 nests the tool list under `mode.tools` (the `LanguageModelV1` call shape); v5+ passes a\n // top-level `tools` array. Reading both keeps `tool.definitions` populated on the model-call span.\n tools: callArgs.tools ?? (isObjectLike(callArgs.mode) ? callArgs.mode.tools : undefined),\n messages: callArgs.prompt,\n telemetryMetadata: telemetryMetadataBySpan.get(parent),\n // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on\n // the model-call span whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `languageModelCall` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return Promise.resolve(original.apply(this, args));\n }\n\n // `streamText` ends its operation span synchronously, so its `callId` entry was deliberately left in\n // place for this later model call; drop it now that we've used it.\n const clearStreamCallId = (): void => {\n if (method === 'doStream' && callId) {\n clearOperationCallId(callId);\n }\n };\n\n // Both the synchronous throw and the async rejection of the model call must end the span with an\n // error status (an `async` `doGenerate`/`doStream` that throws rejects rather than throwing here).\n const failSpan = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'unknown_error' });\n span.end();\n clearStreamCallId();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, args));\n return result.then(value => {\n // A streamed model call resolves to `{ stream, ... }` before the stream is consumed, so its\n // usage/finish/output only arrive as the stream drains. Tap it (same helper as the v7 path) and\n // defer ending this model-call span until then. The parent `invoke_agent` span is enriched\n // separately by `deferStreamTextOperationEnd`, which awaits the operation's own result promises.\n if (method === 'doStream' && isObjectLike(value) && isReadableStream(value.stream)) {\n value.stream = tapModelCallStream(\n value.stream,\n final => {\n message.result = { ...value, ...streamedResultToChannelResult(final) };\n enrichSpanOnEnd(span, message, options);\n span.end();\n clearStreamCallId();\n },\n error => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'unknown_error',\n });\n span.end();\n clearStreamCallId();\n },\n );\n\n return value;\n }\n // `doGenerate` (and any non-stream result) settles with the full result; end here, start/end\n // bracket the call to match the channel timing.\n message.result = value;\n enrichSpanOnEnd(span, message, options);\n span.end();\n clearStreamCallId();\n\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\n/**\n * Patch every executable tool on an operation's `tools` (a record keyed by tool name) so each\n * invocation emits a `gen_ai.execute_tool` span. v5 routes tool execution through the batch\n * `executeTools`, which binds `tool.execute` at call time — so replacing the `execute` property here\n * (before the call runs) is picked up. Tools without an `execute` (client-side tools) are skipped,\n * matching `executeTools`.\n */\nfunction patchOperationTools(tools: Record<string, unknown>, options: VercelAiChannelOptions): void {\n // This runs inside the channel `start` transform (no upstream try/catch), so a throw here would break\n // the user's `ai` call. Instrumentation must never do that — degrade to no tool span instead.\n try {\n for (const [toolName, tool] of Object.entries(tools)) {\n if (isObjectLike(tool)) {\n patchToolExecute(toolName, tool, tools, options);\n }\n }\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI tool patching failed.');\n }\n}\n\nfunction patchToolExecute(\n toolName: string,\n tool: PatchableTool,\n tools: Record<string, unknown>,\n options: VercelAiChannelOptions,\n): void {\n const original = tool.execute;\n if (typeof original !== 'function' || tool[TOOL_PATCHED]) {\n return;\n }\n tool[TOOL_PATCHED] = true;\n tool.execute = function (this: unknown, input: unknown, ...rest: unknown[]): unknown {\n // Skip if there's no enclosing operation span (telemetry disabled for the call), or if that parent\n // is itself a tool-call span — the latter means v6's `executeToolCall` already opened a span for\n // this call and is running `execute` inside it, so spanning again here would double-count. On v5\n // the parent is the enclosing `invoke_agent` operation span, so we proceed.\n const parent = resolveModelCallParent();\n if (!parent || toolCallSpans.has(parent)) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5 passes `{ toolCallId, messages, abortSignal, ... }` as the second argument to `execute`.\n const callOptions = isObjectLike(rest[0]) ? rest[0] : {};\n const message: VercelAiChannelMessage = {\n type: 'executeTool',\n event: {\n callId: callIdBySpan.get(parent),\n toolCall: { toolName, toolCallId: asString(callOptions.toolCallId), input },\n // The `tools` record (keyed by name) lets the shared core backfill the tool's `description`.\n tools,\n // Inherit the enclosing operation's per-call recording flags so tool inputs/outputs are recorded\n // whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `executeTool` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5's `executeTools` catches a thrown tool error and turns it into `tool-error` content rather than\n // rejecting, so the user never sees a rejection — we must capture it here. On v4 the rejection bubbles\n // out of the call and reaches the user's error handling (or our global handlers), so we only mark the\n // span and leave the capture to them, avoiding a duplicate report. Rethrow either way so `executeTools`\n // still produces its `tool-error` result (v5) and the rejection propagates (v4).\n const failSpan = (error: unknown): never => {\n if (operationErrorInfoBySpan.get(parent)?.toolErrorsBubbleToCaller) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'tool_error' });\n } else {\n captureToolError(span, message, error);\n }\n span.end();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, [input, ...rest]));\n return result.then(value => {\n // The shared core (matching v6/v7) expects the tool result nested under `output`.\n message.result = { output: value };\n enrichSpanOnEnd(span, message, options);\n span.end();\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\nfunction buildTextMessage(type: 'generateText' | 'streamText' | 'streamObject' | 'generateObject'): MessageBuilder {\n return (options, telemetry) => ({\n type,\n event: {\n callId: nextCallId(),\n operationId: `ai.${type}`,\n functionId: asString(telemetry.functionId),\n ...modelFields(options.model),\n maxRetries: options.maxRetries,\n // The `ai` SDK takes the system prompt as a top-level `system` option (all of v4/v5/v6); the\n // shared core lifts `event.instructions` into the system-instructions attribute, matching v7's\n // native channel (which carries it as a distinct field rather than inside the messages array).\n instructions: options.system,\n // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string\n // `prompt` becomes a single user message, matching the SDK's own normalization.\n messages: normalizePromptMessages(options),\n // v7's native start event carries `providerOptions`; the shared core reads the OpenAI\n // Conversations API id from it.\n providerOptions: options.providerOptions,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n });\n}\n\nfunction normalizePromptMessages(options: Record<string, unknown>): unknown {\n if (Array.isArray(options.messages)) {\n return options.messages;\n }\n if (typeof options.prompt === 'string') {\n return [{ role: 'user', content: options.prompt }];\n }\n return options.messages ?? options.prompt;\n}\n\nfunction recording(telemetry: Record<string, unknown>): { recordInputs: unknown; recordOutputs: unknown } {\n // Match the OTel integration's per-call default: an explicit `recordInputs`/`recordOutputs` wins, but a\n // call that merely enables telemetry (`isEnabled: true`, no explicit flags) defaults both to `true`.\n // Unlike v7's native `ai:telemetry` channel, the orchestrion channels expose `isEnabled`, so — as noted\n // in `resolveRecording` — we CAN reproduce that default here (the native-channel subscriber cannot).\n const enabledDefault = telemetry.isEnabled === true ? true : undefined;\n return {\n recordInputs: telemetry.recordInputs ?? enabledDefault,\n recordOutputs: telemetry.recordOutputs ?? enabledDefault,\n };\n}\n\nfunction modelFields(model: unknown): { provider?: string; modelId?: string } {\n return { provider: modelField(model, 'provider'), modelId: modelField(model, 'modelId') };\n}\n\nfunction modelField(model: unknown, field: 'modelId' | 'provider'): string | undefined {\n return isObjectLike(model) ? asString(model[field]) : undefined;\n}\n"],"mappings":";;;;;;;;AAsEA,MAAM,UAAU,OAAO,4BAA4B;AACnD,MAAM,eAAe,OAAO,2BAA2B;AASvD,IAAI,gBAAgB;AACpB,SAAS,aAAqB;CAC5B,OAAO,MAAM,EAAE;AACjB;AAIA,MAAM,2BAAW,IAAI,QAAwC;AAI7D,MAAM,iCAAiB,IAAI,QAAc;AAIzC,MAAM,gCAAgB,IAAI,QAAc;AACxC,MAAM,+BAAe,IAAI,QAAsB;AAM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ber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Span } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n SPAN_STATUS_ERROR,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport type { GenAiSpanResult } from '../../ai/core/span-hooks';\nimport {\n captureToolError,\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\n runVercelAiSpanEnd,\n streamedResultToChannelResult,\n type VercelAiChannelMessage,\n type VercelAiChannelOptions,\n type VercelAiTracingChannelFactory,\n} from './vercel-ai-dc-subscriber';\nimport { asString, isReadableStream, tapModelCallStream } from './util';\n\n/**\n * v4, v5 & v6 channel adapter for the Vercel AI (`ai`) SDK.\n *\n * `ai` >= 7 publishes a normalized `ai:telemetry` tracing channel natively\n * (consumed by `subscribeVercelAiTracingChannel`). v4/v5/v6 have no such channel, so\n * orchestrion injects `orchestrion:ai:*` channels around the top-level\n * functions (see `orchestrion/config/index.ts`). The injected channels carry only the\n * wrapped call's `{ arguments, result, error }` — NOT v7's normalized `event`\n * object — so this adapter reconstructs an equivalent {@link VercelAiChannelMessage}\n * from each version's argument/result shapes and delegates to the SAME span-building core\n * (`createSpanFromMessage` / `enrichSpanOnEnd`) the v7 subscriber uses, so the\n * emitted spans are identical between v4, v5, v6 and v7. The shared core reads both v4-style\n * (`promptTokens`/`completionTokens`) and v5+-style (`inputTokens`/`outputTokens`) token names.\n *\n * The model call (`languageModelCall` / `generate_content` span) has no\n * injectable definition in `ai`. On v5/v6 we wrap `resolveLanguageModel` (the\n * single chokepoint every model call flows through) and monkey-patch\n * `doGenerate`/`doStream` on the returned model. v4 has no `resolveLanguageModel`\n * — the passed `LanguageModelV1` (`specificationVersion: 'v1'`) is called directly —\n * so we patch its `doGenerate`/`doStream` at the operation start instead (see\n * `buildOperationSpan`), gated on `'v1'` so it never touches v5/v6 models.\n *\n * Tool-call spans differ by version: v6 exposes a per-call `executeToolCall`\n * function orchestrion wraps into its own channel. v4/v5 have no such export (only a\n * batch `executeTools`), so instead we monkey-patch each tool's `execute` from\n * the operation's `tools`. On v6 that patch is inert: `executeToolCall` runs\n * `execute` inside its own tool-call span (the active async context), so the\n * patch sees that span as its parent and skips — only v4/v5 (where the parent is\n * the enclosing `invoke_agent` span) emit the patched span, so v6 never\n * double-counts tool spans.\n */\n\n/** Builds the normalized message for a channel from the wrapped call's first-arg options. */\ntype MessageBuilder = (options: Record<string, unknown>, telemetry: Record<string, unknown>) => VercelAiChannelMessage;\n\n/** A resolved `ai` language model — has `doGenerate`/`doStream` and identity fields. */\ninterface ResolvedModel {\n modelId?: string;\n provider?: string;\n doGenerate?: (...args: unknown[]) => Promise<unknown>;\n doStream?: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst PATCHED = Symbol('SentryVercelAiModelPatched');\nconst TOOL_PATCHED = Symbol('SentryVercelAiToolPatched');\n\n/** A resolved model with our patch bookkeeping (idempotency flag). */\ntype PatchableModel = ResolvedModel & { [PATCHED]?: boolean };\n\n/** A tool definition off an operation's `tools`, with our patch bookkeeping. */\ntype PatchableTool = { execute?: (...args: unknown[]) => unknown; [TOOL_PATCHED]?: boolean };\n\n// Per-operation correlation id. No Date/random (unavailable / non-deterministic) — a counter is enough.\nlet callIdCounter = 0;\nfunction nextCallId(): string {\n return `v6-${++callIdCounter}`;\n}\n\n// The message built on `start` for each operation, keyed by the (stable-identity) channel context, so\n// the `beforeSpanEnd` handler can enrich the span from the settled result and clear the `callId` maps.\nconst messages = new WeakMap<object, VercelAiChannelMessage>();\n// The spans we opened for top-level operations, and each one's `callId`. A model call resolves its\n// parent against this set (so it never mis-attributes to the enclosing `main`/user span) and reads the\n// parent's `callId` so its span can be named after the operation (e.g. `ai.streamText.doStream`).\nconst operationSpans = new WeakSet<Span>();\n// Tool-call spans — only v6's `executeToolCall` channel opens these. The v5 tool-`execute` patch\n// consults this to avoid double-counting: `executeToolCall` runs `execute` inside its span (which is\n// therefore the active parent), so a resolved parent in this set means v6 already spanned the call.\nconst toolCallSpans = new WeakSet<Span>();\nconst callIdBySpan = new WeakMap<Span, string>();\n// The operation's per-call recording flags (`experimental_telemetry.recordInputs/recordOutputs`), keyed by\n// its span. A model call carries no telemetry of its own, so it inherits the enclosing operation's flags —\n// otherwise a per-call `recordInputs: true` would record inputs on the `invoke_agent` span but not on the\n// child `generate_content` span (whose event would fall back to the global default). v7's channel forwards\n// these flags on every event, so this keeps v6 identical.\nconst recordingBySpan = new WeakMap<Span, ReturnType<typeof recording>>();\n// The operation's `experimental_telemetry.metadata`, keyed by its span, so the model-call span records it\n// too. The OTel integration put it on both, but not on tool-call spans.\nconst telemetryMetadataBySpan = new WeakMap<Span, unknown>();\ninterface OperationErrorInfo {\n // The span active when the operation was invoked (its call site, e.g. the enclosing request/`main` span).\n // When an operation's error bubbles out unhandled it reaches the global handler outside any span, so — as\n // the OTel path does — we stamp this span onto the error (in `beforeSpanEnd`) so the unhandled-rejection\n // handler can restore it and correlate the captured error to the operation's trace.\n callSiteSpan: Span | undefined;\n // Whether a thrown tool error bubbles out of the `ai` call (v4). On v4 a tool-`execute` rejection is\n // wrapped in `AI_ToolExecutionError` and re-thrown, so it reaches the user's own error handling (or our\n // global handlers) — capturing it at the tool span too would double-report it, matching how the OTel path\n // leaves v4 tool errors to bubble. On v5 `executeTools` swallows the rejection into `tool-error` content,\n // so it never surfaces and we must capture it ourselves (see `failSpan`).\n toolErrorsBubbleToCaller: boolean;\n}\n// Per-operation error-handling info, keyed by the operation span (see `OperationErrorInfo`).\nconst operationErrorInfoBySpan = new WeakMap<Span, OperationErrorInfo>();\n\n// The `experimental_telemetry` objects we swapped in to suppress `ai`'s native OTel spans (see\n// `suppressNativeTelemetry`). Our skip logic treats `isEnabled === false` as \"user disabled telemetry,\n// emit no span\"; without this set, a call whose options object we already neutralized — or a user-shared\n// telemetry object we replaced on a prior call — would be misread as user-disabled and lose its span.\nconst suppressedTelemetry = new WeakSet<object>();\n\nlet subscribed = false;\n\n/**\n * Subscribe the v6 orchestrion channel adapter. Safe to always call: inert on\n * `ai` >= 7 (those channels are never published) and when orchestrion injection\n * isn't active. Idempotent.\n *\n * `tracingChannel` is the platform-provided factory (the same one passed to\n * `subscribeVercelAiTracingChannel`); `options` pins the recording settings at\n * subscribe time so we never look the integration up per event.\n */\nexport function subscribeVercelAiOrchestrionChannels(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage('generateText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage('streamText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_OBJECT, buildTextMessage('streamObject'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_OBJECT, buildTextMessage('generateObject'), options);\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED,\n (callOptions, telemetry) => ({\n type: 'embed',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n value: callOptions.value,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED_MANY,\n // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the\n // embeddings input, matching the OTel path's batch `ai.embedMany` span.\n (callOptions, telemetry) => ({\n type: 'embedMany',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n values: callOptions.values,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,\n (callOptions, telemetry) => ({\n type: 'executeTool',\n // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);\n // the shared core reads the matching tool's `description` for the span.\n event: {\n callId: nextCallId(),\n toolCall: callOptions.toolCall,\n tools: callOptions.tools,\n ...recording(telemetry),\n },\n }),\n options,\n );\n subscribeResolveLanguageModel(tracingChannel, CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI channel subscription failed.');\n }\n}\n\n/**\n * Bind one operation channel: `getSpan` opens a span from the message reconstructed out of the wrapped\n * call's first argument; `beforeSpanEnd` enriches it from the settled result (tokens, output messages,\n * finish reasons, …) before the helper ends the span.\n *\n * An operation whose `experimental_telemetry.isEnabled` is explicitly `false` is skipped entirely (no\n * span): the orchestrion channel fires regardless of that flag, whereas v7's native `ai:telemetry`\n * channel is simply not published in that case — so we reproduce v7's \"no telemetry → no span\".\n */\nfunction bindOperation(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n build: MessageBuilder,\n options: VercelAiChannelOptions,\n): void {\n const channel = tracingChannel<OrchestrionChannelContext>(channelName);\n\n // Build the operation span from the wrapped call's first argument and track it (so a model call can\n // resolve it as its parent). `bindTracingChannelToSpan` calls this once at channel `start` and makes\n // the returned span the active async context for the operation's duration — that active span is what\n // `resolveModelCallParent` reads. It also sets `data._sentrySpan`, so we don't here.\n const buildOperationSpan = (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>): Span | undefined => {\n const callOptions = isObjectLike(data.arguments[0]) ? data.arguments[0] : {};\n const telemetry = isObjectLike(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};\n // `isEnabled === false` means the user opted out — emit no span. But `isEnabled` is also `false` on\n // the telemetry object we swap in to suppress native spans, so don't mistake our own object for a\n // user opt-out (which would drop the span on a call whose options we already neutralized).\n if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {\n return undefined;\n }\n const message = build(callOptions, telemetry);\n // Stop `ai` from emitting its own native OTel spans for this call — we build the equivalent spans\n // from the channels, so the SDK's would be duplicates. Reads above have already captured everything\n // we need off `telemetry`.\n suppressNativeTelemetry(callOptions, telemetry);\n // The span active here is the operation's call site — `bindTracingChannelToSpan` only makes the\n // operation span active *after* this returns — so this is the span we later restore for a bubbled error.\n const callSiteSpan = getActiveSpan();\n const span = createSpanFromMessage(message, options);\n if (span) {\n messages.set(data, message);\n operationSpans.add(span);\n // `'v1'` models are v4 (v5/v6 are `'v2'`), where a thrown tool error bubbles out of the call rather\n // than being swallowed into `tool-error` content — so its tool spans must not self-capture the error.\n const isV4 = isObjectLike(callOptions.model) && callOptions.model.specificationVersion === 'v1';\n operationErrorInfoBySpan.set(span, { callSiteSpan, toolErrorsBubbleToCaller: isV4 });\n // v6's `executeToolCall` span: tracked so the v5 tool-`execute` patch can recognize (and skip)\n // tool calls it runs, since that patch sees this span as its active parent (see `patchToolExecute`).\n if (message.type === 'executeTool') {\n toolCallSpans.add(span);\n }\n const callId = asString(message.event.callId);\n if (callId) {\n callIdBySpan.set(span, callId);\n }\n recordingBySpan.set(span, recording(telemetry));\n telemetryMetadataBySpan.set(span, telemetry.metadata);\n // v5 has no `executeToolCall` channel, so patch each tool's `execute` to emit the tool-call span.\n // Inert on v6 (guarded inside `patchToolExecute` when the parent is `executeToolCall`'s own span).\n if (isObjectLike(callOptions.tools)) {\n patchOperationTools(callOptions.tools, options);\n }\n // v4 has no `resolveLanguageModel` chokepoint — the passed `LanguageModelV1` is called directly — so\n // patch its `doGenerate`/`doStream` here, at the operation start, instead. v5/v6 models are patched via\n // `resolveLanguageModel`, so restricting to v4 keeps this strictly additive and avoids double-patching.\n // Embedding models are also `'v1'` but expose no `doGenerate`/`doStream`, so the patch is a no-op for\n // `embed`/`embedMany`.\n if (isV4) {\n patchModelMethods(callOptions.model as PatchableModel, options);\n }\n }\n return span;\n };\n\n bindTracingChannelToSpan(\n channel,\n (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>) => buildOperationSpan(data),\n {\n beforeSpanEnd: (span, data) => {\n const message = messages.get(data);\n if (!message) {\n return;\n }\n // The helper's `error` handler already set the span status; only enrich from a successful result.\n if ('error' in data) {\n // The error bubbles out of the `ai` call. If nothing handles it before our global handler, that\n // handler runs outside any span — so stamp the operation's call-site span onto the error, letting\n // the unhandled-rejection handler restore it and correlate the report to this trace. This mirrors\n // the OTel path; it's a no-op when the error is handled earlier (e.g. a framework error handler).\n const callSiteSpan = operationErrorInfoBySpan.get(span)?.callSiteSpan;\n if (callSiteSpan && isObjectLike(data.error)) {\n addNonEnumerableProperty(data.error, '_sentry_active_span', callSiteSpan);\n }\n } else {\n // v6's `executeToolCall` returns the tool result/error object directly, whereas the shared core\n // (matching v7) expects it nested under `output`; wrap it so tool-error detection works.\n message.result = message.type === 'executeTool' ? { output: data.result } : data.result;\n enrichSpanOnEnd(span, message);\n }\n const isStream = message.type === 'streamText' || message.type === 'streamObject';\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: isStream ? undefined : message.result },\n );\n // A `streamText`/`streamObject` model call runs after this (synchronously-returning) operation's\n // span has already ended, so its `callId` entry must outlive the operation — it's cleared once the\n // model call settles (see `patchModelMethod`). Every other operation can clear here.\n if (!isStream) {\n clearOperationId(message);\n }\n messages.delete(data);\n },\n // `streamText`/`streamObject` return synchronously, so their operation span would otherwise end\n // before the stream drains — losing the aggregate usage/output. Defer the end and await the result's\n // completion promises (`totalUsage`/`text`/…, which resolve on drain), mirroring how v7's channel\n // defers the operation span on the SDK's total-usage promise.\n deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end),\n },\n );\n}\n\n/**\n * Keep a streamed `streamText`/`streamObject` operation span open until the stream drains, then enrich it\n * from the result's completion promises (usage/output/finish reason) and end it. `streamObject` resolves\n * `object` rather than `text`; `getOutputMessages` reads `text`, so a resolved object is stringified into\n * that field. Returns `false` for anything that isn't a streamed result, so the helper ends the span as usual.\n *\n * `streamObject`'s `object` rejects when the output fails schema validation, even though the model call\n * succeeded and `usage` resolved. It's awaited separately so that case still records the token usage on\n * the span before ending it as an error.\n */\nfunction deferStreamTextOperationEnd(\n span: Span,\n data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>,\n end: (error?: unknown) => void,\n): boolean {\n const message = messages.get(data);\n const type = message?.type;\n if (\n !message ||\n (type !== 'streamText' && type !== 'streamObject') ||\n 'error' in data ||\n !isStreamingResult(data.result)\n ) {\n return false;\n }\n\n const streamResult = data.result;\n void (async () => {\n try {\n const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([\n streamResult.totalUsage ?? streamResult.usage,\n streamResult.text,\n // Settle `object` into an outcome so a validation failure can't short-circuit the usage read.\n type === 'streamObject'\n ? Promise.resolve(streamResult.object).then(\n value => ({ value }),\n (error: unknown) => ({ value: undefined, error }),\n )\n : { value: undefined },\n streamResult.toolCalls,\n streamResult.finishReason,\n streamResult.response,\n ]);\n if ('error' in objectOutcome) {\n // The model call itself succeeded, so keep its usage on the span; `beforeSpanEnd` skips\n // enrichment once `end(error)` marks the payload as errored.\n message.result = { usage, toolCalls, finishReason, response };\n enrichSpanOnEnd(span, message);\n end(objectOutcome.error);\n return;\n }\n const object = objectOutcome.value;\n // Feed the resolved values back through the shared enrichment: `beforeSpanEnd` reads `data.result`.\n data.result = {\n usage,\n text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object),\n toolCalls,\n finishReason,\n response,\n };\n end();\n } catch (error) {\n end(error);\n }\n })();\n\n return true;\n}\n\n/** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */\nfunction isStreamingResult(result: unknown): result is Record<string, PromiseLike<unknown> | undefined> {\n return isObjectLike(result) && (isThenable(result.totalUsage) || isThenable(result.usage));\n}\n\nfunction isThenable(value: unknown): boolean {\n return isObjectLike(value) && typeof value.then === 'function';\n}\n\n/**\n * Neutralize `ai`'s native OpenTelemetry instrumentation for this call by pointing\n * `experimental_telemetry` at a copy with `isEnabled: false`. `ai`'s `getTracer` then returns its\n * internal no-op tracer, so it never creates (nor sets active) the duplicate `ai.*` spans we'd\n * otherwise have to drop.\n *\n * Only a call that explicitly enabled telemetry emits native spans — otherwise `ai` already uses its\n * no-op tracer, so there's nothing to suppress and we leave the user's options untouched. When\n * `isEnabled === true`, `telemetry` is `callOptions.experimental_telemetry` and `callOptions` is the\n * real first argument the SDK will read, so the reassignment takes effect for the wrapped call. We\n * replace rather than mutate in place, so a telemetry object the user shares across calls keeps its own\n * `isEnabled: true`; the replacement is tracked in `suppressedTelemetry` so our skip logic doesn't\n * later read it back as a user opt-out.\n */\nfunction suppressNativeTelemetry(callOptions: Record<string, unknown>, telemetry: Record<string, unknown>): void {\n if (telemetry.isEnabled !== true) {\n return;\n }\n const suppressed = { ...telemetry, isEnabled: false };\n suppressedTelemetry.add(suppressed);\n callOptions.experimental_telemetry = suppressed;\n}\n\n/**\n * `resolveLanguageModel` returns the model every call flows through. We don't span it — on `end` we\n * monkey-patch `doGenerate`/`doStream` on the returned model so each invocation produces a\n * `languageModelCall` span parented to the enclosing invoke_agent span.\n */\nfunction subscribeResolveLanguageModel(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n options: VercelAiChannelOptions,\n): void {\n tracingChannel<OrchestrionChannelContext>(channelName).subscribe({\n end(rawCtx) {\n const ctx = rawCtx;\n if (!isObjectLike(ctx.result)) {\n return;\n }\n // Patch the model's `doGenerate`/`doStream` once. The model call recovers its parent from the\n // active async context at call time (the operation span `bindTracingChannelToSpan` bound), which\n // propagates into the model call for `streamText` too, so there is nothing to capture on the model here.\n patchModelMethods(ctx.result, options);\n },\n start() {\n /* no-op */\n },\n asyncStart() {\n /* no-op */\n },\n asyncEnd() {\n /* no-op */\n },\n error() {\n /* no-op */\n },\n });\n}\n\n/**\n * Pick the invoke_agent span a model call should hang under: the operation span that\n * `bindTracingChannelToSpan` planted as the active async context for the enclosing operation.\n *\n * Because we suppress `ai`'s native telemetry (so it never installs its own span as active), the active\n * span inside `doGenerate`/`doStream` is our operation span. The `operationSpans` gate makes this return\n * `undefined` when the active span isn't one of ours — e.g. telemetry was disabled for the call so we\n * opened no operation span and the active span is the user's enclosing span — so the model call is\n * skipped rather than mis-parented.\n *\n * This covers `generateText`/`embed` (whose model call is awaited inside the operation body) and\n * `streamText` alike — `ai` initiates the stream synchronously within the operation's bound context, so\n * the later `doStream` continuation restores the same active span even though the operation's span has\n * already ended. The per-operation binding also disambiguates concurrent calls that share one model\n * instance (a single mutable slot on the shared model could not — it would hold whichever operation\n * resolved the model last).\n */\nfunction resolveModelCallParent(): Span | undefined {\n const active = getActiveSpan();\n return active && operationSpans.has(active) ? active : undefined;\n}\n\n/**\n * Idempotently patch a resolved model's `doGenerate`/`doStream` so each invocation emits a\n * `languageModelCall` span. Shared by the v5/v6 `resolveLanguageModel` path and the v4 path (which\n * patches the passed model at the operation start, as v4 has no `resolveLanguageModel`).\n */\nfunction patchModelMethods(model: PatchableModel, options: VercelAiChannelOptions): void {\n if (model[PATCHED]) {\n return;\n }\n model[PATCHED] = true;\n patchModelMethod(model, 'doGenerate', options);\n patchModelMethod(model, 'doStream', options);\n}\n\nfunction patchModelMethod(\n model: PatchableModel,\n method: 'doGenerate' | 'doStream',\n options: VercelAiChannelOptions,\n): void {\n const original = model[method];\n if (typeof original !== 'function') {\n return;\n }\n model[method] = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const parent = resolveModelCallParent();\n // No enclosing operation span (e.g. telemetry disabled for the call) → don't open a model-call span.\n if (!parent) {\n return Promise.resolve(original.apply(this, args));\n }\n\n const callArgs = isObjectLike(args[0]) ? args[0] : {};\n // Carry the operation's `callId` so the shared core can name the span after it\n // (`ai.generateText.doGenerate` / `ai.streamText.doStream`).\n const callId = callIdBySpan.get(parent);\n const message: VercelAiChannelMessage = {\n type: 'languageModelCall',\n event: {\n callId,\n provider: model.provider,\n modelId: model.modelId,\n // v4 nests the tool list under `mode.tools` (the `LanguageModelV1` call shape); v5+ passes a\n // top-level `tools` array. Reading both keeps `tool.definitions` populated on the model-call span.\n tools: callArgs.tools ?? (isObjectLike(callArgs.mode) ? callArgs.mode.tools : undefined),\n messages: callArgs.prompt,\n telemetryMetadata: telemetryMetadataBySpan.get(parent),\n // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on\n // the model-call span whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `languageModelCall` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return Promise.resolve(original.apply(this, args));\n }\n\n // `streamText` ends its operation span synchronously, so its `callId` entry was deliberately left in\n // place for this later model call; drop it now that we've used it.\n const clearStreamCallId = (): void => {\n if (method === 'doStream' && callId) {\n clearOperationCallId(callId);\n }\n };\n\n // Both the synchronous throw and the async rejection of the model call must end the span with an\n // error status (an `async` `doGenerate`/`doStream` that throws rejects rather than throwing here).\n const failSpan = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'unknown_error' });\n endSpan(span, { error });\n clearStreamCallId();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, args));\n return result.then(value => {\n // A streamed model call resolves to `{ stream, ... }` before the stream is consumed, so its\n // usage/finish/output only arrive as the stream drains. Tap it (same helper as the v7 path) and\n // defer ending this model-call span until then. The parent `invoke_agent` span is enriched\n // separately by `deferStreamTextOperationEnd`, which awaits the operation's own result promises.\n if (method === 'doStream' && isObjectLike(value) && isReadableStream(value.stream)) {\n value.stream = tapModelCallStream(\n span,\n value.stream,\n final => {\n message.result = { ...value, ...streamedResultToChannelResult(final) };\n enrichSpanOnEnd(span, message);\n endSpan(span, {});\n clearStreamCallId();\n },\n error => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'unknown_error',\n });\n endSpan(span, { error });\n clearStreamCallId();\n },\n );\n\n return value;\n }\n // `doGenerate` (and any non-stream result) settles with the full result; end here, start/end\n // bracket the call to match the channel timing.\n message.result = value;\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: value });\n clearStreamCallId();\n\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\n/**\n * Patch every executable tool on an operation's `tools` (a record keyed by tool name) so each\n * invocation emits a `gen_ai.execute_tool` span. v5 routes tool execution through the batch\n * `executeTools`, which binds `tool.execute` at call time — so replacing the `execute` property here\n * (before the call runs) is picked up. Tools without an `execute` (client-side tools) are skipped,\n * matching `executeTools`.\n */\nfunction patchOperationTools(tools: Record<string, unknown>, options: VercelAiChannelOptions): void {\n // This runs inside the channel `start` transform (no upstream try/catch), so a throw here would break\n // the user's `ai` call. Instrumentation must never do that — degrade to no tool span instead.\n try {\n for (const [toolName, tool] of Object.entries(tools)) {\n if (isObjectLike(tool)) {\n patchToolExecute(toolName, tool, tools, options);\n }\n }\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI tool patching failed.');\n }\n}\n\nfunction patchToolExecute(\n toolName: string,\n tool: PatchableTool,\n tools: Record<string, unknown>,\n options: VercelAiChannelOptions,\n): void {\n const original = tool.execute;\n if (typeof original !== 'function' || tool[TOOL_PATCHED]) {\n return;\n }\n tool[TOOL_PATCHED] = true;\n tool.execute = function (this: unknown, input: unknown, ...rest: unknown[]): unknown {\n // Skip if there's no enclosing operation span (telemetry disabled for the call), or if that parent\n // is itself a tool-call span — the latter means v6's `executeToolCall` already opened a span for\n // this call and is running `execute` inside it, so spanning again here would double-count. On v5\n // the parent is the enclosing `invoke_agent` operation span, so we proceed.\n const parent = resolveModelCallParent();\n if (!parent || toolCallSpans.has(parent)) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5 passes `{ toolCallId, messages, abortSignal, ... }` as the second argument to `execute`.\n const callOptions = isObjectLike(rest[0]) ? rest[0] : {};\n const message: VercelAiChannelMessage = {\n type: 'executeTool',\n event: {\n callId: callIdBySpan.get(parent),\n toolCall: { toolName, toolCallId: asString(callOptions.toolCallId), input },\n // The `tools` record (keyed by name) lets the shared core backfill the tool's `description`.\n tools,\n // Inherit the enclosing operation's per-call recording flags so tool inputs/outputs are recorded\n // whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `executeTool` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5's `executeTools` catches a thrown tool error and turns it into `tool-error` content rather than\n // rejecting, so the user never sees a rejection — we must capture it here. On v4 the rejection bubbles\n // out of the call and reaches the user's error handling (or our global handlers), so we only mark the\n // span and leave the capture to them, avoiding a duplicate report. Rethrow either way so `executeTools`\n // still produces its `tool-error` result (v5) and the rejection propagates (v4).\n const failSpan = (error: unknown): never => {\n if (operationErrorInfoBySpan.get(parent)?.toolErrorsBubbleToCaller) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'tool_error' });\n } else {\n captureToolError(span, message, error);\n }\n endSpan(span, { error });\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, [input, ...rest]));\n return result.then(value => {\n // The shared core (matching v6/v7) expects the tool result nested under `output`.\n message.result = { output: value };\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: message.result });\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\nfunction endSpan(span: Span, result: GenAiSpanResult<unknown>): void {\n runVercelAiSpanEnd(span, result);\n span.end();\n}\n\nfunction buildTextMessage(type: 'generateText' | 'streamText' | 'streamObject' | 'generateObject'): MessageBuilder {\n return (options, telemetry) => ({\n type,\n event: {\n callId: nextCallId(),\n operationId: `ai.${type}`,\n functionId: asString(telemetry.functionId),\n ...modelFields(options.model),\n maxRetries: options.maxRetries,\n // The `ai` SDK takes the system prompt as a top-level `system` option (all of v4/v5/v6); the\n // shared core lifts `event.instructions` into the system-instructions attribute, matching v7's\n // native channel (which carries it as a distinct field rather than inside the messages array).\n instructions: options.system,\n // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string\n // `prompt` becomes a single user message, matching the SDK's own normalization.\n messages: normalizePromptMessages(options),\n // v7's native start event carries `providerOptions`; the shared core reads the OpenAI\n // Conversations API id from it.\n providerOptions: options.providerOptions,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n });\n}\n\nfunction normalizePromptMessages(options: Record<string, unknown>): unknown {\n if (Array.isArray(options.messages)) {\n return options.messages;\n }\n if (typeof options.prompt === 'string') {\n return [{ role: 'user', content: options.prompt }];\n }\n return options.messages ?? options.prompt;\n}\n\nfunction recording(telemetry: Record<string, unknown>): { recordInputs: unknown; recordOutputs: unknown } {\n // Match the OTel integration's per-call default: an explicit `recordInputs`/`recordOutputs` wins, but a\n // call that merely enables telemetry (`isEnabled: true`, no explicit flags) defaults both to `true`.\n // Unlike v7's native `ai:telemetry` channel, the orchestrion channels expose `isEnabled`, so — as noted\n // in `resolveRecording` — we CAN reproduce that default here (the native-channel subscriber cannot).\n const enabledDefault = telemetry.isEnabled === true ? true : undefined;\n return {\n recordInputs: telemetry.recordInputs ?? enabledDefault,\n recordOutputs: telemetry.recordOutputs ?? enabledDefault,\n };\n}\n\nfunction modelFields(model: unknown): { provider?: string; modelId?: string } {\n return { provider: modelField(model, 'provider'), modelId: modelField(model, 'modelId') };\n}\n\nfunction modelField(model: unknown, field: 'modelId' | 'provider'): string | undefined {\n return isObjectLike(model) ? asString(model[field]) : undefined;\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,UAAU,OAAO,4BAA4B;AACnD,MAAM,eAAe,OAAO,2BAA2B;AASvD,IAAI,gBAAgB;AACpB,SAAS,aAAqB;CAC5B,OAAO,MAAM,EAAE;AACjB;AAIA,MAAM,2BAAW,IAAI,QAA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Y,QAAQ;AACrC;AAEA,SAAS,UAAU,WAAuF;CAKxG,MAAM,iBAAiB,UAAU,cAAc,OAAO,OAAO,KAAA;CAC7D,OAAO;EACL,cAAc,UAAU,gBAAgB;EACxC,eAAe,UAAU,iBAAiB;CAC5C;AACF;AAEA,SAAS,YAAY,OAAyD;CAC5E,OAAO;EAAE,UAAU,WAAW,OAAO,UAAU;EAAG,SAAS,WAAW,OAAO,SAAS;CAAE;AAC1F;AAEA,SAAS,WAAW,OAAgB,OAAmD;CACrF,OAAO,aAAa,KAAK,IAAI,SAAS,MAAM,MAAM,IAAI,KAAA;AACxD"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { DEBUG_BUILD } from "../debug-build.js";
|
|
2
|
+
import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
3
|
+
import { _INTERNAL_captureLog, debug, isObjectLike } from "@sentry/core";
|
|
4
|
+
// src/integrations/winston.ts
|
|
5
|
+
const DEFAULT_CAPTURED_LEVELS = [
|
|
6
|
+
"trace",
|
|
7
|
+
"debug",
|
|
8
|
+
"info",
|
|
9
|
+
"warn",
|
|
10
|
+
"error",
|
|
11
|
+
"fatal"
|
|
12
|
+
];
|
|
13
|
+
const LEVEL_SYMBOL = Symbol.for("level");
|
|
14
|
+
const MESSAGE_SYMBOL = Symbol.for("message");
|
|
15
|
+
const SPLAT_SYMBOL = Symbol.for("splat");
|
|
16
|
+
/**
|
|
17
|
+
* Creates a new Sentry Winston transport that fowards logs to Sentry.
|
|
18
|
+
*
|
|
19
|
+
* Supports Winston 3.x.x.
|
|
20
|
+
*
|
|
21
|
+
* @param TransportClass - The Winston transport class to extend.
|
|
22
|
+
* @returns The extended transport class.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* const winston = require('winston');
|
|
27
|
+
* const Transport = require('winston-transport');
|
|
28
|
+
*
|
|
29
|
+
* const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);
|
|
30
|
+
*
|
|
31
|
+
* const logger = winston.createLogger({
|
|
32
|
+
* transports: [new SentryWinstonTransport()],
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
function createSentryWinstonTransport(TransportClass, sentryWinstonOptions) {
|
|
37
|
+
class SentryWinstonTransport extends TransportClass {
|
|
38
|
+
constructor(options) {
|
|
39
|
+
super(options);
|
|
40
|
+
this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Forwards a winston log to the Sentry SDK.
|
|
44
|
+
*/
|
|
45
|
+
log(info, callback) {
|
|
46
|
+
try {
|
|
47
|
+
setImmediate(() => {
|
|
48
|
+
this.emit("logged", info);
|
|
49
|
+
});
|
|
50
|
+
if (!isObjectLike(info)) return;
|
|
51
|
+
const levelFromSymbol = info[LEVEL_SYMBOL];
|
|
52
|
+
const { level, message, timestamp, ...attributes } = info;
|
|
53
|
+
attributes[LEVEL_SYMBOL] = void 0;
|
|
54
|
+
attributes[MESSAGE_SYMBOL] = void 0;
|
|
55
|
+
attributes[SPLAT_SYMBOL] = void 0;
|
|
56
|
+
const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol];
|
|
57
|
+
const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol];
|
|
58
|
+
const logSeverityLevel = customLevel ?? winstonLogLevel ?? "info";
|
|
59
|
+
if (this._levels.has(logSeverityLevel)) _INTERNAL_captureLog({
|
|
60
|
+
level: logSeverityLevel,
|
|
61
|
+
message,
|
|
62
|
+
attributes: {
|
|
63
|
+
...attributes,
|
|
64
|
+
[SENTRY_ORIGIN]: "auto.log.winston"
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
else if (!customLevel && !winstonLogLevel) DEBUG_BUILD && debug.log(`Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the "customLevelMap" option of the Sentry Winston transport.`);
|
|
68
|
+
} catch {}
|
|
69
|
+
if (callback) callback();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return SentryWinstonTransport;
|
|
73
|
+
}
|
|
74
|
+
const WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = {
|
|
75
|
+
silly: "trace",
|
|
76
|
+
debug: "debug",
|
|
77
|
+
verbose: "debug",
|
|
78
|
+
http: "debug",
|
|
79
|
+
info: "info",
|
|
80
|
+
notice: "info",
|
|
81
|
+
warn: "warn",
|
|
82
|
+
warning: "warn",
|
|
83
|
+
error: "error",
|
|
84
|
+
emerg: "fatal",
|
|
85
|
+
alert: "fatal",
|
|
86
|
+
crit: "fatal"
|
|
87
|
+
};
|
|
88
|
+
export { createSentryWinstonTransport };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=winston.js.map
|
|
@@ -0,0 +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,6 +1,7 @@
|
|
|
1
1
|
import { parse } from "../../vendored/meriyah/dist/meriyah2.js";
|
|
2
2
|
import { subscriberExportForModule } from "../config/channel-integration-definitions.js";
|
|
3
3
|
import { MODULE_REGISTRATION_TRANSFORM } from "../config/registration-only.js";
|
|
4
|
+
import { stringifyForCodeInjection } from "@sentry/core";
|
|
4
5
|
// src/orchestrion/bundler/moduleInjectedTransform.ts
|
|
5
6
|
const injectedPrograms = /* @__PURE__ */ new WeakSet();
|
|
6
7
|
const DEFAULT_IMPORT_SPECIFIER = "@sentry/server-utils";
|
|
@@ -37,8 +38,8 @@ const ORCHESTRION_BUNDLER_MARKER_BANNER = ";(function(){var g=globalThis.__SENTR
|
|
|
37
38
|
*
|
|
38
39
|
* The specifier is parameterized for bundlers where the bare import emitted
|
|
39
40
|
* inside a transformed `node_modules` file can't resolve (Turbopack under
|
|
40
|
-
* isolated installs); it's embedded via `
|
|
41
|
-
* paths survive.
|
|
41
|
+
* isolated installs); it's embedded via `stringifyForCodeInjection` so
|
|
42
|
+
* absolute Windows paths survive.
|
|
42
43
|
*
|
|
43
44
|
* The call result is assigned to a global rather than discarded. The helper
|
|
44
45
|
* returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare
|
|
@@ -49,8 +50,8 @@ const ORCHESTRION_BUNDLER_MARKER_BANNER = ";(function(){var g=globalThis.__SENTR
|
|
|
49
50
|
*/
|
|
50
51
|
function moduleInjectedSnippet(moduleName, exportName, esm, importSpecifier) {
|
|
51
52
|
const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : "orchestrionModuleInjected";
|
|
52
|
-
const importStmt = esm ? `import { ${bindings} } from ${
|
|
53
|
-
const args = exportName ? `${
|
|
53
|
+
const importStmt = esm ? `import { ${bindings} } from ${stringifyForCodeInjection(importSpecifier)};` : `const { ${bindings} } = require(${stringifyForCodeInjection(importSpecifier)});`;
|
|
54
|
+
const args = exportName ? `${stringifyForCodeInjection(moduleName)}, () => ${exportName}()` : stringifyForCodeInjection(moduleName);
|
|
54
55
|
return `${importStmt}\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;
|
|
55
56
|
}
|
|
56
57
|
/**
|
|
@@ -68,7 +69,7 @@ function moduleInjectedSnippet(moduleName, exportName, esm, importSpecifier) {
|
|
|
68
69
|
function selfProvidedSnippet(moduleName, filePath) {
|
|
69
70
|
const marker = "globalThis.__SENTRY_ORCHESTRION__";
|
|
70
71
|
const self = `./${filePath.split("/").pop()}`;
|
|
71
|
-
return `import * as __SENTRY_SELF_PROVIDED__ from ${
|
|
72
|
+
return `import * as __SENTRY_SELF_PROVIDED__ from ${stringifyForCodeInjection(self)};\n(${marker} = ${marker} || {});\n(${marker}.providedModules = ${marker}.providedModules || {});\nObject.defineProperty(${marker}.providedModules, ${stringifyForCodeInjection(moduleName)}, { configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });`;
|
|
72
73
|
}
|
|
73
74
|
/**
|
|
74
75
|
* The unified `customTransforms` every orchestrion bundler plugin (and the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"moduleInjectedTransform.js","names":[],"sources":["../../../../src/orchestrion/bundler/moduleInjectedTransform.ts"],"sourcesContent":["import type { CustomTransform } from '../apmTypes';\nimport { parse } from 'meriyah';\nimport { subscriberExportForModule } from '../config/channel-integration-definitions';\nimport { MODULE_REGISTRATION_TRANSFORM } from '../config/registration-only';\n\n// Tracks Program nodes we already injected into, so a package with several\n// instrumented files (or several configs pointing at one file) is injected only\n// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.\nconst injectedPrograms = new WeakSet<object>();\n\ninterface ProgramNode {\n type: string;\n body: Array<{ type: string; directive?: string }>;\n}\n\n// Where the injected snippet imports from: the `orchestrionModuleInjected`\n// helper and the module's channel-subscriber factory both live on the main\n// `@sentry/server-utils` entry, so a single import serves both. The ESM barrel\n// tree-shakes to just the helper and the factories actually referenced.\nconst DEFAULT_IMPORT_SPECIFIER = '@sentry/server-utils';\n\n/**\n * Assignment target that keeps the injected call from being tree-shaken. See\n * {@link moduleInjectedSnippet}. The value written is always `undefined`; only\n * the assignment matters.\n */\nconst MODULE_INJECTED_SINK = 'globalThis.__SENTRY_ORCHESTRION_INJECT__';\n\n/**\n * Entry-chunk banner that marks \"the bundler plugin ran\" for\n * `detectOrchestrionSetup()`. Merge-only (`g.bundler = g.bundler || new Set()`)\n * so it can never clobber module names already recorded by an injected snippet\n * that happened to run first; the names themselves arrive per module, when each\n * transformed module is evaluated and its snippet calls\n * `orchestrionModuleInjected`.\n */\nexport const ORCHESTRION_BUNDLER_MARKER_BANNER =\n ';(function(){var g=globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{};g.bundler=g.bundler||new Set();})();';\n\n/**\n * Snippet injected into each instrumented module. It imports the\n * `orchestrionModuleInjected` helper — plus the module's channel-subscriber\n * factory, when it has one — from `@sentry/server-utils` and calls the helper\n * with the module's real name. The helper records the module on the global\n * marker, stores the factory, and emits the `orchestrion.module-injected` client\n * event, so it runs exactly when the module is evaluated — the moment its\n * channels can start publishing. That per-module timing is what keeps\n * subscriptions lazy (Node caps diagnostics channels in use at 1024).\n *\n * Importing the single named factory (rather than a central dispatch that pulls\n * in every subscriber) is what makes this tree-shake: a bundle carries only the\n * subscriber code for packages actually transformed into it. The helper is\n * generic (references no factory), so importing it alongside doesn't pull\n * siblings.\n *\n * The specifier is parameterized for bundlers where the bare import emitted\n * inside a transformed `node_modules` file can't resolve (Turbopack under\n * isolated installs); it's embedded via `JSON.stringify` so absolute Windows\n * paths survive.\n *\n * The call result is assigned to a global rather than discarded. The helper\n * returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare\n * call statement is something a bundler can prove droppable: rollup >= 4.63.0\n * does exactly that and removes the whole registration, leaving the module\n * instrumented but unsubscribed. Writing to a property of `globalThis` is a\n * side effect no bundler can shake out, so the call survives.\n */\nfunction moduleInjectedSnippet(\n moduleName: string,\n exportName: string | undefined,\n esm: boolean,\n importSpecifier: string,\n): string {\n const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : 'orchestrionModuleInjected';\n const importStmt = esm\n ? `import { ${bindings} } from ${JSON.stringify(importSpecifier)};`\n : `const { ${bindings} } = require(${JSON.stringify(importSpecifier)});`;\n\n // The arrow defers reading `exportName` to `init()`. `@sentry/*/vite` imports some packages into\n // their own integration module (e.g. Mastra's), and in that cycle a direct read would hit the TDZ.\n const args = exportName ? `${JSON.stringify(moduleName)}, () => ${exportName}()` : JSON.stringify(moduleName);\n return `${importStmt}\\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;\n}\n\n/**\n * Publishes the module's own namespace on `providedModules`. For `@flue/runtime`'s `dist/index.mjs`,\n * this prepends roughly:\n *\n * ```js\n * import * as __SENTRY_SELF_PROVIDED__ from \"./index.mjs\";\n * globalThis.__SENTRY_ORCHESTRION__.providedModules[\"@flue/runtime\"] = __SENTRY_SELF_PROVIDED__; // as a getter\n * ```\n *\n * A self-import adds no edge to the module graph; importing the package into a Sentry module would\n * close a cycle through every instrumented dependency, since those all import `@sentry/server-utils`.\n */\nfunction selfProvidedSnippet(moduleName: string, filePath: string): string {\n const marker = 'globalThis.__SENTRY_ORCHESTRION__';\n const self = `./${filePath.split('/').pop()}`;\n return (\n `import * as __SENTRY_SELF_PROVIDED__ from ${JSON.stringify(self)};\\n` +\n `(${marker} = ${marker} || {});\\n` +\n `(${marker}.providedModules = ${marker}.providedModules || {});\\n` +\n `Object.defineProperty(${marker}.providedModules, ${JSON.stringify(moduleName)}, ` +\n '{ configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });'\n );\n}\n\nexport interface ModuleInjectedTransformsOptions {\n /** Packages whose ESM entry publishes its own namespace on `providedModules`. */\n selfProvidedModules?: readonly string[];\n}\n\n/**\n * The unified `customTransforms` every orchestrion bundler plugin (and the\n * webpack/Turbopack loader) applies: an override for orchestrion's built-in\n * `tracingChannelImport` transform, which runs (via `tracingChannelDeclaration`)\n * for every file that gets a channel wrapped — the one hook that reaches every\n * instrumented module without any extra instrumentation configs. It chains the\n * default (which splices the `diagnostics_channel` import and bails when it is\n * already present), then splices the module-injected snippet in after any\n * `'use strict'` directive.\n *\n * Invoked once per wrapped channel, so the `WeakSet` keeps the snippet to one\n * per file. Requires `@apm-js-collab/code-transformer` >= 0.18.1, where\n * built-ins dispatch through the override map and expose the originals on\n * `state.transforms.defaults`.\n *\n * Also carries the registration-only operator, which splices the same snippet\n * without any channel injection — for library versions whose tracing channels\n * are native.\n */\nexport function moduleInjectedTransforms(\n // A function is read per injected file — the webpack/Turbopack loader uses it\n // to supply a per-file relative specifier (Turbopack supports neither\n // absolute-path imports nor bare specifiers that don't resolve from the\n // importing file's location).\n importSpecifier?: string | (() => string | undefined),\n { selfProvidedModules = [] }: ModuleInjectedTransformsOptions = {},\n): Record<string, CustomTransform> {\n const spliceModuleInjected = (state: unknown, program: unknown): void => {\n const { moduleType, module } = state as {\n moduleType?: string;\n module?: { name?: string; filePath?: string | RegExp };\n };\n\n const node = program as ProgramNode;\n if (injectedPrograms.has(node)) {\n return;\n }\n\n const moduleName = module?.name;\n if (!moduleName) {\n return;\n }\n\n injectedPrograms.add(node);\n\n const specifier =\n (typeof importSpecifier === 'function' ? importSpecifier() : importSpecifier) ?? DEFAULT_IMPORT_SPECIFIER;\n const exportName = subscriberExportForModule(moduleName);\n const esm = moduleType === 'esm';\n const selfProvided =\n esm && typeof module?.filePath === 'string' && selfProvidedModules.includes(moduleName)\n ? `${selfProvidedSnippet(moduleName, module.filePath)}\\n`\n : '';\n const statements = parse(selfProvided + moduleInjectedSnippet(moduleName, exportName, esm, specifier), {\n module: esm,\n next: true,\n }).body as ProgramNode['body'];\n\n const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');\n node.body.splice(directiveIndex + 1, 0, ...statements);\n };\n\n const injectModuleInjected: CustomTransform = (state, program, parent, ancestry) => {\n const { transforms } = state as {\n transforms: { defaults: { tracingChannelImport: CustomTransform } };\n };\n\n transforms.defaults.tracingChannelImport(state, program, parent, ancestry);\n spliceModuleInjected(state, program);\n };\n\n // Operator for registration-only configs (`transform` field, see\n // `config/registration-only.ts`): dispatched INSTEAD of `traceSync`, so no\n // channel is declared and no function is wrapped. Their `astQuery: 'Program'`\n // matches only the file root, so `node` is the Program itself.\n const injectRegistrationOnly: CustomTransform = (state, node) => {\n spliceModuleInjected(state, node);\n };\n\n return {\n tracingChannelImport: injectModuleInjected,\n [MODULE_REGISTRATION_TRANSFORM]: injectRegistrationOnly,\n };\n}\n"],"mappings":";;;;AAQA,MAAM,mCAAmB,IAAI,QAAgB;AAW7C,MAAM,2BAA2B;;;;;;AAOjC,MAAM,uBAAuB;;;;;;;;;AAU7B,MAAa,oCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BF,SAAS,sBACP,YACA,YACA,KACA,iBACQ;CACR,MAAM,WAAW,aAAa,8BAA8B,eAAe;CAC3E,MAAM,aAAa,MACf,YAAY,SAAS,UAAU,KAAK,UAAU,eAAe,EAAE,KAC/D,WAAW,SAAS,eAAe,KAAK,UAAU,eAAe,EAAE;CAIvE,MAAM,OAAO,aAAa,GAAG,KAAK,UAAU,UAAU,EAAE,UAAU,WAAW,MAAM,KAAK,UAAU,UAAU;CAC5G,OAAO,GAAG,WAAW,IAAI,qBAAqB,+BAA+B,KAAK;AACpF;;;;;;;;;;;;;AAcA,SAAS,oBAAoB,YAAoB,UAA0B;CACzE,MAAM,SAAS;CACf,MAAM,OAAO,KAAK,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI;CAC1C,OACE,6CAA6C,KAAK,UAAU,IAAI,EAAE,MAC9D,OAAO,KAAK,OAAO,aACnB,OAAO,qBAAqB,OAAO,kDACd,OAAO,oBAAoB,KAAK,UAAU,UAAU,EAAE;AAGnF;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBAKd,iBACA,EAAE,sBAAsB,CAAC,MAAuC,CAAC,GAChC;CACjC,MAAM,wBAAwB,OAAgB,YAA2B;EACvE,MAAM,EAAE,YAAY,WAAW;EAK/B,MAAM,OAAO;EACb,IAAI,iBAAiB,IAAI,IAAI,GAC3B;EAGF,MAAM,aAAa,QAAQ;EAC3B,IAAI,CAAC,YACH;EAGF,iBAAiB,IAAI,IAAI;EAEzB,MAAM,aACH,OAAO,oBAAoB,aAAa,gBAAgB,IAAI,oBAAoB;EACnF,MAAM,aAAa,0BAA0B,UAAU;EACvD,MAAM,MAAM,eAAe;EAC3B,MAAM,eACJ,OAAO,OAAO,QAAQ,aAAa,YAAY,oBAAoB,SAAS,UAAU,IAClF,GAAG,oBAAoB,YAAY,OAAO,QAAQ,EAAE,MACpD;EACN,MAAM,aAAa,MAAM,eAAe,sBAAsB,YAAY,YAAY,KAAK,SAAS,GAAG;GACrG,QAAQ;GACR,MAAM;EACR,CAAC,CAAC,CAAC;EAEH,MAAM,iBAAiB,KAAK,KAAK,WAAU,MAAK,EAAE,SAAS,yBAAyB,EAAE,cAAc,YAAY;EAChH,KAAK,KAAK,OAAO,iBAAiB,GAAG,GAAG,GAAG,UAAU;CACvD;CAEA,MAAM,wBAAyC,OAAO,SAAS,QAAQ,aAAa;EAClF,MAAM,EAAE,eAAe;EAIvB,WAAW,SAAS,qBAAqB,OAAO,SAAS,QAAQ,QAAQ;EACzE,qBAAqB,OAAO,OAAO;CACrC;CAMA,MAAM,0BAA2C,OAAO,SAAS;EAC/D,qBAAqB,OAAO,IAAI;CAClC;CAEA,OAAO;EACL,sBAAsB;GACrB,gCAAgC;CACnC;AACF"}
|
|
1
|
+
{"version":3,"file":"moduleInjectedTransform.js","names":[],"sources":["../../../../src/orchestrion/bundler/moduleInjectedTransform.ts"],"sourcesContent":["import type { CustomTransform } from '../apmTypes';\nimport { parse } from 'meriyah';\nimport { subscriberExportForModule } from '../config/channel-integration-definitions';\nimport { MODULE_REGISTRATION_TRANSFORM } from '../config/registration-only';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\n// Tracks Program nodes we already injected into, so a package with several\n// instrumented files (or several configs pointing at one file) is injected only\n// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.\nconst injectedPrograms = new WeakSet<object>();\n\ninterface ProgramNode {\n type: string;\n body: Array<{ type: string; directive?: string }>;\n}\n\n// Where the injected snippet imports from: the `orchestrionModuleInjected`\n// helper and the module's channel-subscriber factory both live on the main\n// `@sentry/server-utils` entry, so a single import serves both. The ESM barrel\n// tree-shakes to just the helper and the factories actually referenced.\nconst DEFAULT_IMPORT_SPECIFIER = '@sentry/server-utils';\n\n/**\n * Assignment target that keeps the injected call from being tree-shaken. See\n * {@link moduleInjectedSnippet}. The value written is always `undefined`; only\n * the assignment matters.\n */\nconst MODULE_INJECTED_SINK = 'globalThis.__SENTRY_ORCHESTRION_INJECT__';\n\n/**\n * Entry-chunk banner that marks \"the bundler plugin ran\" for\n * `detectOrchestrionSetup()`. Merge-only (`g.bundler = g.bundler || new Set()`)\n * so it can never clobber module names already recorded by an injected snippet\n * that happened to run first; the names themselves arrive per module, when each\n * transformed module is evaluated and its snippet calls\n * `orchestrionModuleInjected`.\n */\nexport const ORCHESTRION_BUNDLER_MARKER_BANNER =\n ';(function(){var g=globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{};g.bundler=g.bundler||new Set();})();';\n\n/**\n * Snippet injected into each instrumented module. It imports the\n * `orchestrionModuleInjected` helper — plus the module's channel-subscriber\n * factory, when it has one — from `@sentry/server-utils` and calls the helper\n * with the module's real name. The helper records the module on the global\n * marker, stores the factory, and emits the `orchestrion.module-injected` client\n * event, so it runs exactly when the module is evaluated — the moment its\n * channels can start publishing. That per-module timing is what keeps\n * subscriptions lazy (Node caps diagnostics channels in use at 1024).\n *\n * Importing the single named factory (rather than a central dispatch that pulls\n * in every subscriber) is what makes this tree-shake: a bundle carries only the\n * subscriber code for packages actually transformed into it. The helper is\n * generic (references no factory), so importing it alongside doesn't pull\n * siblings.\n *\n * The specifier is parameterized for bundlers where the bare import emitted\n * inside a transformed `node_modules` file can't resolve (Turbopack under\n * isolated installs); it's embedded via `stringifyForCodeInjection` so\n * absolute Windows paths survive.\n *\n * The call result is assigned to a global rather than discarded. The helper\n * returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare\n * call statement is something a bundler can prove droppable: rollup >= 4.63.0\n * does exactly that and removes the whole registration, leaving the module\n * instrumented but unsubscribed. Writing to a property of `globalThis` is a\n * side effect no bundler can shake out, so the call survives.\n */\nfunction moduleInjectedSnippet(\n moduleName: string,\n exportName: string | undefined,\n esm: boolean,\n importSpecifier: string,\n): string {\n const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : 'orchestrionModuleInjected';\n const importStmt = esm\n ? `import { ${bindings} } from ${stringifyForCodeInjection(importSpecifier)};`\n : `const { ${bindings} } = require(${stringifyForCodeInjection(importSpecifier)});`;\n\n // The arrow defers reading `exportName` to `init()`. `@sentry/*/vite` imports some packages into\n // their own integration module (e.g. Mastra's), and in that cycle a direct read would hit the TDZ.\n const args = exportName\n ? `${stringifyForCodeInjection(moduleName)}, () => ${exportName}()`\n : stringifyForCodeInjection(moduleName);\n return `${importStmt}\\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;\n}\n\n/**\n * Publishes the module's own namespace on `providedModules`. For `@flue/runtime`'s `dist/index.mjs`,\n * this prepends roughly:\n *\n * ```js\n * import * as __SENTRY_SELF_PROVIDED__ from \"./index.mjs\";\n * globalThis.__SENTRY_ORCHESTRION__.providedModules[\"@flue/runtime\"] = __SENTRY_SELF_PROVIDED__; // as a getter\n * ```\n *\n * A self-import adds no edge to the module graph; importing the package into a Sentry module would\n * close a cycle through every instrumented dependency, since those all import `@sentry/server-utils`.\n */\nfunction selfProvidedSnippet(moduleName: string, filePath: string): string {\n const marker = 'globalThis.__SENTRY_ORCHESTRION__';\n const self = `./${filePath.split('/').pop()}`;\n return (\n `import * as __SENTRY_SELF_PROVIDED__ from ${stringifyForCodeInjection(self)};\\n` +\n `(${marker} = ${marker} || {});\\n` +\n `(${marker}.providedModules = ${marker}.providedModules || {});\\n` +\n `Object.defineProperty(${marker}.providedModules, ${stringifyForCodeInjection(moduleName)}, ` +\n '{ configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });'\n );\n}\n\nexport interface ModuleInjectedTransformsOptions {\n /** Packages whose ESM entry publishes its own namespace on `providedModules`. */\n selfProvidedModules?: readonly string[];\n}\n\n/**\n * The unified `customTransforms` every orchestrion bundler plugin (and the\n * webpack/Turbopack loader) applies: an override for orchestrion's built-in\n * `tracingChannelImport` transform, which runs (via `tracingChannelDeclaration`)\n * for every file that gets a channel wrapped — the one hook that reaches every\n * instrumented module without any extra instrumentation configs. It chains the\n * default (which splices the `diagnostics_channel` import and bails when it is\n * already present), then splices the module-injected snippet in after any\n * `'use strict'` directive.\n *\n * Invoked once per wrapped channel, so the `WeakSet` keeps the snippet to one\n * per file. Requires `@apm-js-collab/code-transformer` >= 0.18.1, where\n * built-ins dispatch through the override map and expose the originals on\n * `state.transforms.defaults`.\n *\n * Also carries the registration-only operator, which splices the same snippet\n * without any channel injection — for library versions whose tracing channels\n * are native.\n */\nexport function moduleInjectedTransforms(\n // A function is read per injected file — the webpack/Turbopack loader uses it\n // to supply a per-file relative specifier (Turbopack supports neither\n // absolute-path imports nor bare specifiers that don't resolve from the\n // importing file's location).\n importSpecifier?: string | (() => string | undefined),\n { selfProvidedModules = [] }: ModuleInjectedTransformsOptions = {},\n): Record<string, CustomTransform> {\n const spliceModuleInjected = (state: unknown, program: unknown): void => {\n const { moduleType, module } = state as {\n moduleType?: string;\n module?: { name?: string; filePath?: string | RegExp };\n };\n\n const node = program as ProgramNode;\n if (injectedPrograms.has(node)) {\n return;\n }\n\n const moduleName = module?.name;\n if (!moduleName) {\n return;\n }\n\n injectedPrograms.add(node);\n\n const specifier =\n (typeof importSpecifier === 'function' ? importSpecifier() : importSpecifier) ?? DEFAULT_IMPORT_SPECIFIER;\n const exportName = subscriberExportForModule(moduleName);\n const esm = moduleType === 'esm';\n const selfProvided =\n esm && typeof module?.filePath === 'string' && selfProvidedModules.includes(moduleName)\n ? `${selfProvidedSnippet(moduleName, module.filePath)}\\n`\n : '';\n const statements = parse(selfProvided + moduleInjectedSnippet(moduleName, exportName, esm, specifier), {\n module: esm,\n next: true,\n }).body as ProgramNode['body'];\n\n const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');\n node.body.splice(directiveIndex + 1, 0, ...statements);\n };\n\n const injectModuleInjected: CustomTransform = (state, program, parent, ancestry) => {\n const { transforms } = state as {\n transforms: { defaults: { tracingChannelImport: CustomTransform } };\n };\n\n transforms.defaults.tracingChannelImport(state, program, parent, ancestry);\n spliceModuleInjected(state, program);\n };\n\n // Operator for registration-only configs (`transform` field, see\n // `config/registration-only.ts`): dispatched INSTEAD of `traceSync`, so no\n // channel is declared and no function is wrapped. Their `astQuery: 'Program'`\n // matches only the file root, so `node` is the Program itself.\n const injectRegistrationOnly: CustomTransform = (state, node) => {\n spliceModuleInjected(state, node);\n };\n\n return {\n tracingChannelImport: injectModuleInjected,\n [MODULE_REGISTRATION_TRANSFORM]: injectRegistrationOnly,\n };\n}\n"],"mappings":";;;;;AASA,MAAM,mCAAmB,IAAI,QAAgB;AAW7C,MAAM,2BAA2B;;;;;;AAOjC,MAAM,uBAAuB;;;;;;;;;AAU7B,MAAa,oCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BF,SAAS,sBACP,YACA,YACA,KACA,iBACQ;CACR,MAAM,WAAW,aAAa,8BAA8B,eAAe;CAC3E,MAAM,aAAa,MACf,YAAY,SAAS,UAAU,0BAA0B,eAAe,EAAE,KAC1E,WAAW,SAAS,eAAe,0BAA0B,eAAe,EAAE;CAIlF,MAAM,OAAO,aACT,GAAG,0BAA0B,UAAU,EAAE,UAAU,WAAW,MAC9D,0BAA0B,UAAU;CACxC,OAAO,GAAG,WAAW,IAAI,qBAAqB,+BAA+B,KAAK;AACpF;;;;;;;;;;;;;AAcA,SAAS,oBAAoB,YAAoB,UAA0B;CACzE,MAAM,SAAS;CACf,MAAM,OAAO,KAAK,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI;CAC1C,OACE,6CAA6C,0BAA0B,IAAI,EAAE,MACzE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-commonjs` options for builds that bundle CommonJS packages while their
|
|
20
20
|
* dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks
|
|
21
21
|
* direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).
|
|
22
|
-
* Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.
|
|
22
|
+
* Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.
|
|
23
23
|
*/
|
|
24
24
|
function commonJSInteropOptions() {
|
|
25
25
|
return {
|
|
@@ -29,10 +29,10 @@ function commonJSInteropOptions() {
|
|
|
29
29
|
}
|
|
30
30
|
const COMMONJS_HELPERS_ID = "\0commonjsHelpers.js";
|
|
31
31
|
const BROKEN_NAMESPACE_CHECK = "Object.keys(n).length === 1";
|
|
32
|
-
const FIXED_NAMESPACE_CHECK = "Object.keys(n).filter(k => k !== 'module.exports').length === 1";
|
|
32
|
+
const FIXED_NAMESPACE_CHECK = "(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))";
|
|
33
33
|
/**
|
|
34
|
-
* Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23 by patching the
|
|
35
|
-
* namespace check in its helpers module. The patch applies only while the exact broken
|
|
34
|
+
* Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the
|
|
35
|
+
* broken namespace check in its helpers module. The patch applies only while the exact broken
|
|
36
36
|
* expression exists, so it retires itself once the plugin is fixed upstream.
|
|
37
37
|
*/
|
|
38
38
|
function sentryCommonJSInteropPlugin() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rollup.js","names":["codeTransformer"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23
|
|
1
|
+
{"version":3,"file":"rollup.js","names":["codeTransformer"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23 and Deno add a `'module.exports'` key to every CommonJS\n// namespace (nodejs/node#53848), so ignoring that key restores the check there. Bun adds a key\n// for each own property of `module.exports`, which for a function includes the non-enumerable\n// `length` and `name`. So on Bun, a namespace whose keys all mirror its function default, at least\n// one of them a non-enumerable property, is unwrapped. An ES module namespace can match only when\n// its named exports equal the same properties of its default export, which loses nothing.\nconst BROKEN_NAMESPACE_CHECK = 'Object.keys(n).length === 1';\nconst FIXED_NAMESPACE_CHECK =\n \"(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))\";\n\n/**\n * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the\n * broken namespace check in its helpers module. The patch applies only while the exact broken\n * expression exists, so it retires itself once the plugin is fixed upstream.\n */\nexport function sentryCommonJSInteropPlugin(): Plugin {\n return {\n name: 'sentry-commonjs-interop',\n transform(code: string, id: string) {\n if (id !== COMMONJS_HELPERS_ID || !code.includes(BROKEN_NAMESPACE_CHECK)) {\n return null;\n }\n return { code: code.replace(BROKEN_NAMESPACE_CHECK, FIXED_NAMESPACE_CHECK), map: null };\n },\n };\n}\n\n/**\n * Rollup plugin that runs the orchestrion code transform on the bundled output.\n *\n * Use when bundling a Node app with Rollup. For unbundled Node processes use the\n * runtime hook instead (`node --import @sentry/node/orchestrion app.js`).\n *\n * @example\n * ```ts\n * // rollup.config.js\n * import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';\n * export default { plugins: [sentryOrchestrionPlugin()] };\n * ```\n */\nexport function sentryOrchestrionPlugin(options: PluginOptions = {}): Plugin {\n if (options.buildTimeInstrumentation === false) {\n // Inert plugin — no code transform, so no instrumentation lands in the bundle.\n return { name: 'sentry-orchestrion-disabled' };\n }\n\n const moduleNames = instrumentedModuleNames(options.instrumentations);\n\n // Rolldown omits `external` from the normalized options passed to\n // `buildStart` (function-typed options don't cross its Rust/JS boundary —\n // rolldown/rolldown#1041), so capture the raw value for the probe below.\n let rawExternal: ExternalOption | undefined;\n\n return {\n ...codeTransformer(orchestrionTransformOptions(options)),\n options(inputOptions: InputOptions): null {\n rawExternal = inputOptions.external;\n return null;\n },\n // The module-injected snippet imports `@sentry/server-utils` from INSIDE\n // transformed `node_modules` files. Under isolated installs (pnpm) that bare\n // specifier doesn't resolve from an instrumented package's location, so when\n // normal resolution fails, fall back to this package's own resolution so it\n // gets bundled from its real on-disk path.\n //\n // Forward `options` unchanged: it carries the `custom` metadata `@rollup/plugin-commonjs`\n // uses to recognize a `require()` it is already resolving. Drop it and that plugin warns\n // (THIS_RESOLVE_WITHOUT_OPTIONS), then abandons the resolution.\n async resolveId(\n this: PluginContext,\n source: string,\n importer: string | undefined,\n options: Parameters<ResolveIdHook>[2],\n ) {\n if (source !== SNIPPET_IMPORT_SPECIFIER) {\n return null;\n }\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (resolved) {\n return resolved;\n }\n return resolveOrchestrionRuntimeRequest(source) ?? null;\n },\n buildStart(this: PluginContext, rollupOptions: NormalizedInputOptions): void {\n // An externalized dependency never passes through the code transform, so\n // its diagnostics_channel calls are silently never injected. Rollup has\n // normalized `external` into a single predicate by the time buildStart\n // runs; Rolldown doesn't provide it here at all, so probe the raw value\n // captured in the `options` hook instead.\n const externalizedModules = moduleNames.filter(name =>\n typeof rollupOptions.external === 'function'\n ? rollupOptions.external(name, undefined, false)\n : rawExternal != null && rawExternalMatchesModule(rawExternal, name),\n );\n if (externalizedModules.length > 0) {\n this.warn(externalizedModulesWarning(externalizedModules));\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAS,yBAAyB,UAA0B,MAAuB;CACjF,IAAI,OAAO,aAAa,YAC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