@sentry/server-utils 11.12.0 → 11.14.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/THIRD-PARTY-LICENSES.txt +94 -94
- package/build/cjs/chunks/config.js +3402 -0
- package/build/cjs/chunks/config.js.map +1 -0
- package/build/cjs/{vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-Bd0h-mo3.js → chunks/core-BiWIBBjf.js} +40 -23
- package/build/cjs/chunks/core-BiWIBBjf.js.map +1 -0
- package/build/cjs/chunks/core.js +2 -0
- package/build/cjs/chunks/debug-build.js +15 -0
- package/build/cjs/chunks/debug-build.js.map +1 -0
- package/build/cjs/{vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm → chunks}/esbuild.js +20 -18
- package/build/cjs/chunks/esbuild.js.map +1 -0
- package/build/cjs/chunks/exports.js +7058 -0
- package/build/cjs/chunks/exports.js.map +1 -0
- package/build/cjs/{vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm → chunks}/instrumentation-serde-C-Xxv-jj.js +14 -6
- package/build/cjs/chunks/instrumentation-serde-C-Xxv-jj.js.map +1 -0
- package/build/cjs/chunks/module-details-from-path.js +15969 -0
- package/build/cjs/chunks/module-details-from-path.js.map +1 -0
- package/build/cjs/chunks/moduleInjectedTransform.js +10883 -0
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -0
- package/build/cjs/chunks/options.js +66 -0
- package/build/cjs/chunks/options.js.map +1 -0
- package/build/cjs/chunks/pi-ai.js +80 -0
- package/build/cjs/chunks/pi-ai.js.map +1 -0
- package/build/cjs/chunks/registration-only.js +38 -0
- package/build/cjs/chunks/registration-only.js.map +1 -0
- package/build/cjs/chunks/resolve.js +75 -0
- package/build/cjs/chunks/resolve.js.map +1 -0
- package/build/cjs/chunks/rolldown-runtime.js +48 -0
- package/build/cjs/{vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup-DCG8HLmh.js → chunks/rollup-CzqrjlS4.js} +17 -19
- package/build/cjs/chunks/rollup-CzqrjlS4.js.map +1 -0
- package/build/cjs/index.js +10505 -167
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.no-diagnostic-channels.js +30 -53
- package/build/cjs/index.request-handler.js +240 -7
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/cjs/orchestrion/bundler/bun.js +102 -35
- package/build/cjs/orchestrion/bundler/bun.js.map +1 -1
- package/build/cjs/orchestrion/bundler/esbuild.js +59 -50
- package/build/cjs/orchestrion/bundler/esbuild.js.map +1 -1
- package/build/cjs/orchestrion/bundler/load-hook.js +24 -21
- package/build/cjs/orchestrion/bundler/load-hook.js.map +1 -1
- package/build/cjs/orchestrion/bundler/rollup.js +80 -71
- package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
- package/build/cjs/orchestrion/bundler/vite.js +212 -165
- package/build/cjs/orchestrion/bundler/vite.js.map +1 -1
- package/build/cjs/orchestrion/bundler/webpack-loader.js +134 -16
- package/build/cjs/orchestrion/bundler/webpack-loader.js.map +1 -1
- package/build/cjs/orchestrion/bundler/webpack.js +157 -77
- package/build/cjs/orchestrion/bundler/webpack.js.map +1 -1
- package/build/cjs/orchestrion/config/index.js +12 -129
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/defineProperty.js +17 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/assertClassBrand.js +9 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/checkPrivateRedeclaration.js +8 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateFieldGet2.js +9 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateFieldInitSpec.js +9 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateFieldSet2.js +9 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateMethodInitSpec.js +9 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/defineProperty.js +11 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/toPrimitive.js +13 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/toPropertyKey.js +8 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/typeof.js +10 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/toPrimitive.js +19 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/toPropertyKey.js +15 -0
- package/build/esm/_virtual/_@oxc-project_runtime@0.158.0/helpers/typeof.js +15 -0
- package/build/esm/_virtual/_cjs/require_array_set.js +2 -0
- package/build/esm/_virtual/_cjs/require_astring.js +2 -0
- package/build/esm/_virtual/_cjs/require_base64.js +2 -0
- package/build/esm/_virtual/_cjs/require_base64_vlq.js +2 -0
- package/build/esm/_virtual/_cjs/require_binary_search.js +2 -0
- package/build/esm/_virtual/_cjs/require_esquery_min.js +2 -0
- package/build/esm/_virtual/_cjs/require_mapping_list.js +2 -0
- package/build/esm/_virtual/_cjs/require_meriyah.js +2 -0
- package/build/esm/_virtual/_cjs/require_quick_sort.js +2 -0
- package/build/esm/_virtual/_cjs/require_source_map.js +2 -0
- package/build/esm/_virtual/_cjs/require_source_map_consumer.js +2 -0
- package/build/esm/_virtual/_cjs/require_source_map_generator.js +2 -0
- package/build/esm/_virtual/_cjs/require_source_node.js +2 -0
- package/build/esm/_virtual/_cjs/require_util.js +2 -0
- package/build/esm/_virtual/_rolldown/runtime.js +35 -0
- package/build/esm/ai/anthropic-ai/constants.js +10 -6
- package/build/esm/ai/anthropic-ai/constants.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +183 -199
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +176 -140
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +99 -125
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +72 -52
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/apiPromise.js +35 -47
- package/build/esm/ai/core/apiPromise.js.map +1 -1
- package/build/esm/ai/core/gen-ai-attributes.js +29 -2
- package/build/esm/ai/core/gen-ai-attributes.js.map +1 -1
- package/build/esm/ai/core/streaming-tool-calls.js +37 -0
- package/build/esm/ai/core/streaming-tool-calls.js.map +1 -0
- package/build/esm/ai/core/utils.js +200 -144
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/constants.js +31 -6
- package/build/esm/ai/flue/constants.js.map +1 -1
- package/build/esm/ai/flue/index.js +140 -134
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +93 -179
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/constants.js +16 -8
- 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 +252 -255
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +89 -66
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/google-genai/utils.js +115 -102
- package/build/esm/ai/google-genai/utils.js.map +1 -1
- package/build/esm/ai/index.js +12 -0
- package/build/esm/ai/langchain/constants.js +9 -8
- package/build/esm/ai/langchain/constants.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +83 -67
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +249 -307
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/typesafe-classifier.js +43 -43
- package/build/esm/ai/langchain/typesafe-classifier.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +323 -288
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +73 -79
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/constants.js +3 -2
- package/build/esm/ai/langgraph/constants.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +111 -109
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +84 -110
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +171 -195
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js +25 -18
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/constants.js +63 -18
- package/build/esm/ai/mastra/constants.js.map +1 -1
- package/build/esm/ai/mastra/index.js +164 -190
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/span-registry.js +17 -8
- package/build/esm/ai/mastra/span-registry.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +110 -137
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/constants.js +19 -9
- package/build/esm/ai/mistral/constants.js.map +1 -1
- package/build/esm/ai/mistral/index.js +112 -113
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +180 -187
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/mistral/utils.js +75 -73
- package/build/esm/ai/mistral/utils.js.map +1 -1
- package/build/esm/ai/openai/constants.js +20 -22
- package/build/esm/ai/openai/constants.js.map +1 -1
- package/build/esm/ai/openai/index.js +151 -159
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/mapping.js +76 -53
- package/build/esm/ai/openai/mapping.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +151 -155
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/openai/utils.js +94 -110
- package/build/esm/ai/openai/utils.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +74 -0
- package/build/esm/ai/pi-ai/chat.js.map +1 -0
- package/build/esm/ai/pi-ai/constants.js +6 -0
- package/build/esm/ai/pi-ai/constants.js.map +1 -0
- package/build/esm/ai/pi-ai/messages.js +114 -107
- package/build/esm/ai/pi-ai/messages.js.map +1 -1
- package/build/esm/ai/pi-ai/providers.js +21 -18
- package/build/esm/ai/pi-ai/providers.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +28 -0
- package/build/esm/ai/pi-ai/recording.js.map +1 -0
- package/build/esm/ai/pi-ai/usage.js +31 -27
- package/build/esm/ai/pi-ai/usage.js.map +1 -1
- package/build/esm/ai/pi-durable/constants.js +15 -5
- package/build/esm/ai/pi-durable/constants.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +164 -165
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js +134 -136
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +152 -160
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/pi-durable/utils.js +6 -4
- package/build/esm/ai/pi-durable/utils.js.map +1 -1
- package/build/esm/ai/typesafe/constants.js +3 -2
- package/build/esm/ai/typesafe/constants.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +82 -94
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/vercel-ai/index.js +57 -60
- package/build/esm/ai/vercel-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/constants.js +15 -2
- package/build/esm/ai/workers-ai/constants.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +83 -78
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +133 -141
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/ai/workers-ai/utils.js +131 -143
- package/build/esm/ai/workers-ai/utils.js.map +1 -1
- package/build/esm/async-context.js +74 -63
- package/build/esm/async-context.js.map +1 -1
- package/build/esm/debug-build.js +9 -3
- package/build/esm/debug-build.js.map +1 -1
- package/build/esm/eve.js +61 -22
- package/build/esm/eve.js.map +1 -1
- package/build/esm/exports.js +21 -0
- package/build/esm/index.js +83 -76
- package/build/esm/index.js.map +1 -1
- package/build/esm/index.no-diagnostic-channels.js +21 -20
- package/build/esm/index.request-handler.js +1 -2
- package/build/esm/integrations/amqplib.js +338 -349
- package/build/esm/integrations/amqplib.js.map +1 -1
- package/build/esm/integrations/anthropic.js +154 -120
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/constants.js +11 -2
- package/build/esm/integrations/aws-sdk/constants.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +118 -134
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/MessageAttributes.js +30 -31
- package/build/esm/integrations/aws-sdk/services/MessageAttributes.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +38 -44
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime-content.js +144 -0
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime-content.js.map +1 -0
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +316 -454
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/dynamodb.js +67 -125
- package/build/esm/integrations/aws-sdk/services/dynamodb.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/index.js +1 -0
- package/build/esm/integrations/aws-sdk/services/kinesis.js +12 -16
- package/build/esm/integrations/aws-sdk/services/kinesis.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/lambda.js +51 -57
- package/build/esm/integrations/aws-sdk/services/lambda.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/s3.js +12 -16
- package/build/esm/integrations/aws-sdk/services/s3.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/secretsmanager.js +16 -22
- package/build/esm/integrations/aws-sdk/services/secretsmanager.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/sns.js +66 -70
- package/build/esm/integrations/aws-sdk/services/sns.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/sqs.js +104 -124
- package/build/esm/integrations/aws-sdk/services/sqs.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/stepfunctions.js +14 -20
- package/build/esm/integrations/aws-sdk/services/stepfunctions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/utils.js +18 -19
- package/build/esm/integrations/aws-sdk/utils.js.map +1 -1
- package/build/esm/integrations/cron.js +33 -35
- package/build/esm/integrations/cron.js.map +1 -1
- package/build/esm/integrations/dataloader.js +101 -93
- package/build/esm/integrations/dataloader.js.map +1 -1
- package/build/esm/integrations/express/error-handled.js +13 -8
- package/build/esm/integrations/express/error-handled.js.map +1 -1
- package/build/esm/integrations/express/error-handler.js +49 -31
- package/build/esm/integrations/express/error-handler.js.map +1 -1
- package/build/esm/integrations/express/index.js +26 -17
- package/build/esm/integrations/express/index.js.map +1 -1
- package/build/esm/integrations/express/instrumentation.js +182 -196
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/express/route.js +70 -45
- package/build/esm/integrations/express/route.js.map +1 -1
- package/build/esm/integrations/express/utils.js +11 -5
- package/build/esm/integrations/express/utils.js.map +1 -1
- package/build/esm/integrations/fastify/errors.js +33 -26
- package/build/esm/integrations/fastify/errors.js.map +1 -1
- package/build/esm/integrations/fastify/index.js +41 -21
- package/build/esm/integrations/fastify/index.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +188 -208
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/fastify/utils.js +21 -15
- package/build/esm/integrations/fastify/utils.js.map +1 -1
- package/build/esm/integrations/firebase/firestore.js +69 -70
- package/build/esm/integrations/firebase/firestore.js.map +1 -1
- package/build/esm/integrations/firebase/functions.js +66 -68
- package/build/esm/integrations/firebase/functions.js.map +1 -1
- package/build/esm/integrations/firebase/index.js +21 -13
- package/build/esm/integrations/firebase/index.js.map +1 -1
- package/build/esm/integrations/firebase/instrumentation.js +86 -47
- package/build/esm/integrations/firebase/instrumentation.js.map +1 -1
- package/build/esm/integrations/flue.js +46 -33
- package/build/esm/integrations/flue.js.map +1 -1
- package/build/esm/integrations/generic-pool.js +30 -27
- package/build/esm/integrations/generic-pool.js.map +1 -1
- package/build/esm/integrations/google-genai.js +93 -87
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/graphql/constants.js +6 -4
- package/build/esm/integrations/graphql/constants.js.map +1 -1
- package/build/esm/integrations/graphql/graphql-dc-subscriber.js +95 -99
- package/build/esm/integrations/graphql/graphql-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/graphql/index.js +38 -47
- package/build/esm/integrations/graphql/index.js.map +1 -1
- package/build/esm/integrations/graphql/resolvers.js +117 -142
- package/build/esm/integrations/graphql/resolvers.js.map +1 -1
- package/build/esm/integrations/graphql/spans.js +110 -93
- package/build/esm/integrations/graphql/spans.js.map +1 -1
- package/build/esm/integrations/graphql/utils.js +84 -79
- package/build/esm/integrations/graphql/utils.js.map +1 -1
- package/build/esm/integrations/groq.js +22 -16
- package/build/esm/integrations/groq.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-error-handler.js +47 -38
- package/build/esm/integrations/hapi/hapi-error-handler.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-types.js +20 -13
- package/build/esm/integrations/hapi/hapi-types.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-utils.js +165 -166
- package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +53 -64
- package/build/esm/integrations/hapi/index.js.map +1 -1
- package/build/esm/integrations/hono/applyPatches.js +43 -26
- package/build/esm/integrations/hono/applyPatches.js.map +1 -1
- package/build/esm/integrations/hono/connInfo.js +39 -30
- package/build/esm/integrations/hono/connInfo.js.map +1 -1
- package/build/esm/integrations/hono/constants.js +3 -2
- package/build/esm/integrations/hono/constants.js.map +1 -1
- package/build/esm/integrations/hono/createHonoMiddleware.js +59 -36
- package/build/esm/integrations/hono/createHonoMiddleware.js.map +1 -1
- package/build/esm/integrations/hono/defaultShouldHandleError.js +17 -9
- package/build/esm/integrations/hono/defaultShouldHandleError.js.map +1 -1
- package/build/esm/integrations/hono/hono-context.js +13 -9
- package/build/esm/integrations/hono/hono-context.js.map +1 -1
- package/build/esm/integrations/hono/honoIntegration.js +114 -78
- package/build/esm/integrations/hono/honoIntegration.js.map +1 -1
- package/build/esm/integrations/hono/index.js +3 -0
- package/build/esm/integrations/hono/isMiddleware.js +26 -13
- package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
- package/build/esm/integrations/hono/matchResult.js +59 -64
- package/build/esm/integrations/hono/matchResult.js.map +1 -1
- package/build/esm/integrations/hono/middlewareHandlers.js +88 -82
- package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
- package/build/esm/integrations/hono/patchAppRequest.js +77 -62
- package/build/esm/integrations/hono/patchAppRequest.js.map +1 -1
- package/build/esm/integrations/hono/patchAppUse.js +71 -56
- package/build/esm/integrations/hono/patchAppUse.js.map +1 -1
- package/build/esm/integrations/hono/patchRoute.js +73 -59
- package/build/esm/integrations/hono/patchRoute.js.map +1 -1
- package/build/esm/integrations/hono/resolveRouteName.js +19 -22
- package/build/esm/integrations/hono/resolveRouteName.js.map +1 -1
- package/build/esm/integrations/hono/sentryOriginalTraps.js +23 -16
- package/build/esm/integrations/hono/sentryOriginalTraps.js.map +1 -1
- package/build/esm/integrations/hono/wrapMiddlewareSpan.js +45 -42
- package/build/esm/integrations/hono/wrapMiddlewareSpan.js.map +1 -1
- package/build/esm/integrations/index.js +92 -85
- package/build/esm/integrations/index.js.map +1 -1
- package/build/esm/integrations/kafkajs/consumer.js +58 -60
- package/build/esm/integrations/kafkajs/consumer.js.map +1 -1
- package/build/esm/integrations/kafkajs/index.js +53 -57
- package/build/esm/integrations/kafkajs/index.js.map +1 -1
- package/build/esm/integrations/kafkajs/semconv.js +4 -2
- package/build/esm/integrations/kafkajs/semconv.js.map +1 -1
- package/build/esm/integrations/kafkajs/spans.js +107 -101
- package/build/esm/integrations/kafkajs/spans.js.map +1 -1
- package/build/esm/integrations/knex.js +133 -157
- package/build/esm/integrations/knex.js.map +1 -1
- package/build/esm/integrations/koa/index.js +122 -133
- package/build/esm/integrations/koa/index.js.map +1 -1
- package/build/esm/integrations/koa/koa-error-handler.js +43 -25
- package/build/esm/integrations/koa/koa-error-handler.js.map +1 -1
- package/build/esm/integrations/langchain.js +66 -75
- package/build/esm/integrations/langchain.js.map +1 -1
- package/build/esm/integrations/langgraph.js +55 -61
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/lru-memoizer.js +22 -20
- package/build/esm/integrations/lru-memoizer.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +47 -50
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mastra.js +208 -209
- package/build/esm/integrations/mastra.js.map +1 -1
- package/build/esm/integrations/mcp-server.js +28 -28
- package/build/esm/integrations/mcp-server.js.map +1 -1
- package/build/esm/integrations/mistral.js +74 -56
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/mongodb/index.js +101 -76
- package/build/esm/integrations/mongodb/index.js.map +1 -1
- package/build/esm/integrations/mongodb/mongodb-span.js +110 -106
- package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
- package/build/esm/integrations/mongoose/index.js +82 -89
- package/build/esm/integrations/mongoose/index.js.map +1 -1
- package/build/esm/integrations/mongoose/mongoose-dc-subscriber.js +85 -72
- package/build/esm/integrations/mongoose/mongoose-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/mongoose/mongoose-legacy-span.js +39 -36
- package/build/esm/integrations/mongoose/mongoose-legacy-span.js.map +1 -1
- package/build/esm/integrations/mysql.js +74 -83
- package/build/esm/integrations/mysql.js.map +1 -1
- package/build/esm/integrations/mysql2/index.js +86 -61
- package/build/esm/integrations/mysql2/index.js.map +1 -1
- package/build/esm/integrations/mysql2/mysql2-dc-subscriber.js +51 -38
- package/build/esm/integrations/mysql2/mysql2-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/neon.js +84 -86
- package/build/esm/integrations/neon.js.map +1 -1
- package/build/esm/integrations/nitro/captureStorageEvents.js +97 -111
- package/build/esm/integrations/nitro/captureStorageEvents.js.map +1 -1
- package/build/esm/integrations/nitro/captureTracingEvents.js +139 -181
- package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
- package/build/esm/integrations/nitro/index.js +26 -20
- package/build/esm/integrations/nitro/index.js.map +1 -1
- package/build/esm/integrations/nitro/setServerTimingHeaders.js +31 -33
- package/build/esm/integrations/nitro/setServerTimingHeaders.js.map +1 -1
- package/build/esm/integrations/node-cron.js +54 -48
- package/build/esm/integrations/node-cron.js.map +1 -1
- package/build/esm/integrations/node-schedule.js +45 -51
- package/build/esm/integrations/node-schedule.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +84 -79
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +85 -75
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pg.js +147 -130
- package/build/esm/integrations/pg.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +69 -0
- package/build/esm/integrations/pi-ai.js.map +1 -0
- package/build/esm/integrations/pi-durable.js +46 -42
- package/build/esm/integrations/pi-durable.js.map +1 -1
- package/build/esm/integrations/postgresjs/index.js +124 -126
- package/build/esm/integrations/postgresjs/index.js.map +1 -1
- package/build/esm/integrations/postgresjs/postgresjs-dc-subscriber.js +72 -64
- package/build/esm/integrations/postgresjs/postgresjs-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/postgresjs-wrapper.js +232 -187
- package/build/esm/integrations/postgresjs-wrapper.js.map +1 -1
- package/build/esm/integrations/prisma/global.js +6 -5
- package/build/esm/integrations/prisma/global.js.map +1 -1
- package/build/esm/integrations/prisma/index.js +44 -26
- package/build/esm/integrations/prisma/index.js.map +1 -1
- package/build/esm/integrations/prisma/orchestrion.js +96 -115
- package/build/esm/integrations/prisma/orchestrion.js.map +1 -1
- package/build/esm/integrations/prisma/tracing-helper.js +192 -208
- package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
- package/build/esm/integrations/redis/index.js +173 -190
- package/build/esm/integrations/redis/index.js.map +1 -1
- package/build/esm/integrations/redis/ioredis-channel-subscriber.js +78 -72
- package/build/esm/integrations/redis/ioredis-channel-subscriber.js.map +1 -1
- package/build/esm/integrations/redis/redis-cache.js +110 -111
- package/build/esm/integrations/redis/redis-cache.js.map +1 -1
- package/build/esm/integrations/redis/redis-dc-subscriber.js +79 -84
- package/build/esm/integrations/redis/redis-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/redis/redis-span-name.js +31 -21
- package/build/esm/integrations/redis/redis-span-name.js.map +1 -1
- package/build/esm/integrations/redis/redis-statement-serializer.js +38 -27
- package/build/esm/integrations/redis/redis-statement-serializer.js.map +1 -1
- package/build/esm/integrations/serveTunnel.js +30 -24
- package/build/esm/integrations/serveTunnel.js.map +1 -1
- package/build/esm/integrations/tedious.js +132 -132
- package/build/esm/integrations/tedious.js.map +1 -1
- package/build/esm/integrations/together-ai.js +22 -16
- package/build/esm/integrations/together-ai.js.map +1 -1
- package/build/esm/integrations/typesafe.js +32 -37
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/gen-ai-recording-mode.js +20 -4
- package/build/esm/integrations/vercel-ai/gen-ai-recording-mode.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js +29 -26
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +86 -92
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +515 -514
- 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 +386 -361
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-tool-telemetry.js +61 -34
- package/build/esm/integrations/vercel-ai/vercel-ai-tool-telemetry.js.map +1 -1
- package/build/esm/opentelemetry.js +70 -35
- package/build/esm/opentelemetry.js.map +1 -1
- package/build/esm/orchestrion/bundler/bun.js +42 -32
- package/build/esm/orchestrion/bundler/bun.js.map +1 -1
- package/build/esm/orchestrion/bundler/esbuild.js +57 -47
- package/build/esm/orchestrion/bundler/esbuild.js.map +1 -1
- package/build/esm/orchestrion/bundler/externalRequire.js +65 -62
- package/build/esm/orchestrion/bundler/externalRequire.js.map +1 -1
- package/build/esm/orchestrion/bundler/load-hook.js +23 -19
- package/build/esm/orchestrion/bundler/load-hook.js.map +1 -1
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +119 -44
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
- package/build/esm/orchestrion/bundler/options.js +42 -13
- package/build/esm/orchestrion/bundler/options.js.map +1 -1
- package/build/esm/orchestrion/bundler/resolve.js +43 -13
- package/build/esm/orchestrion/bundler/resolve.js.map +1 -1
- package/build/esm/orchestrion/bundler/rollup.js +79 -68
- package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
- package/build/esm/orchestrion/bundler/vite.js +122 -160
- package/build/esm/orchestrion/bundler/vite.js.map +1 -1
- package/build/esm/orchestrion/bundler/webpack-loader.js +18 -14
- package/build/esm/orchestrion/bundler/webpack-loader.js.map +1 -1
- package/build/esm/orchestrion/bundler/webpack.js +57 -71
- package/build/esm/orchestrion/bundler/webpack.js.map +1 -1
- package/build/esm/orchestrion/channels.js +105 -87
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/amqplib.js +152 -83
- package/build/esm/orchestrion/config/amqplib.js.map +1 -1
- package/build/esm/orchestrion/config/anthropic-ai.js +96 -43
- package/build/esm/orchestrion/config/anthropic-ai.js.map +1 -1
- package/build/esm/orchestrion/config/aws-sdk.js +46 -22
- package/build/esm/orchestrion/config/aws-sdk.js.map +1 -1
- package/build/esm/orchestrion/config/channel-integration-definitions.js +193 -51
- package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
- package/build/esm/orchestrion/config/cron.js +27 -18
- package/build/esm/orchestrion/config/cron.js.map +1 -1
- package/build/esm/orchestrion/config/dataloader.js +62 -45
- package/build/esm/orchestrion/config/dataloader.js.map +1 -1
- package/build/esm/orchestrion/config/express.js +80 -71
- package/build/esm/orchestrion/config/express.js.map +1 -1
- package/build/esm/orchestrion/config/firebase.js +133 -70
- package/build/esm/orchestrion/config/firebase.js.map +1 -1
- package/build/esm/orchestrion/config/flue.js +15 -7
- package/build/esm/orchestrion/config/flue.js.map +1 -1
- package/build/esm/orchestrion/config/generic-pool.js +29 -19
- package/build/esm/orchestrion/config/generic-pool.js.map +1 -1
- package/build/esm/orchestrion/config/google-genai.js +64 -33
- package/build/esm/orchestrion/config/google-genai.js.map +1 -1
- package/build/esm/orchestrion/config/graphql.js +43 -22
- package/build/esm/orchestrion/config/graphql.js.map +1 -1
- package/build/esm/orchestrion/config/groq.js +9 -9
- package/build/esm/orchestrion/config/groq.js.map +1 -1
- package/build/esm/orchestrion/config/hapi.js +56 -38
- package/build/esm/orchestrion/config/hapi.js.map +1 -1
- package/build/esm/orchestrion/config/hono.js +23 -26
- package/build/esm/orchestrion/config/hono.js.map +1 -1
- package/build/esm/orchestrion/config/index.js +177 -111
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/orchestrion/config/ioredis.js +65 -31
- package/build/esm/orchestrion/config/ioredis.js.map +1 -1
- package/build/esm/orchestrion/config/kafkajs.js +29 -26
- package/build/esm/orchestrion/config/kafkajs.js.map +1 -1
- package/build/esm/orchestrion/config/knex.js +57 -29
- package/build/esm/orchestrion/config/knex.js.map +1 -1
- package/build/esm/orchestrion/config/koa.js +31 -24
- package/build/esm/orchestrion/config/koa.js.map +1 -1
- package/build/esm/orchestrion/config/langchain.js +78 -49
- package/build/esm/orchestrion/config/langchain.js.map +1 -1
- package/build/esm/orchestrion/config/langgraph.js +25 -20
- package/build/esm/orchestrion/config/langgraph.js.map +1 -1
- package/build/esm/orchestrion/config/lru-memoizer.js +17 -15
- package/build/esm/orchestrion/config/lru-memoizer.js.map +1 -1
- package/build/esm/orchestrion/config/mastra.js +44 -44
- package/build/esm/orchestrion/config/mastra.js.map +1 -1
- package/build/esm/orchestrion/config/mcp-server.js +24 -32
- package/build/esm/orchestrion/config/mcp-server.js.map +1 -1
- package/build/esm/orchestrion/config/mistral.js +87 -47
- package/build/esm/orchestrion/config/mistral.js.map +1 -1
- package/build/esm/orchestrion/config/module-names.js +9 -3
- package/build/esm/orchestrion/config/module-names.js.map +1 -1
- package/build/esm/orchestrion/config/mongodb.js +101 -61
- package/build/esm/orchestrion/config/mongodb.js.map +1 -1
- package/build/esm/orchestrion/config/mongoose.js +131 -100
- package/build/esm/orchestrion/config/mongoose.js.map +1 -1
- package/build/esm/orchestrion/config/mysql.js +17 -14
- package/build/esm/orchestrion/config/mysql.js.map +1 -1
- package/build/esm/orchestrion/config/mysql2.js +64 -28
- package/build/esm/orchestrion/config/mysql2.js.map +1 -1
- package/build/esm/orchestrion/config/neon.js +33 -36
- package/build/esm/orchestrion/config/neon.js.map +1 -1
- package/build/esm/orchestrion/config/nestjs.js +151 -120
- package/build/esm/orchestrion/config/nestjs.js.map +1 -1
- package/build/esm/orchestrion/config/nitro.js +25 -7
- package/build/esm/orchestrion/config/nitro.js.map +1 -1
- package/build/esm/orchestrion/config/node-cron.js +74 -43
- package/build/esm/orchestrion/config/node-cron.js.map +1 -1
- package/build/esm/orchestrion/config/node-schedule.js +26 -21
- package/build/esm/orchestrion/config/node-schedule.js.map +1 -1
- package/build/esm/orchestrion/config/openai-compatible.js +42 -15
- package/build/esm/orchestrion/config/openai-compatible.js.map +1 -1
- package/build/esm/orchestrion/config/openai.js +72 -39
- package/build/esm/orchestrion/config/openai.js.map +1 -1
- package/build/esm/orchestrion/config/pg.js +70 -45
- package/build/esm/orchestrion/config/pg.js.map +1 -1
- package/build/esm/orchestrion/config/pi-ai.js +49 -0
- package/build/esm/orchestrion/config/pi-ai.js.map +1 -0
- package/build/esm/orchestrion/config/pi-durable.js +36 -26
- package/build/esm/orchestrion/config/pi-durable.js.map +1 -1
- package/build/esm/orchestrion/config/postgres.js +63 -48
- package/build/esm/orchestrion/config/postgres.js.map +1 -1
- package/build/esm/orchestrion/config/prisma.js +46 -36
- package/build/esm/orchestrion/config/prisma.js.map +1 -1
- package/build/esm/orchestrion/config/redis.js +133 -72
- package/build/esm/orchestrion/config/redis.js.map +1 -1
- package/build/esm/orchestrion/config/registration-only.js +23 -8
- package/build/esm/orchestrion/config/registration-only.js.map +1 -1
- package/build/esm/orchestrion/config/remix-v3.js +68 -47
- package/build/esm/orchestrion/config/remix-v3.js.map +1 -1
- package/build/esm/orchestrion/config/remix.js +77 -45
- package/build/esm/orchestrion/config/remix.js.map +1 -1
- package/build/esm/orchestrion/config/tedious.js +31 -16
- package/build/esm/orchestrion/config/tedious.js.map +1 -1
- package/build/esm/orchestrion/config/together-ai.js +17 -15
- package/build/esm/orchestrion/config/together-ai.js.map +1 -1
- package/build/esm/orchestrion/config/typesafe.js +16 -10
- package/build/esm/orchestrion/config/typesafe.js.map +1 -1
- package/build/esm/orchestrion/config/vercel-ai.js +54 -44
- package/build/esm/orchestrion/config/vercel-ai.js.map +1 -1
- package/build/esm/orchestrion/detect.js +50 -34
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/orchestrion/instrumentation.js +90 -70
- package/build/esm/orchestrion/instrumentation.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/tracing-channel.js +143 -135
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/esm/utils/cronMonitoring.js +237 -132
- package/build/esm/utils/cronMonitoring.js.map +1 -1
- package/build/esm/utils/diagnosticsChannel.js +26 -21
- package/build/esm/utils/diagnosticsChannel.js.map +1 -1
- package/build/esm/utils/moduleInjected.js +35 -13
- package/build/esm/utils/moduleInjected.js.map +1 -1
- package/build/esm/utils/monitorStream.js +52 -58
- package/build/esm/utils/monitorStream.js.map +1 -1
- package/build/esm/utils/runtime.js +10 -8
- package/build/esm/utils/runtime.js.map +1 -1
- package/build/esm/utils/setHttpServerSpanRouteAttribute.js +22 -21
- package/build/esm/utils/setHttpServerSpanRouteAttribute.js.map +1 -1
- package/build/esm/utils/sql.js +260 -225
- package/build/esm/utils/sql.js.map +1 -1
- package/build/esm/utils/tunnelServer.js +27 -23
- package/build/esm/utils/tunnelServer.js.map +1 -1
- package/build/esm/utils/withCleanScopes.js +17 -12
- package/build/esm/utils/withCleanScopes.js.map +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +180 -208
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer/index.js +9 -5
- package/build/esm/vendored/@apm-js-collab/code-transformer/index.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/index.js +21 -9
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/index.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/matcher.js +80 -83
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/matcher.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transformer.js +289 -313
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transformer.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transforms.js +488 -284
- package/build/esm/vendored/@apm-js-collab/code-transformer/lib/transforms.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/bun.js +5 -6
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/bun.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/{core-Bd0h-mo3.js → core-BiWIBBjf.js} +15 -14
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-BiWIBBjf.js.map +1 -0
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core.js +3 -0
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/esbuild.js +6 -7
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/esbuild.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/instrumentation-serde-C-Xxv-jj.js +3 -3
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/instrumentation-serde-C-Xxv-jj.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/{rollup-DCG8HLmh.js → rollup-CzqrjlS4.js} +8 -13
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup-CzqrjlS4.js.map +1 -0
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup.js +1 -0
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/vite.js +4 -5
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/vite.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js +13 -12
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js.map +1 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack.js +7 -8
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack.js.map +1 -1
- package/build/esm/vendored/astring/dist/astring.js +910 -1065
- package/build/esm/vendored/astring/dist/astring.js.map +1 -1
- package/build/esm/vendored/esquery/dist/esquery.min.js +1312 -0
- package/build/esm/vendored/esquery/dist/esquery.min.js.map +1 -0
- package/build/esm/vendored/meriyah/dist/meriyah.js +10539 -9189
- package/build/esm/vendored/meriyah/dist/meriyah.js.map +1 -1
- package/build/esm/vendored/meriyah/dist/meriyah2.js +10122 -8806
- package/build/esm/vendored/meriyah/dist/meriyah2.js.map +1 -1
- package/build/esm/vendored/module-details-from-path/index.js +31 -40
- package/build/esm/vendored/module-details-from-path/index.js.map +1 -1
- package/build/esm/vendored/semifies/index.js +106 -108
- package/build/esm/vendored/semifies/index.js.map +1 -1
- package/build/esm/vendored/source-map/lib/array-set.js +100 -70
- package/build/esm/vendored/source-map/lib/array-set.js.map +1 -1
- package/build/esm/vendored/source-map/lib/base64-vlq.js +71 -54
- package/build/esm/vendored/source-map/lib/base64-vlq.js.map +1 -1
- package/build/esm/vendored/source-map/lib/base64.js +38 -39
- package/build/esm/vendored/source-map/lib/base64.js.map +1 -1
- package/build/esm/vendored/source-map/lib/binary-search.js +61 -50
- package/build/esm/vendored/source-map/lib/binary-search.js.map +1 -1
- package/build/esm/vendored/source-map/lib/mapping-list.js +75 -39
- package/build/esm/vendored/source-map/lib/mapping-list.js.map +1 -1
- package/build/esm/vendored/source-map/lib/quick-sort.js +73 -33
- package/build/esm/vendored/source-map/lib/quick-sort.js.map +1 -1
- package/build/esm/vendored/source-map/lib/source-map-consumer.js +763 -609
- package/build/esm/vendored/source-map/lib/source-map-consumer.js.map +1 -1
- package/build/esm/vendored/source-map/lib/source-map-generator.js +281 -282
- package/build/esm/vendored/source-map/lib/source-map-generator.js.map +1 -1
- package/build/esm/vendored/source-map/lib/source-node.js +294 -267
- package/build/esm/vendored/source-map/lib/source-node.js.map +1 -1
- package/build/esm/vendored/source-map/lib/util.js +241 -252
- package/build/esm/vendored/source-map/lib/util.js.map +1 -1
- package/build/esm/vendored/source-map/source-map.js +17 -13
- package/build/esm/vendored/source-map/source-map.js.map +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +2 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +7 -2
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/streaming-tool-calls.d.ts +19 -0
- package/build/types/ai/core/streaming-tool-calls.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +18 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/constants.d.ts +5 -7
- package/build/types/ai/flue/constants.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +7 -4
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +1 -38
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +1 -13
- 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 +7 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +1 -1
- package/build/types/ai/mistral/streaming.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.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +20 -0
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -0
- package/build/types/ai/pi-ai/constants.d.ts +3 -0
- package/build/types/ai/pi-ai/constants.d.ts.map +1 -0
- package/build/types/ai/pi-ai/providers.d.ts +9 -6
- package/build/types/ai/pi-ai/providers.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +15 -0
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -0
- package/build/types/ai/pi-ai/types.d.ts +31 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -0
- package/build/types/ai/pi-durable/index.d.ts +5 -5
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +3 -43
- package/build/types/ai/pi-durable/types.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 +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +13 -0
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
- package/build/types/eve.d.ts +13 -0
- package/build/types/eve.d.ts.map +1 -1
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -1
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +2 -0
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime-content.d.ts +30 -0
- package/build/types/integrations/aws-sdk/services/bedrock-runtime-content.d.ts.map +1 -0
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +5 -0
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/cron.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +3 -3
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/index.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/nitro/captureStorageEvents.d.ts.map +1 -1
- package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
- package/build/types/integrations/nitro/setServerTimingHeaders.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.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +19 -0
- package/build/types/integrations/pi-ai.d.ts.map +1 -0
- package/build/types/integrations/pi-durable.d.ts +3 -4
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/gen-ai-recording-mode.d.ts +5 -1
- package/build/types/integrations/vercel-ai/gen-ai-recording-mode.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +6 -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/vercel-ai/vercel-ai-tool-telemetry.d.ts +3 -3
- package/build/types/integrations/vercel-ai/vercel-ai-tool-telemetry.d.ts.map +1 -1
- package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts +5 -1
- package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
- package/build/types/orchestrion/bundler/options.d.ts +6 -0
- package/build/types/orchestrion/bundler/options.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 +5 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/anthropic-ai.d.ts +1 -0
- package/build/types/orchestrion/config/anthropic-ai.d.ts.map +1 -1
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
- package/build/types/orchestrion/config/flue.d.ts +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/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/orchestrion/config/pi-ai.d.ts +8 -0
- package/build/types/orchestrion/config/pi-ai.d.ts.map +1 -0
- package/build/types/orchestrion/config/vercel-ai.d.ts +1 -0
- package/build/types/orchestrion/config/vercel-ai.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/build/types/utils/wrapServerRequestHandler.d.ts +5 -0
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +9 -12
- package/build/cjs/_virtual/_commonjsHelpers.js +0 -8
- package/build/cjs/_virtual/_commonjsHelpers.js.map +0 -1
- package/build/cjs/_virtual/array-set.js +0 -6
- package/build/cjs/_virtual/array-set.js.map +0 -1
- package/build/cjs/_virtual/astring.js +0 -6
- package/build/cjs/_virtual/astring.js.map +0 -1
- package/build/cjs/_virtual/base64-vlq.js +0 -6
- package/build/cjs/_virtual/base64-vlq.js.map +0 -1
- package/build/cjs/_virtual/base64.js +0 -6
- package/build/cjs/_virtual/base64.js.map +0 -1
- package/build/cjs/_virtual/binary-search.js +0 -6
- package/build/cjs/_virtual/binary-search.js.map +0 -1
- package/build/cjs/_virtual/mapping-list.js +0 -6
- package/build/cjs/_virtual/mapping-list.js.map +0 -1
- package/build/cjs/_virtual/meriyah.js +0 -6
- package/build/cjs/_virtual/meriyah.js.map +0 -1
- package/build/cjs/_virtual/quick-sort.js +0 -6
- package/build/cjs/_virtual/quick-sort.js.map +0 -1
- package/build/cjs/_virtual/source-map-consumer.js +0 -6
- package/build/cjs/_virtual/source-map-consumer.js.map +0 -1
- package/build/cjs/_virtual/source-map-generator.js +0 -6
- package/build/cjs/_virtual/source-map-generator.js.map +0 -1
- package/build/cjs/_virtual/source-map.js +0 -6
- package/build/cjs/_virtual/source-map.js.map +0 -1
- package/build/cjs/_virtual/source-node.js +0 -6
- package/build/cjs/_virtual/source-node.js.map +0 -1
- package/build/cjs/_virtual/util.js +0 -6
- package/build/cjs/_virtual/util.js.map +0 -1
- package/build/cjs/ai/anthropic-ai/constants.js +0 -15
- package/build/cjs/ai/anthropic-ai/constants.js.map +0 -1
- package/build/cjs/ai/anthropic-ai/index.js +0 -225
- package/build/cjs/ai/anthropic-ai/index.js.map +0 -1
- package/build/cjs/ai/anthropic-ai/streaming.js +0 -161
- package/build/cjs/ai/anthropic-ai/streaming.js.map +0 -1
- package/build/cjs/ai/anthropic-ai/tool-runner.js +0 -148
- package/build/cjs/ai/anthropic-ai/tool-runner.js.map +0 -1
- package/build/cjs/ai/anthropic-ai/utils.js +0 -69
- package/build/cjs/ai/anthropic-ai/utils.js.map +0 -1
- package/build/cjs/ai/core/apiPromise.js +0 -54
- package/build/cjs/ai/core/apiPromise.js.map +0 -1
- package/build/cjs/ai/core/gen-ai-attributes.js +0 -14
- package/build/cjs/ai/core/gen-ai-attributes.js.map +0 -1
- package/build/cjs/ai/core/utils.js +0 -182
- package/build/cjs/ai/core/utils.js.map +0 -1
- package/build/cjs/ai/flue/constants.js +0 -20
- package/build/cjs/ai/flue/constants.js.map +0 -1
- package/build/cjs/ai/flue/index.js +0 -141
- package/build/cjs/ai/flue/index.js.map +0 -1
- package/build/cjs/ai/flue/utils.js +0 -200
- package/build/cjs/ai/flue/utils.js.map +0 -1
- package/build/cjs/ai/google-genai/constants.js +0 -17
- package/build/cjs/ai/google-genai/constants.js.map +0 -1
- package/build/cjs/ai/google-genai/index.js +0 -280
- package/build/cjs/ai/google-genai/index.js.map +0 -1
- package/build/cjs/ai/google-genai/streaming.js +0 -79
- package/build/cjs/ai/google-genai/streaming.js.map +0 -1
- package/build/cjs/ai/google-genai/utils.js +0 -131
- package/build/cjs/ai/google-genai/utils.js.map +0 -1
- package/build/cjs/ai/langchain/constants.js +0 -19
- package/build/cjs/ai/langchain/constants.js.map +0 -1
- package/build/cjs/ai/langchain/embeddings.js +0 -82
- package/build/cjs/ai/langchain/embeddings.js.map +0 -1
- package/build/cjs/ai/langchain/index.js +0 -312
- package/build/cjs/ai/langchain/index.js.map +0 -1
- package/build/cjs/ai/langchain/typesafe-classifier.js +0 -62
- package/build/cjs/ai/langchain/typesafe-classifier.js.map +0 -1
- package/build/cjs/ai/langchain/utils.js +0 -355
- package/build/cjs/ai/langchain/utils.js.map +0 -1
- package/build/cjs/ai/langgraph/agent-span.js +0 -94
- package/build/cjs/ai/langgraph/agent-span.js.map +0 -1
- package/build/cjs/ai/langgraph/constants.js +0 -8
- package/build/cjs/ai/langgraph/constants.js.map +0 -1
- package/build/cjs/ai/langgraph/index.js +0 -134
- package/build/cjs/ai/langgraph/index.js.map +0 -1
- package/build/cjs/ai/langgraph/stream.js +0 -117
- package/build/cjs/ai/langgraph/stream.js.map +0 -1
- package/build/cjs/ai/langgraph/utils.js +0 -221
- package/build/cjs/ai/langgraph/utils.js.map +0 -1
- package/build/cjs/ai/mastra/classifier-evaluation.js +0 -30
- package/build/cjs/ai/mastra/classifier-evaluation.js.map +0 -1
- package/build/cjs/ai/mastra/constants.js +0 -41
- package/build/cjs/ai/mastra/constants.js.map +0 -1
- package/build/cjs/ai/mastra/index.js +0 -195
- package/build/cjs/ai/mastra/index.js.map +0 -1
- package/build/cjs/ai/mastra/span-registry.js +0 -20
- package/build/cjs/ai/mastra/span-registry.js.map +0 -1
- package/build/cjs/ai/mastra/utils.js +0 -177
- package/build/cjs/ai/mastra/utils.js.map +0 -1
- package/build/cjs/ai/mistral/constants.js +0 -20
- package/build/cjs/ai/mistral/constants.js.map +0 -1
- package/build/cjs/ai/mistral/index.js +0 -130
- package/build/cjs/ai/mistral/index.js.map +0 -1
- package/build/cjs/ai/mistral/streaming.js +0 -208
- package/build/cjs/ai/mistral/streaming.js.map +0 -1
- package/build/cjs/ai/mistral/utils.js +0 -87
- package/build/cjs/ai/mistral/utils.js.map +0 -1
- package/build/cjs/ai/openai/constants.js +0 -35
- package/build/cjs/ai/openai/constants.js.map +0 -1
- package/build/cjs/ai/openai/index.js +0 -176
- package/build/cjs/ai/openai/index.js.map +0 -1
- package/build/cjs/ai/openai/mapping.js +0 -67
- package/build/cjs/ai/openai/mapping.js.map +0 -1
- package/build/cjs/ai/openai/streaming.js +0 -166
- package/build/cjs/ai/openai/streaming.js.map +0 -1
- package/build/cjs/ai/openai/utils.js +0 -128
- package/build/cjs/ai/openai/utils.js.map +0 -1
- package/build/cjs/ai/pi-ai/messages.js +0 -135
- package/build/cjs/ai/pi-ai/messages.js.map +0 -1
- package/build/cjs/ai/pi-ai/providers.js +0 -22
- package/build/cjs/ai/pi-ai/providers.js.map +0 -1
- package/build/cjs/ai/pi-ai/usage.js +0 -34
- package/build/cjs/ai/pi-ai/usage.js.map +0 -1
- package/build/cjs/ai/pi-durable/constants.js +0 -22
- package/build/cjs/ai/pi-durable/constants.js.map +0 -1
- package/build/cjs/ai/pi-durable/index.js +0 -176
- package/build/cjs/ai/pi-durable/index.js.map +0 -1
- package/build/cjs/ai/pi-durable/models.js +0 -140
- package/build/cjs/ai/pi-durable/models.js.map +0 -1
- package/build/cjs/ai/pi-durable/runs.js +0 -159
- package/build/cjs/ai/pi-durable/runs.js.map +0 -1
- package/build/cjs/ai/pi-durable/tools.js +0 -178
- package/build/cjs/ai/pi-durable/tools.js.map +0 -1
- package/build/cjs/ai/pi-durable/utils.js +0 -9
- package/build/cjs/ai/pi-durable/utils.js.map +0 -1
- package/build/cjs/ai/typesafe/constants.js +0 -10
- package/build/cjs/ai/typesafe/constants.js.map +0 -1
- package/build/cjs/ai/typesafe/index.js +0 -112
- package/build/cjs/ai/typesafe/index.js.map +0 -1
- package/build/cjs/ai/vercel-ai/index.js +0 -70
- package/build/cjs/ai/vercel-ai/index.js.map +0 -1
- package/build/cjs/ai/workers-ai/constants.js +0 -10
- package/build/cjs/ai/workers-ai/constants.js.map +0 -1
- package/build/cjs/ai/workers-ai/index.js +0 -85
- package/build/cjs/ai/workers-ai/index.js.map +0 -1
- package/build/cjs/ai/workers-ai/streaming.js +0 -149
- package/build/cjs/ai/workers-ai/streaming.js.map +0 -1
- package/build/cjs/ai/workers-ai/utils.js +0 -166
- package/build/cjs/ai/workers-ai/utils.js.map +0 -1
- package/build/cjs/async-context.js +0 -68
- package/build/cjs/async-context.js.map +0 -1
- package/build/cjs/debug-build.js +0 -6
- package/build/cjs/debug-build.js.map +0 -1
- package/build/cjs/eve.js +0 -30
- package/build/cjs/eve.js.map +0 -1
- package/build/cjs/index.no-diagnostic-channels.js.map +0 -1
- package/build/cjs/integrations/amqplib.js +0 -417
- package/build/cjs/integrations/amqplib.js.map +0 -1
- package/build/cjs/integrations/anthropic.js +0 -145
- package/build/cjs/integrations/anthropic.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/constants.js +0 -16
- package/build/cjs/integrations/aws-sdk/constants.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/index.js +0 -146
- package/build/cjs/integrations/aws-sdk/index.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/MessageAttributes.js +0 -46
- package/build/cjs/integrations/aws-sdk/services/MessageAttributes.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/ServicesExtensions.js +0 -47
- package/build/cjs/integrations/aws-sdk/services/ServicesExtensions.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/bedrock-runtime.js +0 -477
- package/build/cjs/integrations/aws-sdk/services/bedrock-runtime.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/dynamodb.js +0 -130
- package/build/cjs/integrations/aws-sdk/services/dynamodb.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/kinesis.js +0 -19
- package/build/cjs/integrations/aws-sdk/services/kinesis.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/lambda.js +0 -63
- package/build/cjs/integrations/aws-sdk/services/lambda.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/s3.js +0 -19
- package/build/cjs/integrations/aws-sdk/services/s3.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/secretsmanager.js +0 -25
- package/build/cjs/integrations/aws-sdk/services/secretsmanager.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/sns.js +0 -79
- package/build/cjs/integrations/aws-sdk/services/sns.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/sqs.js +0 -135
- package/build/cjs/integrations/aws-sdk/services/sqs.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/services/stepfunctions.js +0 -23
- package/build/cjs/integrations/aws-sdk/services/stepfunctions.js.map +0 -1
- package/build/cjs/integrations/aws-sdk/utils.js +0 -30
- package/build/cjs/integrations/aws-sdk/utils.js.map +0 -1
- package/build/cjs/integrations/cron.js +0 -49
- package/build/cjs/integrations/cron.js.map +0 -1
- package/build/cjs/integrations/dataloader.js +0 -118
- package/build/cjs/integrations/dataloader.js.map +0 -1
- package/build/cjs/integrations/express/error-handled.js +0 -17
- package/build/cjs/integrations/express/error-handled.js.map +0 -1
- package/build/cjs/integrations/express/error-handler.js +0 -43
- package/build/cjs/integrations/express/error-handler.js.map +0 -1
- package/build/cjs/integrations/express/index.js +0 -24
- package/build/cjs/integrations/express/index.js.map +0 -1
- package/build/cjs/integrations/express/instrumentation.js +0 -222
- package/build/cjs/integrations/express/instrumentation.js.map +0 -1
- package/build/cjs/integrations/express/route.js +0 -76
- package/build/cjs/integrations/express/route.js.map +0 -1
- package/build/cjs/integrations/express/utils.js +0 -12
- package/build/cjs/integrations/express/utils.js.map +0 -1
- package/build/cjs/integrations/fastify/errors.js +0 -36
- package/build/cjs/integrations/fastify/errors.js.map +0 -1
- package/build/cjs/integrations/fastify/index.js +0 -28
- package/build/cjs/integrations/fastify/index.js.map +0 -1
- package/build/cjs/integrations/fastify/instrumentation.js +0 -252
- package/build/cjs/integrations/fastify/instrumentation.js.map +0 -1
- package/build/cjs/integrations/fastify/utils.js +0 -26
- package/build/cjs/integrations/fastify/utils.js.map +0 -1
- package/build/cjs/integrations/firebase/firestore.js +0 -93
- package/build/cjs/integrations/firebase/firestore.js.map +0 -1
- package/build/cjs/integrations/firebase/functions.js +0 -79
- package/build/cjs/integrations/firebase/functions.js.map +0 -1
- package/build/cjs/integrations/firebase/index.js +0 -20
- package/build/cjs/integrations/firebase/index.js.map +0 -1
- package/build/cjs/integrations/firebase/instrumentation.js +0 -56
- package/build/cjs/integrations/firebase/instrumentation.js.map +0 -1
- package/build/cjs/integrations/flue.js +0 -40
- package/build/cjs/integrations/flue.js.map +0 -1
- package/build/cjs/integrations/generic-pool.js +0 -36
- package/build/cjs/integrations/generic-pool.js.map +0 -1
- package/build/cjs/integrations/google-genai.js +0 -105
- package/build/cjs/integrations/google-genai.js.map +0 -1
- package/build/cjs/integrations/graphql/constants.js +0 -36
- package/build/cjs/integrations/graphql/constants.js.map +0 -1
- package/build/cjs/integrations/graphql/graphql-dc-subscriber.js +0 -122
- package/build/cjs/integrations/graphql/graphql-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/graphql/index.js +0 -60
- package/build/cjs/integrations/graphql/index.js.map +0 -1
- package/build/cjs/integrations/graphql/resolvers.js +0 -175
- package/build/cjs/integrations/graphql/resolvers.js.map +0 -1
- package/build/cjs/integrations/graphql/spans.js +0 -114
- package/build/cjs/integrations/graphql/spans.js.map +0 -1
- package/build/cjs/integrations/graphql/utils.js +0 -98
- package/build/cjs/integrations/graphql/utils.js.map +0 -1
- package/build/cjs/integrations/groq.js +0 -21
- package/build/cjs/integrations/groq.js.map +0 -1
- package/build/cjs/integrations/hapi/hapi-error-handler.js +0 -46
- package/build/cjs/integrations/hapi/hapi-error-handler.js.map +0 -1
- package/build/cjs/integrations/hapi/hapi-types.js +0 -23
- package/build/cjs/integrations/hapi/hapi-types.js.map +0 -1
- package/build/cjs/integrations/hapi/hapi-utils.js +0 -202
- package/build/cjs/integrations/hapi/hapi-utils.js.map +0 -1
- package/build/cjs/integrations/hapi/index.js +0 -73
- package/build/cjs/integrations/hapi/index.js.map +0 -1
- package/build/cjs/integrations/hono/applyPatches.js +0 -38
- package/build/cjs/integrations/hono/applyPatches.js.map +0 -1
- package/build/cjs/integrations/hono/connInfo.js +0 -37
- package/build/cjs/integrations/hono/connInfo.js.map +0 -1
- package/build/cjs/integrations/hono/constants.js +0 -8
- package/build/cjs/integrations/hono/constants.js.map +0 -1
- package/build/cjs/integrations/hono/createHonoMiddleware.js +0 -43
- package/build/cjs/integrations/hono/createHonoMiddleware.js.map +0 -1
- package/build/cjs/integrations/hono/defaultShouldHandleError.js +0 -14
- package/build/cjs/integrations/hono/defaultShouldHandleError.js.map +0 -1
- package/build/cjs/integrations/hono/hono-context.js +0 -14
- package/build/cjs/integrations/hono/hono-context.js.map +0 -1
- package/build/cjs/integrations/hono/honoIntegration.js +0 -98
- package/build/cjs/integrations/hono/honoIntegration.js.map +0 -1
- package/build/cjs/integrations/hono/isMiddleware.js +0 -22
- package/build/cjs/integrations/hono/isMiddleware.js.map +0 -1
- package/build/cjs/integrations/hono/matchResult.js +0 -85
- package/build/cjs/integrations/hono/matchResult.js.map +0 -1
- package/build/cjs/integrations/hono/middlewareHandlers.js +0 -101
- package/build/cjs/integrations/hono/middlewareHandlers.js.map +0 -1
- package/build/cjs/integrations/hono/patchAppRequest.js +0 -78
- package/build/cjs/integrations/hono/patchAppRequest.js.map +0 -1
- package/build/cjs/integrations/hono/patchAppUse.js +0 -70
- package/build/cjs/integrations/hono/patchAppUse.js.map +0 -1
- package/build/cjs/integrations/hono/patchRoute.js +0 -69
- package/build/cjs/integrations/hono/patchRoute.js.map +0 -1
- package/build/cjs/integrations/hono/resolveRouteName.js +0 -29
- package/build/cjs/integrations/hono/resolveRouteName.js.map +0 -1
- package/build/cjs/integrations/hono/sentryOriginalTraps.js +0 -21
- package/build/cjs/integrations/hono/sentryOriginalTraps.js.map +0 -1
- package/build/cjs/integrations/hono/wrapMiddlewareSpan.js +0 -48
- package/build/cjs/integrations/hono/wrapMiddlewareSpan.js.map +0 -1
- package/build/cjs/integrations/index.js +0 -93
- package/build/cjs/integrations/index.js.map +0 -1
- package/build/cjs/integrations/kafkajs/consumer.js +0 -71
- package/build/cjs/integrations/kafkajs/consumer.js.map +0 -1
- package/build/cjs/integrations/kafkajs/index.js +0 -70
- package/build/cjs/integrations/kafkajs/index.js.map +0 -1
- package/build/cjs/integrations/kafkajs/semconv.js +0 -14
- package/build/cjs/integrations/kafkajs/semconv.js.map +0 -1
- package/build/cjs/integrations/kafkajs/spans.js +0 -127
- package/build/cjs/integrations/kafkajs/spans.js.map +0 -1
- package/build/cjs/integrations/knex.js +0 -187
- package/build/cjs/integrations/knex.js.map +0 -1
- package/build/cjs/integrations/koa/index.js +0 -155
- package/build/cjs/integrations/koa/index.js.map +0 -1
- package/build/cjs/integrations/koa/koa-error-handler.js +0 -33
- package/build/cjs/integrations/koa/koa-error-handler.js.map +0 -1
- package/build/cjs/integrations/langchain.js +0 -92
- package/build/cjs/integrations/langchain.js.map +0 -1
- package/build/cjs/integrations/langgraph.js +0 -73
- package/build/cjs/integrations/langgraph.js.map +0 -1
- package/build/cjs/integrations/lru-memoizer.js +0 -29
- package/build/cjs/integrations/lru-memoizer.js.map +0 -1
- package/build/cjs/integrations/mastra-classifier.js +0 -57
- package/build/cjs/integrations/mastra-classifier.js.map +0 -1
- package/build/cjs/integrations/mastra.js +0 -247
- package/build/cjs/integrations/mastra.js.map +0 -1
- package/build/cjs/integrations/mcp-server.js +0 -37
- package/build/cjs/integrations/mcp-server.js.map +0 -1
- package/build/cjs/integrations/mistral.js +0 -69
- package/build/cjs/integrations/mistral.js.map +0 -1
- package/build/cjs/integrations/mongodb/index.js +0 -94
- package/build/cjs/integrations/mongodb/index.js.map +0 -1
- package/build/cjs/integrations/mongodb/mongodb-span.js +0 -135
- package/build/cjs/integrations/mongodb/mongodb-span.js.map +0 -1
- package/build/cjs/integrations/mongoose/index.js +0 -109
- package/build/cjs/integrations/mongoose/index.js.map +0 -1
- package/build/cjs/integrations/mongoose/mongoose-dc-subscriber.js +0 -101
- package/build/cjs/integrations/mongoose/mongoose-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/mongoose/mongoose-legacy-span.js +0 -41
- package/build/cjs/integrations/mongoose/mongoose-legacy-span.js.map +0 -1
- package/build/cjs/integrations/mysql.js +0 -101
- package/build/cjs/integrations/mysql.js.map +0 -1
- package/build/cjs/integrations/mysql2/index.js +0 -80
- package/build/cjs/integrations/mysql2/index.js.map +0 -1
- package/build/cjs/integrations/mysql2/mysql2-dc-subscriber.js +0 -57
- package/build/cjs/integrations/mysql2/mysql2-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/neon.js +0 -107
- package/build/cjs/integrations/neon.js.map +0 -1
- package/build/cjs/integrations/nitro/captureStorageEvents.js +0 -132
- package/build/cjs/integrations/nitro/captureStorageEvents.js.map +0 -1
- package/build/cjs/integrations/nitro/captureTracingEvents.js +0 -202
- package/build/cjs/integrations/nitro/captureTracingEvents.js.map +0 -1
- package/build/cjs/integrations/nitro/index.js +0 -27
- package/build/cjs/integrations/nitro/index.js.map +0 -1
- package/build/cjs/integrations/nitro/setServerTimingHeaders.js +0 -40
- package/build/cjs/integrations/nitro/setServerTimingHeaders.js.map +0 -1
- package/build/cjs/integrations/node-cron.js +0 -68
- package/build/cjs/integrations/node-cron.js.map +0 -1
- package/build/cjs/integrations/node-schedule.js +0 -76
- package/build/cjs/integrations/node-schedule.js.map +0 -1
- package/build/cjs/integrations/openai-compatible.js +0 -90
- package/build/cjs/integrations/openai-compatible.js.map +0 -1
- package/build/cjs/integrations/openai.js +0 -93
- package/build/cjs/integrations/openai.js.map +0 -1
- package/build/cjs/integrations/pg.js +0 -171
- package/build/cjs/integrations/pg.js.map +0 -1
- package/build/cjs/integrations/pi-durable.js +0 -50
- package/build/cjs/integrations/pi-durable.js.map +0 -1
- package/build/cjs/integrations/postgresjs/index.js +0 -147
- package/build/cjs/integrations/postgresjs/index.js.map +0 -1
- package/build/cjs/integrations/postgresjs/postgresjs-dc-subscriber.js +0 -81
- package/build/cjs/integrations/postgresjs/postgresjs-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/postgresjs-wrapper.js +0 -219
- package/build/cjs/integrations/postgresjs-wrapper.js.map +0 -1
- package/build/cjs/integrations/prisma/global.js +0 -14
- package/build/cjs/integrations/prisma/global.js.map +0 -1
- package/build/cjs/integrations/prisma/index.js +0 -36
- package/build/cjs/integrations/prisma/index.js.map +0 -1
- package/build/cjs/integrations/prisma/orchestrion.js +0 -137
- package/build/cjs/integrations/prisma/orchestrion.js.map +0 -1
- package/build/cjs/integrations/prisma/tracing-helper.js +0 -241
- package/build/cjs/integrations/prisma/tracing-helper.js.map +0 -1
- package/build/cjs/integrations/redis/index.js +0 -223
- package/build/cjs/integrations/redis/index.js.map +0 -1
- package/build/cjs/integrations/redis/ioredis-channel-subscriber.js +0 -87
- package/build/cjs/integrations/redis/ioredis-channel-subscriber.js.map +0 -1
- package/build/cjs/integrations/redis/redis-cache.js +0 -144
- package/build/cjs/integrations/redis/redis-cache.js.map +0 -1
- package/build/cjs/integrations/redis/redis-dc-subscriber.js +0 -107
- package/build/cjs/integrations/redis/redis-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/redis/redis-span-name.js +0 -32
- package/build/cjs/integrations/redis/redis-span-name.js.map +0 -1
- package/build/cjs/integrations/redis/redis-statement-serializer.js +0 -34
- package/build/cjs/integrations/redis/redis-statement-serializer.js.map +0 -1
- package/build/cjs/integrations/serveTunnel.js +0 -33
- package/build/cjs/integrations/serveTunnel.js.map +0 -1
- package/build/cjs/integrations/tedious.js +0 -160
- package/build/cjs/integrations/tedious.js.map +0 -1
- package/build/cjs/integrations/together-ai.js +0 -19
- package/build/cjs/integrations/together-ai.js.map +0 -1
- package/build/cjs/integrations/typesafe.js +0 -45
- package/build/cjs/integrations/typesafe.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/gen-ai-recording-mode.js +0 -13
- package/build/cjs/integrations/vercel-ai/gen-ai-recording-mode.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/index.js +0 -34
- package/build/cjs/integrations/vercel-ai/index.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/util.js +0 -108
- package/build/cjs/integrations/vercel-ai/util.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/vercel-ai-dc-subscriber.js +0 -589
- package/build/cjs/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +0 -409
- package/build/cjs/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +0 -1
- package/build/cjs/integrations/vercel-ai/vercel-ai-tool-telemetry.js +0 -40
- package/build/cjs/integrations/vercel-ai/vercel-ai-tool-telemetry.js.map +0 -1
- package/build/cjs/opentelemetry.js +0 -45
- package/build/cjs/opentelemetry.js.map +0 -1
- package/build/cjs/orchestrion/bundler/externalRequire.js +0 -82
- package/build/cjs/orchestrion/bundler/externalRequire.js.map +0 -1
- package/build/cjs/orchestrion/bundler/moduleInjectedTransform.js +0 -55
- package/build/cjs/orchestrion/bundler/moduleInjectedTransform.js.map +0 -1
- package/build/cjs/orchestrion/bundler/options.js +0 -25
- package/build/cjs/orchestrion/bundler/options.js.map +0 -1
- package/build/cjs/orchestrion/bundler/resolve.js +0 -27
- package/build/cjs/orchestrion/bundler/resolve.js.map +0 -1
- package/build/cjs/orchestrion/channels.js +0 -92
- package/build/cjs/orchestrion/channels.js.map +0 -1
- package/build/cjs/orchestrion/config/amqplib.js +0 -93
- package/build/cjs/orchestrion/config/amqplib.js.map +0 -1
- package/build/cjs/orchestrion/config/anthropic-ai.js +0 -53
- package/build/cjs/orchestrion/config/anthropic-ai.js.map +0 -1
- package/build/cjs/orchestrion/config/aws-sdk.js +0 -32
- package/build/cjs/orchestrion/config/aws-sdk.js.map +0 -1
- package/build/cjs/orchestrion/config/channel-integration-definitions.js +0 -59
- package/build/cjs/orchestrion/config/channel-integration-definitions.js.map +0 -1
- package/build/cjs/orchestrion/config/cron.js +0 -26
- package/build/cjs/orchestrion/config/cron.js.map +0 -1
- package/build/cjs/orchestrion/config/dataloader.js +0 -53
- package/build/cjs/orchestrion/config/dataloader.js.map +0 -1
- package/build/cjs/orchestrion/config/express.js +0 -81
- package/build/cjs/orchestrion/config/express.js.map +0 -1
- package/build/cjs/orchestrion/config/firebase.js +0 -85
- package/build/cjs/orchestrion/config/firebase.js.map +0 -1
- package/build/cjs/orchestrion/config/flue.js +0 -10
- package/build/cjs/orchestrion/config/flue.js.map +0 -1
- package/build/cjs/orchestrion/config/generic-pool.js +0 -25
- package/build/cjs/orchestrion/config/generic-pool.js.map +0 -1
- package/build/cjs/orchestrion/config/google-genai.js +0 -43
- package/build/cjs/orchestrion/config/google-genai.js.map +0 -1
- package/build/cjs/orchestrion/config/graphql.js +0 -32
- package/build/cjs/orchestrion/config/graphql.js.map +0 -1
- package/build/cjs/orchestrion/config/groq.js +0 -19
- package/build/cjs/orchestrion/config/groq.js.map +0 -1
- package/build/cjs/orchestrion/config/hapi.js +0 -48
- package/build/cjs/orchestrion/config/hapi.js.map +0 -1
- package/build/cjs/orchestrion/config/hono.js +0 -34
- package/build/cjs/orchestrion/config/hono.js.map +0 -1
- package/build/cjs/orchestrion/config/index.js.map +0 -1
- package/build/cjs/orchestrion/config/ioredis.js +0 -41
- package/build/cjs/orchestrion/config/ioredis.js.map +0 -1
- package/build/cjs/orchestrion/config/kafkajs.js +0 -34
- package/build/cjs/orchestrion/config/kafkajs.js.map +0 -1
- package/build/cjs/orchestrion/config/knex.js +0 -43
- package/build/cjs/orchestrion/config/knex.js.map +0 -1
- package/build/cjs/orchestrion/config/koa.js +0 -32
- package/build/cjs/orchestrion/config/koa.js.map +0 -1
- package/build/cjs/orchestrion/config/langchain.js +0 -66
- package/build/cjs/orchestrion/config/langchain.js.map +0 -1
- package/build/cjs/orchestrion/config/langgraph.js +0 -32
- package/build/cjs/orchestrion/config/langgraph.js.map +0 -1
- package/build/cjs/orchestrion/config/lru-memoizer.js +0 -21
- package/build/cjs/orchestrion/config/lru-memoizer.js.map +0 -1
- package/build/cjs/orchestrion/config/mastra.js +0 -54
- package/build/cjs/orchestrion/config/mastra.js.map +0 -1
- package/build/cjs/orchestrion/config/mcp-server.js +0 -41
- package/build/cjs/orchestrion/config/mcp-server.js.map +0 -1
- package/build/cjs/orchestrion/config/mistral.js +0 -57
- package/build/cjs/orchestrion/config/mistral.js.map +0 -1
- package/build/cjs/orchestrion/config/module-names.js +0 -8
- package/build/cjs/orchestrion/config/module-names.js.map +0 -1
- package/build/cjs/orchestrion/config/mongodb.js +0 -71
- package/build/cjs/orchestrion/config/mongodb.js.map +0 -1
- package/build/cjs/orchestrion/config/mongoose.js +0 -113
- package/build/cjs/orchestrion/config/mongoose.js.map +0 -1
- package/build/cjs/orchestrion/config/mysql.js +0 -20
- package/build/cjs/orchestrion/config/mysql.js.map +0 -1
- package/build/cjs/orchestrion/config/mysql2.js +0 -38
- package/build/cjs/orchestrion/config/mysql2.js.map +0 -1
- package/build/cjs/orchestrion/config/neon.js +0 -46
- package/build/cjs/orchestrion/config/neon.js.map +0 -1
- package/build/cjs/orchestrion/config/nestjs.js +0 -130
- package/build/cjs/orchestrion/config/nestjs.js.map +0 -1
- package/build/cjs/orchestrion/config/nitro.js +0 -10
- package/build/cjs/orchestrion/config/nitro.js.map +0 -1
- package/build/cjs/orchestrion/config/node-cron.js +0 -53
- package/build/cjs/orchestrion/config/node-cron.js.map +0 -1
- package/build/cjs/orchestrion/config/node-schedule.js +0 -29
- package/build/cjs/orchestrion/config/node-schedule.js.map +0 -1
- package/build/cjs/orchestrion/config/openai-compatible.js +0 -19
- package/build/cjs/orchestrion/config/openai-compatible.js.map +0 -1
- package/build/cjs/orchestrion/config/openai.js +0 -49
- package/build/cjs/orchestrion/config/openai.js.map +0 -1
- package/build/cjs/orchestrion/config/pg.js +0 -55
- package/build/cjs/orchestrion/config/pg.js.map +0 -1
- package/build/cjs/orchestrion/config/pi-durable.js +0 -34
- package/build/cjs/orchestrion/config/pi-durable.js.map +0 -1
- package/build/cjs/orchestrion/config/postgres.js +0 -58
- package/build/cjs/orchestrion/config/postgres.js.map +0 -1
- package/build/cjs/orchestrion/config/prisma.js +0 -53
- package/build/cjs/orchestrion/config/prisma.js.map +0 -1
- package/build/cjs/orchestrion/config/redis.js +0 -82
- package/build/cjs/orchestrion/config/redis.js.map +0 -1
- package/build/cjs/orchestrion/config/registration-only.js +0 -15
- package/build/cjs/orchestrion/config/registration-only.js.map +0 -1
- package/build/cjs/orchestrion/config/remix-v3.js +0 -55
- package/build/cjs/orchestrion/config/remix-v3.js.map +0 -1
- package/build/cjs/orchestrion/config/remix.js +0 -54
- package/build/cjs/orchestrion/config/remix.js.map +0 -1
- package/build/cjs/orchestrion/config/tedious.js +0 -28
- package/build/cjs/orchestrion/config/tedious.js.map +0 -1
- package/build/cjs/orchestrion/config/together-ai.js +0 -23
- package/build/cjs/orchestrion/config/together-ai.js.map +0 -1
- package/build/cjs/orchestrion/config/typesafe.js +0 -18
- package/build/cjs/orchestrion/config/typesafe.js.map +0 -1
- package/build/cjs/orchestrion/config/vercel-ai.js +0 -56
- package/build/cjs/orchestrion/config/vercel-ai.js.map +0 -1
- package/build/cjs/orchestrion/detect.js +0 -42
- package/build/cjs/orchestrion/detect.js.map +0 -1
- package/build/cjs/orchestrion/instrumentation.js +0 -80
- package/build/cjs/orchestrion/instrumentation.js.map +0 -1
- package/build/cjs/tracing-channel.js +0 -152
- package/build/cjs/tracing-channel.js.map +0 -1
- package/build/cjs/utils/cronMonitoring.js +0 -160
- package/build/cjs/utils/cronMonitoring.js.map +0 -1
- package/build/cjs/utils/diagnosticsChannel.js +0 -48
- package/build/cjs/utils/diagnosticsChannel.js.map +0 -1
- package/build/cjs/utils/moduleInjected.js +0 -18
- package/build/cjs/utils/moduleInjected.js.map +0 -1
- package/build/cjs/utils/monitorStream.js +0 -63
- package/build/cjs/utils/monitorStream.js.map +0 -1
- package/build/cjs/utils/runtime.js +0 -19
- package/build/cjs/utils/runtime.js.map +0 -1
- package/build/cjs/utils/setHttpServerSpanRouteAttribute.js +0 -26
- package/build/cjs/utils/setHttpServerSpanRouteAttribute.js.map +0 -1
- package/build/cjs/utils/sql.js +0 -285
- package/build/cjs/utils/sql.js.map +0 -1
- package/build/cjs/utils/tunnelServer.js +0 -29
- package/build/cjs/utils/tunnelServer.js.map +0 -1
- package/build/cjs/utils/withCleanScopes.js +0 -17
- package/build/cjs/utils/withCleanScopes.js.map +0 -1
- package/build/cjs/utils/wrapServerRequestHandler.js +0 -221
- package/build/cjs/utils/wrapServerRequestHandler.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer/index.js +0 -8
- package/build/cjs/vendored/@apm-js-collab/code-transformer/index.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/index.js +0 -12
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/index.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/matcher.js +0 -86
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/matcher.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/transformer.js +0 -316
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/transformer.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/transforms.js +0 -470
- package/build/cjs/vendored/@apm-js-collab/code-transformer/lib/transforms.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/bun.js +0 -65
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/bun.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-Bd0h-mo3.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/esbuild.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/instrumentation-serde-C-Xxv-jj.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup-DCG8HLmh.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/vite.js +0 -14
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/vite.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js +0 -117
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack-loader-factory.js.map +0 -1
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack.js +0 -103
- package/build/cjs/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/webpack.js.map +0 -1
- package/build/cjs/vendored/astring/dist/astring.js +0 -1068
- package/build/cjs/vendored/astring/dist/astring.js.map +0 -1
- package/build/cjs/vendored/esquery/dist/esquery.esm.min.js +0 -847
- package/build/cjs/vendored/esquery/dist/esquery.esm.min.js.map +0 -1
- package/build/cjs/vendored/meriyah/dist/meriyah.js +0 -9192
- package/build/cjs/vendored/meriyah/dist/meriyah.js.map +0 -1
- package/build/cjs/vendored/meriyah/dist/meriyah2.js +0 -9209
- package/build/cjs/vendored/meriyah/dist/meriyah2.js.map +0 -1
- package/build/cjs/vendored/module-details-from-path/index.js +0 -43
- package/build/cjs/vendored/module-details-from-path/index.js.map +0 -1
- package/build/cjs/vendored/semifies/index.js +0 -111
- package/build/cjs/vendored/semifies/index.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/array-set.js +0 -73
- package/build/cjs/vendored/source-map/lib/array-set.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/base64-vlq.js +0 -57
- package/build/cjs/vendored/source-map/lib/base64-vlq.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/base64.js +0 -42
- package/build/cjs/vendored/source-map/lib/base64.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/binary-search.js +0 -55
- package/build/cjs/vendored/source-map/lib/binary-search.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/mapping-list.js +0 -42
- package/build/cjs/vendored/source-map/lib/mapping-list.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/quick-sort.js +0 -36
- package/build/cjs/vendored/source-map/lib/quick-sort.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/source-map-consumer.js +0 -612
- package/build/cjs/vendored/source-map/lib/source-map-consumer.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/source-map-generator.js +0 -285
- package/build/cjs/vendored/source-map/lib/source-map-generator.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/source-node.js +0 -270
- package/build/cjs/vendored/source-map/lib/source-node.js.map +0 -1
- package/build/cjs/vendored/source-map/lib/util.js +0 -300
- package/build/cjs/vendored/source-map/lib/util.js.map +0 -1
- package/build/cjs/vendored/source-map/source-map.js +0 -16
- package/build/cjs/vendored/source-map/source-map.js.map +0 -1
- package/build/esm/_virtual/_commonjsHelpers.js +0 -6
- package/build/esm/_virtual/_commonjsHelpers.js.map +0 -1
- package/build/esm/_virtual/array-set.js +0 -4
- package/build/esm/_virtual/array-set.js.map +0 -1
- package/build/esm/_virtual/astring.js +0 -4
- package/build/esm/_virtual/astring.js.map +0 -1
- package/build/esm/_virtual/base64-vlq.js +0 -4
- package/build/esm/_virtual/base64-vlq.js.map +0 -1
- package/build/esm/_virtual/base64.js +0 -4
- package/build/esm/_virtual/base64.js.map +0 -1
- package/build/esm/_virtual/binary-search.js +0 -4
- package/build/esm/_virtual/binary-search.js.map +0 -1
- package/build/esm/_virtual/mapping-list.js +0 -4
- package/build/esm/_virtual/mapping-list.js.map +0 -1
- package/build/esm/_virtual/meriyah.js +0 -4
- package/build/esm/_virtual/meriyah.js.map +0 -1
- package/build/esm/_virtual/quick-sort.js +0 -4
- package/build/esm/_virtual/quick-sort.js.map +0 -1
- package/build/esm/_virtual/source-map-consumer.js +0 -4
- package/build/esm/_virtual/source-map-consumer.js.map +0 -1
- package/build/esm/_virtual/source-map-generator.js +0 -4
- package/build/esm/_virtual/source-map-generator.js.map +0 -1
- package/build/esm/_virtual/source-map.js +0 -4
- package/build/esm/_virtual/source-map.js.map +0 -1
- package/build/esm/_virtual/source-node.js +0 -4
- package/build/esm/_virtual/source-node.js.map +0 -1
- package/build/esm/_virtual/util.js +0 -4
- package/build/esm/_virtual/util.js.map +0 -1
- package/build/esm/ai/pi-durable/models.js +0 -138
- package/build/esm/ai/pi-durable/models.js.map +0 -1
- package/build/esm/index.no-diagnostic-channels.js.map +0 -1
- package/build/esm/index.request-handler.js.map +0 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/core-Bd0h-mo3.js.map +0 -1
- package/build/esm/vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup-DCG8HLmh.js.map +0 -1
- package/build/esm/vendored/esquery/dist/esquery.esm.min.js +0 -845
- package/build/esm/vendored/esquery/dist/esquery.esm.min.js.map +0 -1
- package/build/types/ai/pi-durable/models.d.ts +0 -10
- package/build/types/ai/pi-durable/models.d.ts.map +0 -1
package/build/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"names":["_attachHapiErrorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BO,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,sBAAA,CAAA,CAAA,CAAyBA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["addNonEnumerableProperty","captureException","withActiveSpan","defaultShouldHandleError","getResponseStatusCode","isObjectLike","HTTP_ROUTE","HTTP_REQUEST_METHOD","HAPI_TYPE","HAPI_PLUGIN_NAME","getClient","hasSpanStreamingEnabled","REQUEST_HANDLER_SPAN_NAME_FALLBACK","ROUTER_SPAN_NAME_FALLBACK","HAPI_EXT_TYPE","SERVER_EXT_TYPE","HANDLER","ROUTER","MIDDLEWARE","startSpan","SENTRY_OP","SENTRY_ORIGIN","getActiveSpan","setHttpServerSpanRouteAttribute","attachHapiErrorHandler","defaultShouldHandleError","addNonEnumerableProperty","getIsolationScope","getDefaultIsolationScope","DEBUG_BUILD","debug","captureException","NOOP","DEBUG_BUILD","debug","captureException","SPAN_STATUS_ERROR","getAsyncContextStrategy","getMainCarrier","isObjectLike","ERROR_TYPE","spanIsIgnored","getRootSpan","withActiveSpan","GLOBAL_OBJ","getClient","isBun","channel","nodeDiagnosticsChannel","setConversationId","defineIntegration","INTEGRATION_NAME","defaultShouldHandleError","isObjectLike","getClient","INTEGRATION_NAME","diagnosticsChannel.subscribe","defaultShouldHandleError","addNonEnumerableProperty","captureException","ORIGIN","isObjectLike","HTTP_ROUTE","getIsolationScope","SENTRY_ORIGIN","SENTRY_OP","HANDLER","HTTP_REQUEST_METHOD","URL_PATH","setHttpServerSpanRouteAttribute","getClient","hasSpanStreamingEnabled","startInactiveSpan","REQUEST_HANDLER_SPAN_NAME_FALLBACK","withActiveSpan","HTTP_RESPONSE_STATUS_CODE","SPAN_STATUS_ERROR","MIDDLEWARE","startSpan","_isInstrumented","diagnosticsChannel.subscribe","INTEGRATION_NAME","defaultShouldHandleError","defineIntegration","INSTRUMENTED","GLOBAL_OBJ","diagnosticsChannel.tracingChannel","DEBUG_BUILD","debug","waitForTracingChannelBinding","isBun","isDeno","getOrchestrionInjectedModules","isCloudflareWorkers","addNonEnumerableProperty","PRISMA_ORIGIN","LRUMap","getSqlQueryAttributes","SENTRY_ORIGIN","DB_QUERY_SUMMARY","DB_SYSTEM","DB_SYSTEM_NAME","SENTRY_OP","toSqlDialect","DB_STATEMENT","DB_QUERY_TEXT","buildSpanName","getSqlSpanName","startInactiveSpan","SENTRY_KIND","getActiveSpan","DEBUG_BUILD","debug","endSpan","startSpanManual","operationSpans","prismaChannels","PRISMA_LAZY_TERMINALS","diagnosticsChannel.tracingChannel","getActiveSpan","startInactiveSpan","SENTRY_ORIGIN","SENTRY_OP","DB","DB_OPERATION_NAME","DB_COLLECTION_NAME","spanIsIgnored","getRootSpan","withActiveSpan","INTEGRATION_NAME","prismaModuleNames","defineIntegration","amqplibChannels","anthropicAiChannels","awsSdkChannels","cronChannels","dataloaderChannels","expressChannels","firebaseChannels","genericPoolChannels","googleGenAiChannels","graphqlChannels","groqChannels","hapiChannels","honoChannels","ioredisChannels","kafkajsChannels","knexChannels","koaChannels","langchainChannels","langgraphChannels","lruMemoizerChannels","mastraChannels","mcpServerChannels","mistralChannels","mongodbChannels","mongooseChannels","mysql2Channels","mysqlChannels","neonChannels","nestjsChannels","nodeCronChannels","nodeScheduleChannels","openaiChannels","pgChannels","piAiChannels","piDurableChannels","postgresJsChannels","prismaChannels","redisChannels","remixChannels","tediousChannels","togetherAiChannels","typesafeChannels","vercelAiChannels","INTEGRATION_NAME","CONSUMER_ORIGIN","NOOP","amqplibModuleNames","subscribeConnect","diagnosticsChannel.tracingChannel","getHeaderAsString","continueTrace","timestampInSeconds","diagnosticsChannel\n .tracingChannel","SPAN_STATUS_ERROR","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_OP","QUEUE_PUBLISH","SENTRY_KIND","MESSAGING_DESTINATION_NAME","MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY","MESSAGING_OPERATION_NAME","MESSAGING_OPERATION_TYPE","MESSAGING_MESSAGE_ID","MESSAGING_MESSAGE_CONVERSATION_ID","SENTRY_ORIGIN","getTraceData","QUEUE_PROCESS","SENTRY_SEGMENT_NAME_SOURCE","MESSAGING_SYSTEM","NETWORK_PROTOCOL_VERSION","NETWORK_PROTOCOL_NAME","SERVER_ADDRESS","SERVER_PORT","URL_FULL","defineIntegration","isObjectLike","INTEGRATION_NAME","INSTRUMENTED_CHANNELS","anthropicAiModuleNames","diagnosticsChannel.tracingChannel","createGenAiSpan","markCancelledIfAborted","getRequestSignal","addResponseAttributes","resolveAIRecordingOptions","wrapStreamResult","diagnosticsChannel\n .tracingChannel","instrumentToolRunner","instrumentSessionToolRunner","shouldSkipAiProviderSpan","extractRequestAttributes","getProviderName","GEN_AI_REQUEST_MODEL","SENTRY_ORIGIN","ANTHROPIC_AI_ORIGIN","getClient","startInactiveSpan","hasSpanStreamingEnabled","getGenAiSpanOp","addPrivateRequestAttributes","getActiveSpan","isAsyncIterable","instrumentMessageStream","instrumentAsyncIterableStream","defineIntegration","isObjectLike","stringify","GEN_AI_SYSTEM_INSTRUCTIONS","GEN_AI_INPUT_MESSAGES","GEN_AI_TOOL_DEFINITIONS","getMessagesAttributes","messagesFromParams","GEN_AI_OUTPUT_MESSAGES","resolveAIRecordingOptions","isInsidePiAiSpan","GEN_AI_PROVIDER_NAME","GEN_AI_OPERATION_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_TOP_P","ATTR_GEN_AI_REQUEST_STOP_SEQUENCES","GEN_AI_CHAT","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_GENERATE_CONTENT","getTokenUsageAttributes","GEN_AI_USAGE_OUTPUT_TOKENS","getErrorStatus","endStreamSpan","GEN_AI_RESPONSE_FINISH_REASONS","DEBUG_BUILD","debug","DB_SYSTEM_NAME","DB_NAMESPACE","DB_OPERATION_NAME","ATTR_AWS_DYNAMODB_TABLE_NAMES","ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY","ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY","ATTR_AWS_DYNAMODB_CONSISTENT_READ","ATTR_AWS_DYNAMODB_PROJECTION","ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES","ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES","ATTR_AWS_DYNAMODB_LIMIT","ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE","ATTR_AWS_DYNAMODB_SCAN_FORWARD","ATTR_AWS_DYNAMODB_INDEX_NAME","ATTR_AWS_DYNAMODB_SELECT","ATTR_AWS_DYNAMODB_SEGMENT","ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS","ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS","ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES","DB","ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY","ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS","ATTR_AWS_DYNAMODB_TABLE_COUNT","ATTR_AWS_DYNAMODB_COUNT","ATTR_AWS_DYNAMODB_SCANNED_COUNT","AWS_KINESIS_STREAM_NAME","ATTR_FAAS_INVOKED_NAME","ATTR_FAAS_INVOKED_PROVIDER","ATTR_FAAS_INVOCATION_ID","ATTR_FAAS_INVOKED_REGION","getTraceData","DEBUG_BUILD","debug","AWS_S3_BUCKET","ATTR_AWS_SECRETSMANAGER_SECRET_ARN","DEBUG_BUILD","debug","uniq","buildSpanName","MESSAGING_SYSTEM","SENTRY_KIND","QUEUE_PUBLISH","ATTR_MESSAGING_DESTINATION_KIND","ATTR_MESSAGING_DESTINATION","MESSAGING_DESTINATION_NAME","MESSAGING_OPERATION_TYPE","getClient","hasSpanStreamingEnabled","ATTR_AWS_SNS_TOPIC_ARN","getTraceData","MESSAGING_SYSTEM","MESSAGING_DESTINATION_NAME","URL_FULL","SENTRY_KIND","QUEUE_RECEIVE","QUEUE_PUBLISH","MESSAGING_OPERATION_TYPE","getClient","hasSpanStreamingEnabled","getTraceData","MESSAGING_MESSAGE_ID","MESSAGING_BATCH_MESSAGE_COUNT","propagationContextFromHeaders","ATTR_AWS_STEP_FUNCTIONS_STATE_MACHINE_ARN","ATTR_AWS_STEP_FUNCTIONS_ACTIVITY_ARN","RPC_SYSTEM","RPC_METHOD","RPC_SERVICE","CLOUD_REGION","INTEGRATION_NAME","AWS_REQUEST_ID","HTTP_RESPONSE_STATUS_CODE","AWS_REQUEST_EXTENDED_ID","awsSdkModuleNames","RPC","startInactiveSpan","SENTRY_KIND","SENTRY_ORIGIN","CLOUD_REGION","diagnosticsChannel.tracingChannel","defineIntegration","INTEGRATION_NAME","ORIGIN","OPERATION_SPAN_OPS","CACHE_GET","CACHE_PUT","CACHE_REMOVE","WRAPPED","getClient","hasSpanStreamingEnabled","SENTRY_OP","CACHE_OPERATION","CACHE_OPERATION_NAMES","SENTRY_KIND","SENTRY_ORIGIN","DB_OPERATION_NAME","DB_COLLECTION_NAME","CACHE_KEY","diagnosticsChannel.tracingChannel","DEBUG_BUILD","debug","waitForTracingChannelBinding","diagnosticsChannel\n .tracingChannel","startSpan","startInactiveSpan","defineIntegration","INTEGRATION_NAME","genericPoolModuleNames","defineIntegration","diagnosticsChannel.tracingChannel","startInactiveSpan","SENTRY_OP","DB","SENTRY_ORIGIN","diagnosticsChannel.tracingChannel","DEBUG_BUILD","debug","stringMatchesSomePattern","captureException","isThenable","startNewTrace","withMonitor","addNonEnumerableProperty","INTEGRATION_NAME","cronModuleNames","subscribe","defineIntegration","INTEGRATION_NAME","nodeCronModuleNames","subscribe","defineIntegration","getMonitorConfig","INTEGRATION_NAME","nodeScheduleModuleNames","subscribe","defineIntegration","INTEGRATION_NAME","ORIGIN","INSTRUMENTED_CHANNELS","googleGenAiModuleNames","diagnosticsChannel.tracingChannel","createGenAiSpan","resolveChatParams","markCancelledIfAborted","getCallAbortSignal","addResponseAttributes","resolveAIRecordingOptions","wrapStreamResult","shouldSkipAiProviderSpan","getActiveSpan","SENTRY_OP","SENTRY_ORIGIN","spanToJSON","extractRequestAttributes","GEN_AI_REQUEST_MODEL","getClient","startInactiveSpan","hasSpanStreamingEnabled","getGenAiSpanOp","addPrivateRequestAttributes","isAsyncIterable","instrumentStream","getAbortSignal","defineIntegration","ORIGIN","getRootSpan","spanToJSON","SENTRY_GRAPHQL_OPERATION","getClient","hasSpanStreamingEnabled","SENTRY_SEGMENT_NAME_SOURCE","isObjectLike","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_ORIGIN","ORIGIN","SENTRY_OP","GRAPHQL","GRAPHQL_PROCESSING_TYPE","GRAPHQL_DOCUMENT","SPAN_STATUS_ERROR","GRAPHQL_OPERATION_TYPE","GRAPHQL_OPERATION_NAME","isObjectLike","withActiveSpan","SPAN_STATUS_ERROR","SENTRY_ORIGIN","ORIGIN","SENTRY_OP","GRAPHQL","GRAPHQL_PROCESSING_TYPE","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_ORIGIN","ORIGIN","SENTRY_OP","GRAPHQL","getClient","startInactiveSpan","hasSpanStreamingEnabled","GRAPHQL_PROCESSING_TYPE","GRAPHQL_DOCUMENT","SPAN_STATUS_ERROR","GRAPHQL_OPERATION_TYPE","GRAPHQL_OPERATION_NAME","INTEGRATION_NAME","graphqlModuleNames","diagnosticsChannel.tracingChannel","waitForTracingChannelBinding","defineIntegration","INTEGRATION_NAME","hapiModuleNames","diagnosticsChannel.tracingChannel","attachHapiErrorHandler","defineIntegration","INTEGRATION_NAME","isBun","isDeno","isCloudflareWorkers","applyPatches","createHonoRequestMiddleware","wrapMiddlewareWithSpan","isMatchedHandlerList","getMiddlewareFlags","wrapRouteHandlers","diagnosticsChannel.tracingChannel","isInternalRequestSpanActive","startInactiveSpan","extractPathname","SENTRY_OP","HTTP_SERVER","SENTRY_ORIGIN","INTERNAL_REQUEST_ORIGIN","honoModuleNames","defineIntegration","INTEGRATION_NAME","ORIGIN","koaModuleNames","diagnosticsChannel.tracingChannel","getActiveSpan","setHttpServerSpanRouteAttribute","HTTP_ROUTE","CODE_FUNCTION_NAME","getClient","hasSpanStreamingEnabled","ROUTER_SPAN_NAME_FALLBACK","startSpan","SENTRY_OP","MIDDLEWARE","ROUTER","SENTRY_ORIGIN","addNonEnumerableProperty","getIsolationScope","getDefaultIsolationScope","DEBUG_BUILD","debug","KOA_TYPE","defineIntegration","DB_SYSTEM_VALUE_REDIS","getClient","hasSpanStreamingEnabled","DB_STORED_PROCEDURE_NAME","CACHE_GET","CACHE_PUT","CACHE_REMOVE","SENTRY_OP","CACHE_KEY","CACHE_OPERATION","CACHE_OPERATION_NAMES","SERVER_ADDRESS","SERVER_PORT","NETWORK_PEER_ADDRESS","NETWORK_PEER_PORT","getClient","hasSpanStreamingEnabled","truncate","spanToJSON","CACHE_ITEM_SIZE","CACHE_HIT","ORIGIN","setupConnectChannel","SENTRY_ORIGIN","SENTRY_OP","DB_QUERY","DB_SYSTEM_NAME","DB_OPERATION_NAME","DB_QUERY_TEXT","SERVER_ADDRESS","SERVER_PORT","startInactiveSpan","DB_OPERATION_BATCH_SIZE","DB","ORIGIN","DB_SYSTEM_VALUE_REDIS","DB_SYSTEM_NAME","SERVER_ADDRESS","SERVER_PORT","SENTRY_ORIGIN","SENTRY_KIND","SENTRY_OP","DB_QUERY","DB_OPERATION_NAME","DB_QUERY_TEXT","startInactiveSpan","diagnosticsChannel.tracingChannel","DB","INTEGRATION_NAME","ORIGIN","SPAN_STATUS_ERROR","isObjectLike","DB_SYSTEM_NAME","SERVER_ADDRESS","SERVER_PORT","SENTRY_ORIGIN","startInactiveSpan","SENTRY_KIND","SENTRY_OP","DB_QUERY","DB_OPERATION_NAME","DB_QUERY_TEXT","diagnosticsChannel.tracingChannel","getActiveSpan","withActiveSpan","DB","DB_OPERATION_BATCH_SIZE","redisModuleNames","ioredisModuleNames","waitForTracingChannelBinding","defineIntegration","propagationContextFromHeaders","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_OP","QUEUE_RECEIVE","QUEUE_PROCESS","SENTRY_KIND","MESSAGING_SYSTEM","MESSAGING_DESTINATION_NAME","MESSAGING_OPERATION_TYPE","MESSAGING_OPERATION_NAME","ATTR_MESSAGING_KAFKA_MESSAGE_KEY","ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE","ATTR_MESSAGING_KAFKA_OFFSET","SENTRY_ORIGIN","QUEUE_PUBLISH","ATTR_MESSAGING_DESTINATION_PARTITION_ID","getTraceData","isObjectLike","ERROR_TYPE","SPAN_STATUS_ERROR","continueTrace","ATTR_MESSAGING_DESTINATION_PARTITION_ID","withActiveSpan","startNewTrace","MESSAGING_BATCH_MESSAGE_COUNT","INTEGRATION_NAME","diagnosticsChannel.tracingChannel","kafkajsModuleNames","defineIntegration","INTEGRATION_NAME","ORIGIN","ATTR_DB_SQL_TABLE","DB_SYSTEM_POSTGRESQL","diagnosticsChannel.tracingChannel","DEBUG_BUILD","debug","waitForTracingChannelBinding","subscribeQuery","getActiveSpan","toSqlDialect","SENTRY_OP","DB","SENTRY_KIND","SENTRY_ORIGIN","getSqlQueryAttributes","truncate","DB_SYSTEM_NAME","DB_OPERATION_NAME","DB_USER","DB_NAMESPACE","SERVER_ADDRESS","SERVER_PORT","NETWORK_TRANSPORT","startInactiveSpan","getSqlSpanName","SPAN_STATUS_ERROR","defineIntegration","diagnosticsChannel.tracingChannel","createGenAiSpan","markCancelledIfAborted","getRequestSignal","addResponseAttributes","resolveAIRecordingOptions","wrapStreamResult","_INTERNAL_shouldSkipAiProviderWrapping","extractRequestAttributes","GEN_AI_PROVIDER_NAME","SENTRY_ORIGIN","getClient","startInactiveSpan","hasSpanStreamingEnabled","getGenAiSpanOp","addRequestAttributes","isAsyncIterable","instrumentStream","defineIntegration","groqModuleNames","INTEGRATION_NAME","LANGCHAIN_INTEGRATION_NAME","OPENAI_INTEGRATION_NAME","ANTHROPIC_AI_INTEGRATION_NAME","GOOGLE_GENAI_INTEGRATION_NAME","MISTRAL_INTEGRATION_NAME","_INTERNAL_skipAiProviderWrapping","langchainModuleNames","createLangChainCallbackHandler","_INTERNAL_mergeLangChainCallbackHandler","getInheritedLangChainCallbacks","getConversationIdMetadataFromConfig","diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel","recordTypeSafeClassifierState","langchainEmbeddingsChannels","startInactiveSpan","_INTERNAL_getLangChainEmbeddingsSpanOptions","defineIntegration","INTEGRATION_NAME","LANGGRAPH_INTEGRATION_NAME","langgraphModuleNames","resolveAIRecordingOptions","createLangChainCallbackHandler","diagnosticsChannel\n .tracingChannel","isInsideManualLangGraphInstrumentation","instrumentCompiledGraph","diagnosticsChannel.tracingChannel","wrapToolsWithSpans","extractAgentNameFromParams","DEBUG_BUILD","debug","extractLLMFromParams","isObjectLike","defineIntegration","FLUE_INTEGRATION_NAME","GLOBAL_OBJ","FLUE_MODULE_NAME","DEBUG_BUILD","debug","createFlueInstrumentation","defineIntegration","GEN_AI_USAGE_INPUT_TOKENS","sum","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_COST_INPUT_TOKENS","GEN_AI_COST_OUTPUT_TOKENS","GEN_AI_COST_TOTAL_TOKENS","GEN_AI_COST_CACHE_READ_INPUT_TOKENS","GEN_AI_COST_CACHE_CREATION_INPUT_TOKENS","getCurrentScope","getIsolationScope","GEN_AI_CHAT","SENTRY_ORIGIN","PI_AI_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_PROVIDER_NAME","GEN_AI_REQUEST_MODEL","GEN_AI_CONVERSATION_ID","GEN_AI_RESPONSE_STREAMING","GEN_AI_REQUEST_TEMPERATURE","GEN_AI_REQUEST_MAX_TOKENS","GEN_AI_REQUEST_REASONING_LEVEL","piAiFinishReason","piAiAssistantMessageToGenAiMessage","GEN_AI_RESPONSE_MODEL","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_FINISH_REASONS","stringify","GEN_AI_OUTPUT_MESSAGES","SPAN_STATUS_ERROR","parseStringToURLObject","isURLObjectRelative","SERVER_ADDRESS","SERVER_PORT","piAiMessagesToGenAiMessages","piAiToolDefinitions","GEN_AI_SYSTEM_INSTRUCTIONS","piAiSystemInstructions","GEN_AI_INPUT_MESSAGES","GEN_AI_TOOL_DEFINITIONS","PI_AI_INTEGRATION_NAME","piAiModuleNames","diagnosticsChannel.tracingChannel","isInsidePiAiSpan","resolvePiAiRecordingOptions","startInactiveSpan","isThenable","defineIntegration","uuid4","DEBUG_BUILD","debug","derefWeakRef","getRootSpan","getDefaultIsolationScope","startInactiveSpan","GEN_AI_INVOKE_AGENT","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_CONVERSATION_ID","withCleanScopes","continueTrace","startNewTrace","SPAN_STATUS_ERROR","isObjectLike","resolveAIRecordingOptions","startSpanManual","GEN_AI_EXECUTE_TOOL","SENTRY_ORIGIN","GEN_AI_OPERATION_NAME","GEN_AI_TOOL_NAME","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ID_ATTRIBUTE","GEN_AI_CONVERSATION_ID","GEN_AI_TOOL_CALL_ARGUMENTS","stringify","timestampInSeconds","SPAN_STATUS_ERROR","captureException","piAiContentToString","GEN_AI_TOOL_CALL_RESULT","makeWeakRef","spanToTraceHeader","spanToBaggageHeader","captureException","addNonEnumerableProperty","SPAN_STATUS_ERROR","GEN_AI_CONVERSATION_ID","setPiAiRecordingOptions","withCleanScopes","getDefaultIsolationScope","startNewTrace","getCurrentScope","withActiveSpan","piDurableModuleNames","diagnosticsChannel.tracingChannel","isObjectLike","DEBUG_BUILD","debug","diagnosticsChannel\n .tracingChannel","defineIntegration","diagnosticsChannel.tracingChannel","setStartingClassifierEvaluation","isObjectLike","processClassifierEvaluationData","GEN_AI_INPUT_MESSAGES","getEvaluationInputMessages","GEN_AI_OUTPUT_MESSAGES","getEvaluationOutputMessages","isObjectLike","MASTRA_INTEGRATION_NAME","mastraModuleNames","diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel","getSentrySpanForMastraId","captureException","withActiveSpan","DEBUG_BUILD","debug","SentryMastraExporter","MASTRA_EXPORTER_BRAND","consoleSandbox","join","createRequire","GLOBAL_OBJ","fileURLToPath","defineIntegration","INTEGRATION_NAME","mcpServerModuleNames","subscribe","diagnosticsChannel.tracingChannel","wrapMcpServerWithSentry","defineIntegration","httpServerHandlesTunnel","handleServedNodeTunnelRequest","DEBUG_BUILD","debug","setNodeTunnelHandler","handleServedNodeTunnelRequest","HTTP_ON_SERVER_REQUEST","defineIntegration","coreServeTunnelIntegration","INTEGRATION_NAME","lruMemoizerModuleNames","diagnosticsChannel.tracingChannel","defineIntegration","isObjectLike","SENTRY_ORIGIN","DB_SYSTEM_NAME","DB_NAMESPACE","DB_COLLECTION_NAME","DB_OPERATION_NAME","DB_CONNECTION_STRING","SERVER_ADDRESS","SERVER_PORT","DB_QUERY_TEXT","getClient","hasSpanStreamingEnabled","startInactiveSpan","SENTRY_OP","DB","SENTRY_KIND","INTEGRATION_NAME","ORIGIN","mongodbModuleNames","diagnosticsChannel.tracingChannel","defineIntegration","ORIGIN","DB_SYSTEM_NAME_VALUE_MONGODB","subscribed","DEBUG_BUILD","debug","getClient","hasSpanStreamingEnabled","startInactiveSpan","SENTRY_ORIGIN","SENTRY_OP","DB","DB_SYSTEM_NAME","DB_OPERATION_NAME","DB_COLLECTION_NAME","DB_NAMESPACE","DB_QUERY_TEXT","DB_OPERATION_BATCH_SIZE","SERVER_ADDRESS","SERVER_PORT","isObjectLike","SENTRY_OP","DB","SENTRY_KIND","DB_COLLECTION_NAME","DB_NAMESPACE","DB_USER","SERVER_ADDRESS","SERVER_PORT","DB_OPERATION_NAME","DB_SYSTEM_NAME","SENTRY_ORIGIN","getClient","hasSpanStreamingEnabled","startInactiveSpan","INTEGRATION_NAME","ORIGIN","diagnosticsChannel.tracingChannel","waitForTracingChannelBinding","mongooseModuleNames","MONGOOSE_CONTEXT_CAPTURE_CHANNELS","getActiveSpan","defineIntegration","INTEGRATION_NAME","MISTRAL_INTEGRATION_NAME","INSTRUMENTED_CHANNELS","mistralModuleNames","diagnosticsChannel.tracingChannel","createGenAiSpan","markCancelledIfAborted","getMistralRequestSignal","addResponseAttributes","resolveAIRecordingOptions","instrumentEventStream","shouldSkipAiProviderSpan","extractRequestAttributes","SENTRY_ORIGIN","MISTRAL_ORIGIN","startInactiveSpan","getSpanName","getGenAiSpanOp","addRequestAttributes","defineIntegration","defineIntegration","togetherAiModuleNames","TYPESAFE_INTEGRATION_NAME","typesafeModuleNames","diagnosticsChannel.tracingChannel","startDecideSpan","resolveAIRecordingOptions","addResponseAttributes","onSystemOneResponse","defineIntegration","INTEGRATION_NAME","DB_SYSTEM_NAME_VALUE_MYSQL","mysqlModuleNames","diagnosticsChannel.tracingChannel","extractSql","getCurrentScope","SENTRY_OP","DB","SENTRY_KIND","DB_SYSTEM_NAME","SENTRY_ORIGIN","DB_CONNECTION_STRING","DB_NAMESPACE","DB_USER","getSqlQueryAttributes","SERVER_ADDRESS","SERVER_PORT","startInactiveSpan","getSqlSpanName","hasOnMethod","bindScopeToEmitter","isObjectLike","defineIntegration","ORIGIN","SENTRY_ORIGIN","SENTRY_OP","DB","DB_SYSTEM_NAME","getSqlQueryAttributes","DB_NAMESPACE","SERVER_ADDRESS","SERVER_PORT","startInactiveSpan","getSqlSpanName","INTEGRATION_NAME","ORIGIN","diagnosticsChannel.tracingChannel","getQueryText","SENTRY_KIND","SENTRY_ORIGIN","SENTRY_OP","DB","DB_SYSTEM_NAME","getSqlQueryAttributes","getConnectionAttributes","startInactiveSpan","getSqlSpanName","extractSql","isObjectLike","DB_NAMESPACE","DB_USER","SERVER_ADDRESS","SERVER_PORT","waitForTracingChannelBinding","mysql2ModuleNames","defineIntegration","INTEGRATION_NAME","ORIGIN","openaiModuleNames","diagnosticsChannel.tracingChannel","markCancelledIfAborted","getRequestSignal","addResponseAttributes","resolveAIRecordingOptions","shouldSkipAiProviderSpan","extractRequestAttributes","SENTRY_ORIGIN","getClient","startInactiveSpan","hasSpanStreamingEnabled","getGenAiSpanOp","addRequestAttributes","instrumentStream","defineIntegration","INTEGRATION_NAME","ORIGIN","DB_SYSTEM_POSTGRESQL","pgModuleNames","diagnosticsChannel.tracingChannel","getCurrentScope","startInactiveSpan","SENTRY_KIND","bindScopeToEmitter","SENTRY_OP","DB","SENTRY_ORIGIN","getSqlQueryAttributes","getSqlSpanName","isObjectLike","DB_SYSTEM_NAME","DB_NAMESPACE","DB_USER","SERVER_ADDRESS","SERVER_PORT","DB_CONNECTION_STRING","defineIntegration","ORIGIN","DB_SYSTEM_NAME_POSTGRES","_isPostgresJsWrapperSpan","getActiveSpan","getSqlQueryAttributes","DB_QUERY_TEXT","SENTRY_OP","DB","SENTRY_KIND","SENTRY_ORIGIN","DB_SYSTEM_NAME","_getConnectionAttributes","startInactiveSpan","getSqlSpanName","DB_OPERATION_NAME","isObjectLike","DB_RESPONSE_STATUS_CODE","DEBUG_BUILD","debug","INTEGRATION_NAME","ORIGIN","NOOP","_buildConnectionContext","_getConnectionAttributes","diagnosticsChannel.tracingChannel","waitForTracingChannelBinding","postgresJsModuleNames","getSqlQueryAttributes","_reconstructQuery","SENTRY_OP","DB","SENTRY_KIND","SENTRY_ORIGIN","DB_SYSTEM_NAME","startInactiveSpan","getSqlSpanName","DB_QUERY_TEXT","DEBUG_BUILD","debug","_wrapQuerySettlement","DB_OPERATION_NAME","defineIntegration","INTEGRATION_NAME","ORIGIN","NOOP","neonModuleNames","diagnosticsChannel.tracingChannel","startInactiveSpan","getActiveSpan","getSqlQueryAttributes","DB_QUERY_TEXT","DB_QUERY_SUMMARY","DB_OPERATION_NAME","SENTRY_OP","DB","SENTRY_ORIGIN","SENTRY_KIND","DB_SYSTEM_NAME","DB_OPERATION_BATCH_SIZE","getLowCardinalitySqlSpanName","defineIntegration","INTEGRATION_NAME","ORIGIN","diagnosticsChannel.tracingChannel","EventEmitter","getSqlQueryAttributes","DB_QUERY_SUMMARY","DB_OPERATION_NAME","SENTRY_OP","DB","SENTRY_KIND","SENTRY_ORIGIN","DB_SYSTEM_NAME","DB_NAMESPACE","DB_USER","SERVER_ADDRESS","SERVER_PORT","getClient","startInactiveSpan","hasSpanStreamingEnabled","DB_QUERY_TEXT","SPAN_STATUS_ERROR","tediousModuleNames","defineIntegration","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_COST_TOTAL_TOKENS","isObjectLike","ORIGIN","GEN_AI_EMBEDDINGS","GEN_AI_RERANK","GEN_AI_DECIDE","GEN_AI_INVOKE_AGENT","GEN_AI_EXECUTE_TOOL","GEN_AI_GENERATE_CONTENT","isObjectLike","getActiveSpan","spanToJSON","GEN_AI_CONVERSATION_ID","GEN_AI_USAGE_OUTPUT_TOKENS","GEN_AI_USAGE_REASONING_OUTPUT_TOKENS","GEN_AI_COST_TOTAL_TOKENS","isReadableStream","GEN_AI_USAGE_INPUT_TOKENS","GEN_AI_USAGE_TOTAL_TOKENS","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","GEN_AI_OUTPUT_MESSAGES","VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE","SENTRY_ORIGIN","GEN_AI_PROVIDER_NAME","GEN_AI_REQUEST_MODEL","_INTERNAL_skipAiProviderWrapping","WORKERS_AI_INTEGRATION_NAME","GEN_AI_EMBEDDINGS_INPUT","stringify","GEN_AI_INPUT_MESSAGES","startInactiveSpan","SENTRY_OP","GEN_AI_OPERATION_NAME","GEN_AI_RESPONSE_STREAMING","GEN_AI_FUNCTION_ID","GEN_AI_TOOL_DEFINITIONS","VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE","GEN_AI_TOOL_NAME","GEN_AI_TOOL_CALL_ID_ATTRIBUTE","GEN_AI_TOOL_DESCRIPTION","GEN_AI_TOOL_CALL_ARGUMENTS","GEN_AI_TOOL_CALL_RESULT","GEN_AI_RESPONSE_FINISH_REASONS","GEN_AI_RESPONSE_ID","GEN_AI_RESPONSE_MODEL","getEvaluationOutputMessages","SPAN_STATUS_ERROR","withScope","spanToTraceContext","captureException","getClient","isPlainObject","GEN_AI_SYSTEM_INSTRUCTIONS","dc.tracingChannel","getActiveSpan","spanToJSON","SENTRY_OP","GEN_AI_GENERATE_CONTENT","handleCallbackErrors","DEBUG_BUILD","debug","isObjectLike","getActiveSpan","addNonEnumerableProperty","withActiveSpan","SPAN_STATUS_ERROR","isReadableStream","dc.tracingChannel","waitForTracingChannelBinding","vercelAiModuleNames","defineIntegration","addNonEnumerableProperty","ORIGIN","MIDDLEWARE","HANDLER","ROUTER","NOOP","captureException","withActiveSpan","getActiveSpan","setHttpServerSpanRouteAttribute","getIsolationScope","getDefaultIsolationScope","DEBUG_BUILD","debug","getClient","hasSpanStreamingEnabled","startInactiveSpan","ROUTER_SPAN_NAME_FALLBACK","REQUEST_HANDLER_SPAN_NAME_FALLBACK","SENTRY_ORIGIN","SENTRY_OP","HTTP_ROUTE","SPAN_STATUS_ERROR","stringMatchesSomePattern","INTEGRATION_NAME","expressModuleNames","diagnosticsChannel.tracingChannel","defineIntegration","getIsolationScope","httpRequestToRequestData","captureException","startInactiveSpan","SENTRY_OP","DB_QUERY","SENTRY_KIND","SENTRY_ORIGIN","DB_OPERATION_NAME","net","DB_COLLECTION_NAME","DB_NAMESPACE","DB_SYSTEM_NAME","SERVER_ADDRESS","SERVER_PORT","SENTRY_ORIGIN","FAAS_NAME","FAAS_TRIGGER","SENTRY_KIND","SENTRY_OP","FUNCTION_GCP","SENTRY_SEGMENT_NAME_SOURCE","GCP_FUNCTION_CONTEXT_TYPE","getClient","hasSpanStreamingEnabled","SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK","startSpanManual","SPAN_STATUS_ERROR","captureException","flush","diagnosticsChannel.tracingChannel","INTEGRATION_NAME","firebaseModuleNames","defineIntegration","CACHE_GET","CACHE_PUT","CACHE_REMOVE","GLOBAL_OBJ","diagnosticsChannel.tracingChannel","CACHE_OPERATION_NAMES","getClient","startInactiveSpan","hasSpanStreamingEnabled","SENTRY_OP","CACHE_OPERATION","SENTRY_ORIGIN","CACHE_KEY","DB_OPERATION_NAME","DB_COLLECTION_NAME","DB_SYSTEM_NAME","CACHE_HIT","flushIfServerless","isObjectLike","safeDateNow","GLOBAL_OBJ","isObjectLike","setHttpStatus","getActiveSpan","spanToJSON","getRootSpan","SENTRY_OP","HTTP_SERVER","parseStringToURLObject","diagnosticsChannel.tracingChannel","HTTP_SPAN_NAME_FALLBACK","startInactiveSpan","SENTRY_ORIGIN","HANDLER","getHttpSpanDetailsFromUrlObject","getClient","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","MIDDLEWARE","setHttpServerSpanRouteAttribute","httpHeadersToSpanAttributes","SERVER_PORT","GLOBAL_OBJ","diagnosticsChannel.tracingChannel","getTraceData","defineIntegration","_attachHapiErrorHandler"],"sources":["../../src/integrations/koa/koa-error-handler.ts","../../src/integrations/hapi/hapi-types.ts","../../src/integrations/hapi/hapi-utils.ts","../../src/integrations/hapi/hapi-error-handler.ts","../../src/tracing-channel.ts","../../src/utils/moduleInjected.ts","../../src/utils/diagnosticsChannel.ts","../../src/integrations/vercel-ai/gen-ai-recording-mode.ts","../../src/eve.ts","../../src/integrations/fastify/utils.ts","../../src/integrations/fastify/errors.ts","../../src/integrations/fastify/instrumentation.ts","../../src/integrations/fastify/index.ts","../../src/orchestrion/instrumentation.ts","../../src/integrations/prisma/global.ts","../../src/integrations/prisma/tracing-helper.ts","../../src/integrations/prisma/orchestrion.ts","../../src/integrations/prisma/index.ts","../../src/orchestrion/channels.ts","../../src/integrations/amqplib.ts","../../src/ai/core/apiPromise.ts","../../src/integrations/anthropic.ts","../../src/integrations/aws-sdk/constants.ts","../../src/integrations/aws-sdk/services/bedrock-runtime-content.ts","../../src/integrations/aws-sdk/services/bedrock-runtime.ts","../../src/integrations/aws-sdk/services/dynamodb.ts","../../src/integrations/aws-sdk/services/kinesis.ts","../../src/integrations/aws-sdk/services/lambda.ts","../../src/integrations/aws-sdk/services/s3.ts","../../src/integrations/aws-sdk/services/secretsmanager.ts","../../src/integrations/aws-sdk/services/MessageAttributes.ts","../../src/integrations/aws-sdk/services/sns.ts","../../src/integrations/aws-sdk/services/sqs.ts","../../src/integrations/aws-sdk/services/stepfunctions.ts","../../src/integrations/aws-sdk/services/ServicesExtensions.ts","../../src/integrations/aws-sdk/utils.ts","../../src/integrations/aws-sdk/index.ts","../../src/integrations/dataloader.ts","../../src/integrations/generic-pool.ts","../../src/utils/cronMonitoring.ts","../../src/integrations/cron.ts","../../src/integrations/node-cron.ts","../../src/integrations/node-schedule.ts","../../src/integrations/google-genai.ts","../../src/integrations/graphql/constants.ts","../../src/integrations/graphql/utils.ts","../../src/integrations/graphql/graphql-dc-subscriber.ts","../../src/integrations/graphql/resolvers.ts","../../src/integrations/graphql/spans.ts","../../src/integrations/graphql/index.ts","../../src/integrations/hapi/index.ts","../../src/integrations/hono/honoIntegration.ts","../../src/integrations/koa/index.ts","../../src/integrations/redis/redis-span-name.ts","../../src/integrations/redis/redis-statement-serializer.ts","../../src/integrations/redis/redis-cache.ts","../../src/integrations/redis/redis-dc-subscriber.ts","../../src/integrations/redis/ioredis-channel-subscriber.ts","../../src/integrations/redis/index.ts","../../src/integrations/kafkajs/semconv.ts","../../src/integrations/kafkajs/spans.ts","../../src/integrations/kafkajs/consumer.ts","../../src/integrations/kafkajs/index.ts","../../src/integrations/knex.ts","../../src/integrations/openai-compatible.ts","../../src/integrations/groq.ts","../../src/integrations/langchain.ts","../../src/integrations/langgraph.ts","../../src/integrations/flue.ts","../../src/ai/pi-ai/usage.ts","../../src/ai/pi-ai/chat.ts","../../src/integrations/pi-ai.ts","../../src/ai/pi-durable/constants.ts","../../src/ai/pi-durable/utils.ts","../../src/ai/pi-durable/runs.ts","../../src/ai/pi-durable/tools.ts","../../src/ai/pi-durable/index.ts","../../src/integrations/pi-durable.ts","../../src/integrations/mastra-classifier.ts","../../src/integrations/mastra.ts","../../src/integrations/mcp-server.ts","../../src/utils/tunnelServer.ts","../../src/integrations/serveTunnel.ts","../../src/integrations/lru-memoizer.ts","../../src/integrations/mongodb/mongodb-span.ts","../../src/integrations/mongodb/index.ts","../../src/integrations/mongoose/mongoose-dc-subscriber.ts","../../src/integrations/mongoose/mongoose-legacy-span.ts","../../src/integrations/mongoose/index.ts","../../src/integrations/mistral.ts","../../src/integrations/together-ai.ts","../../src/integrations/typesafe.ts","../../src/integrations/mysql.ts","../../src/integrations/mysql2/mysql2-dc-subscriber.ts","../../src/integrations/mysql2/index.ts","../../src/integrations/openai.ts","../../src/integrations/pg.ts","../../src/integrations/postgresjs/postgresjs-dc-subscriber.ts","../../src/integrations/postgresjs/index.ts","../../src/integrations/neon.ts","../../src/integrations/tedious.ts","../../src/ai/vercel-ai/index.ts","../../src/integrations/vercel-ai/util.ts","../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts","../../src/integrations/vercel-ai/vercel-ai-tool-telemetry.ts","../../src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts","../../src/integrations/vercel-ai/index.ts","../../src/integrations/express/route.ts","../../src/integrations/express/utils.ts","../../src/integrations/express/error-handled.ts","../../src/integrations/express/instrumentation.ts","../../src/integrations/express/index.ts","../../src/integrations/express/error-handler.ts","../../src/integrations/firebase/firestore.ts","../../src/integrations/firebase/functions.ts","../../src/integrations/firebase/instrumentation.ts","../../src/integrations/firebase/index.ts","../../src/integrations/nitro/captureStorageEvents.ts","../../src/integrations/nitro/captureTracingEvents.ts","../../src/integrations/nitro/setServerTimingHeaders.ts","../../src/integrations/nitro/index.ts","../../src/integrations/index.ts","../../src/index.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { addNonEnumerableProperty, captureException, withActiveSpan } from '@sentry/core';\n\n// Marks a koa app as already carrying the Sentry error listener, so repeat\n// attachments only ever register a single listener — whether reached via the\n// `callback` channel or a lingering manual `setupKoaErrorHandler` call.\nconst ERROR_HANDLER_ATTACHED = '__SENTRY_KOA_ERROR_HANDLER_ATTACHED__';\n\n/**\n * Key under which the koa instrumentation stashes the request's active span on\n * the koa `ctx`. Koa emits its `error` event from `handleRequest`'s `.catch()`,\n * *after* the middleware chain has unwound and no span is active — so we capture\n * within this stashed span to keep the error linked to the request's trace.\n */\nexport const KOA_CONTEXT_SPAN = '__SENTRY_KOA_SPAN__';\n\n/** The subset of a koa `Application` the error handler needs (it extends `EventEmitter`). */\nexport interface KoaApp {\n on(event: 'error', listener: (error: unknown, context?: unknown) => void): unknown;\n [key: string]: unknown;\n}\n\ntype MarkedKoaApp = KoaApp & { [ERROR_HANDLER_ATTACHED]?: boolean };\n\n/**\n * Attach a Sentry error listener to a koa app's `error` event.\n *\n * Koa emits `'error'` for every request error that bubbles up unhandled, so a\n * single `app.on('error')` listener captures the same errors a top-level\n * try/catch middleware would — without depending on middleware order. The error\n * is captured within the request's koa span (stashed on the koa `ctx` under\n * {@link KOA_CONTEXT_SPAN}) so it keeps its trace linkage, since koa emits the\n * event after the middleware spans have already ended.\n *\n * Idempotent — the app is marked so auto-registration (via the `callback`\n * channel) and any explicit `setupKoaErrorHandler` call never stack up multiple\n * listeners.\n *\n * @deprecated Internal. The error handler is registered automatically by the koa\n * instrumentation; there is no need to call this directly. It is exported only\n * so the deprecated `setupKoaErrorHandler` can delegate to it, and will be\n * removed in a future major version.\n */\nexport function attachKoaErrorHandler(app: KoaApp): void {\n const markedApp = app as MarkedKoaApp;\n if (!markedApp || typeof markedApp.on !== 'function' || markedApp[ERROR_HANDLER_ATTACHED]) {\n return;\n }\n addNonEnumerableProperty(markedApp, ERROR_HANDLER_ATTACHED, true);\n\n markedApp.on('error', (error: unknown, context?: unknown) => {\n const span = (context as { [KOA_CONTEXT_SPAN]?: Span } | undefined)?.[KOA_CONTEXT_SPAN];\n const capture = (): void => {\n captureException(error, {\n mechanism: {\n type: 'auto.middleware.koa',\n handled: false,\n },\n });\n };\n\n if (span) {\n withActiveSpan(span, capture);\n } else {\n capture();\n }\n });\n}\n","/*\n * Structural type definitions and constants ported from the vendored\n * `@opentelemetry/instrumentation-hapi` types, with all `@hapi/*` and\n * `@opentelemetry/*` dependencies removed. Only the shapes actually accessed by\n * the orchestrion hapi subscriber are kept.\n */\n\n// Single source of truth for the request lifecycle extension points, so the\n// `ServerRequestExtType` union and the runtime `HapiLifecycleMethodNames` set\n// below can't drift apart.\nconst LIFECYCLE_EXT_POINTS = [\n 'onPreAuth',\n 'onCredentials',\n 'onPostAuth',\n 'onPreHandler',\n 'onPostHandler',\n 'onPreResponse',\n 'onRequest',\n] as const;\n\nexport type ServerRequestExtType = (typeof LIFECYCLE_EXT_POINTS)[number];\n\nexport type LifecycleMethod = (request: unknown, h: unknown, err?: Error) => unknown;\n\nexport interface ServerRouteOptions {\n handler?: LifecycleMethod | unknown;\n [key: string]: unknown;\n}\n\nexport interface ServerRoute {\n path: string;\n method: string | string[];\n handler?: LifecycleMethod | unknown;\n options?: ((server: unknown) => ServerRouteOptions) | ServerRouteOptions;\n [key: string]: unknown;\n}\n\nexport interface ServerExtEventsObject {\n type: string;\n [key: string]: unknown;\n}\n\nexport interface ServerExtEventsRequestObject {\n type: ServerRequestExtType;\n method: LifecycleMethod;\n [key: string]: unknown;\n}\n\nexport interface ServerExtOptions {\n [key: string]: unknown;\n}\n\n/**\n * This symbol is used to mark a Hapi route handler or server extension handler as\n * already patched, since it's possible to use these handlers multiple times\n * i.e. when allowing multiple versions of one plugin, or when registering a plugin\n * multiple times on different servers.\n */\nexport const handlerPatched: unique symbol = Symbol('hapi-handler-patched');\n\nexport type PatchableServerRoute = ServerRoute & {\n [handlerPatched]?: boolean;\n};\n\nexport type PatchableExtMethod = LifecycleMethod & {\n [handlerPatched]?: boolean;\n};\n\nexport type ServerExtDirectInput = [ServerRequestExtType, LifecycleMethod, (ServerExtOptions | undefined)?];\n\nexport const HapiLayerType = {\n ROUTER: 'router',\n PLUGIN: 'plugin',\n EXT: 'server.ext',\n} as const;\n\nexport const HapiLifecycleMethodNames = new Set<string>(LIFECYCLE_EXT_POINTS);\n\n/** The `request`/`error` event payload passed to the error listener. */\nexport interface HapiRequestEvent {\n error?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * The final response attached to a hapi request. On error it is a Boom object\n * (`isBoom`, with the HTTP status under `output.statusCode`); otherwise a normal\n * response carrying `statusCode`. Both are read to derive the status for\n * `shouldHandleError`.\n */\nexport interface HapiResponse {\n statusCode?: number;\n isBoom?: boolean;\n output?: { statusCode?: number };\n}\n\n/** The subset of a hapi request the error listener reads. */\nexport interface HapiRequest {\n method: string;\n route: { path?: string; method: string };\n response?: HapiResponse;\n [key: string]: unknown;\n}\n\n/**\n * Callback deciding whether an error surfaced by hapi should be captured and\n * sent to Sentry. Receives the error and the hapi request (whose `response`\n * carries the resolved HTTP status).\n */\nexport type HapiShouldHandleError = (error: unknown, request: HapiRequest) => boolean;\n\n/** The shared hapi server event emitter (`core.events`, a Podium instance). */\nexport interface HapiServerEvents {\n on(\n criteria: { name: string; channels: string[] },\n listener: (request: HapiRequest, event: HapiRequestEvent) => void,\n ): void;\n [key: string]: unknown;\n}\n\n/** The subset of a hapi server the error handler needs. */\nexport interface HapiServer {\n events: HapiServerEvents;\n [key: string]: unknown;\n}\n","/*\n * OTel-free, `@hapi/*`-free port of the span-building helpers and handler/ext\n * wrap logic from the vendored `@opentelemetry/instrumentation-hapi`\n * (upstream @opentelemetry/instrumentation-hapi@0.64.0). Span output (names,\n * origins, attributes) is kept close to that instrumentation — except the\n * span ops, which are normalized to cross-framework ops (`handler` for plugin\n * routes, `router` for routes, `middleware` for server extensions); span\n * creation goes through the `@sentry/core` API and the OTel active-span guard\n * is replaced with `getActiveSpan()`.\n */\n\nimport {\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport {\n HAPI_EXT_TYPE,\n HAPI_PLUGIN_NAME,\n HAPI_TYPE,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_EXT_TYPE,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type {\n HapiRequest,\n LifecycleMethod,\n PatchableExtMethod,\n PatchableServerRoute,\n ServerExtDirectInput,\n ServerExtEventsObject,\n ServerExtEventsRequestObject,\n ServerRequestExtType,\n ServerRouteOptions,\n} from './hapi-types';\nimport { handlerPatched, HapiLayerType, HapiLifecycleMethodNames } from './hapi-types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\n/**\n * Default function deciding whether an error should be sent to Sentry.\n *\n * Captures 5xx errors and any error whose status can't be resolved; skips 3xx\n * and 4xx (client errors / redirects) and 2xx-and-below outliers are captured\n * as they usually signal an unmapped thrown error. Mirrors the defaults used by\n * the other server framework integrations.\n */\nexport function defaultShouldHandleError(error: unknown, request: HapiRequest): boolean {\n const statusCode = getResponseStatusCode(request, error);\n if (typeof statusCode !== 'number') {\n return true;\n }\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Resolve the HTTP status for an errored hapi request: prefer the resolved\n * response (Boom `output.statusCode`, else `statusCode`), falling back to a Boom\n * error passed directly.\n */\nfunction getResponseStatusCode(request: HapiRequest, error: unknown): number | undefined {\n const response = request.response;\n if (isObjectLike(response)) {\n if (response.isBoom && isObjectLike(response.output) && typeof response.output.statusCode === 'number') {\n return response.output.statusCode;\n }\n if (typeof response.statusCode === 'number') {\n return response.statusCode;\n }\n }\n\n if (isObjectLike(error) && isObjectLike(error.output) && typeof error.output.statusCode === 'number') {\n return error.output.statusCode;\n }\n\n return undefined;\n}\n\ntype SpanAttributes = Record<string, string | undefined>;\n\ninterface SpanMetadata {\n attributes: SpanAttributes;\n name: string;\n}\n\nconst isLifecycleExtType = (variableToCheck: unknown): variableToCheck is ServerRequestExtType => {\n return typeof variableToCheck === 'string' && HapiLifecycleMethodNames.has(variableToCheck);\n};\n\nconst isLifecycleExtEventObj = (variableToCheck: unknown): variableToCheck is ServerExtEventsRequestObject => {\n const event = (variableToCheck as ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nconst isDirectExtInput = (variableToCheck: unknown): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nconst isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[],\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\n/** Build the span name and attributes for a Hapi route. */\nexport const getRouteMetadata = ({\n path,\n method,\n pluginName,\n}: {\n path: string;\n method?: string;\n pluginName?: string;\n}): SpanMetadata => {\n const attributes: SpanAttributes = {\n [HTTP_ROUTE]: path,\n [HTTP_REQUEST_METHOD]: method,\n };\n\n if (pluginName) {\n attributes[HAPI_TYPE] = HapiLayerType.PLUGIN;\n attributes[HAPI_PLUGIN_NAME] = pluginName;\n } else {\n attributes[HAPI_TYPE] = HapiLayerType.ROUTER;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router and request\n // handler spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const fallbackName = pluginName ? REQUEST_HANDLER_SPAN_NAME_FALLBACK : ROUTER_SPAN_NAME_FALLBACK;\n const staticName = method ? `${method} ${path}` : path;\n\n return {\n attributes,\n name: isStreamedSpan ? path || fallbackName : staticName,\n };\n};\n\n/** Build the span name and attributes for a Hapi server extension. */\nexport const getExtMetadata = (\n extPoint: ServerRequestExtType,\n pluginName?: string,\n methodName?: string,\n): SpanMetadata => {\n let baseName = `ext - ${extPoint}`;\n if (methodName && methodName !== 'method') {\n // `method` is the default name for the extension in the ServerExtEventsObject format.\n baseName = `ext - ${extPoint} - ${methodName}`;\n }\n const attributes: SpanAttributes = {\n [HAPI_EXT_TYPE]: extPoint,\n // TODO(v12): Remove `server.ext.type`, which `hapi.ext.type` replaces.\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_EXT_TYPE]: extPoint,\n [HAPI_TYPE]: HapiLayerType.EXT,\n };\n if (pluginName) {\n return {\n attributes: { ...attributes, [HAPI_PLUGIN_NAME]: pluginName },\n name: `${pluginName}: ${baseName}`,\n };\n }\n return { attributes, name: baseName };\n};\n\nconst HAPI_TYPE_TO_SPAN_OP: Record<string, string> = {\n [HapiLayerType.PLUGIN]: HANDLER,\n [HapiLayerType.ROUTER]: ROUTER,\n [HapiLayerType.EXT]: MIDDLEWARE,\n};\n\nfunction startMetadataSpan(metadata: SpanMetadata, original: () => unknown): unknown {\n const hapiType = metadata.attributes[HAPI_TYPE];\n const op = hapiType ? HAPI_TYPE_TO_SPAN_OP[hapiType] : undefined;\n return startSpan(\n {\n name: metadata.name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: 'auto.http.hapi',\n },\n },\n original,\n );\n}\n\n// The route config can register several methods (or `'*'`), so read the method\n// Hapi resolved for this request instead.\nfunction getRequestMethod(request: unknown): string | undefined {\n return isObjectLike(request) && typeof request.method === 'string' ? request.method.toUpperCase() : undefined;\n}\n\n/**\n * Patches each individual route handler method in order to create the span. It\n * does not create spans when there is no parent span.\n */\nfunction wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: LifecycleMethod) => LifecycleMethod = oldHandler => {\n return function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata({ path: route.path, method: getRequestMethod(params[0]), pluginName });\n return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as LifecycleMethod);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server: unknown): ServerRouteOptions {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as LifecycleMethod);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as LifecycleMethod);\n }\n return route;\n}\n\n/**\n * Wraps request extension methods to add instrumentation to each new extension\n * handler. It does not create spans when there is no parent span.\n */\nfunction wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: ServerRequestExtType,\n pluginName?: string,\n): T {\n if (Array.isArray(method)) {\n for (let i = 0; i < method.length; i++) {\n method[i] = wrapExtMethods(method[i]!, extPoint);\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n return startMetadataSpan(metadata, () => method.apply(undefined, params));\n };\n // Mark the wrapper too (not just the original)\n newHandler[handlerPatched] = true;\n return newHandler as T;\n }\n return method;\n}\n\n/**\n * Wrap the route handler(s) in the live `server.route` arguments array, mutating\n * `args[0]` in place. `args[0]` is either a single route options object or an\n * array of them. Idempotent via the `handlerPatched` marker.\n */\nexport function wrapRouteArguments(args: unknown[], pluginName?: string): void {\n const route = args[0] as PatchableServerRoute | PatchableServerRoute[];\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n route[i] = wrapRouteHandler(route[i]!, pluginName);\n }\n } else {\n args[0] = wrapRouteHandler(route, pluginName);\n }\n}\n\n/**\n * Wrap the extension method(s) in the live `server.ext` arguments array,\n * mutating `args` in place. Handles the three accepted input shapes:\n * `(eventsArray)`, `(lifecycleEventObject)`, and `(extTypeString, method, options)`.\n * Idempotent via the `handlerPatched` marker.\n */\nexport function wrapExtArguments(args: unknown[], pluginName?: string): void {\n if (Array.isArray(args[0])) {\n const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i]!;\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as ServerExtEventsRequestObject;\n const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return;\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = wrapExtMethods(method, extInput[0], pluginName);\n args[1] = handler;\n return;\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n }\n}\n","import {\n addNonEnumerableProperty,\n captureException,\n debug,\n getDefaultIsolationScope,\n getIsolationScope,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { HapiRequest, HapiRequestEvent, HapiServer, HapiServerEvents, HapiShouldHandleError } from './hapi-types';\nimport { defaultShouldHandleError } from './hapi-utils';\n\n// Holds the Sentry error-handling state on a server's shared event emitter. Its\n// presence means the single Sentry error listener is already attached, so repeat\n// attachments only ever register one listener — whether reached via the `start`\n// and `initialize` channels, a plugin clone that shares the same emitter, or a\n// manual `setupHapiErrorHandler` call.\n//\n// The `shouldHandleError` predicate lives on this shared object (rather than\n// being captured by the listener) so a later attach carrying an explicit\n// predicate can upgrade it in place: the integration's configured\n// `shouldHandleError` must win even when a default-valued attach (e.g. the\n// deprecated `setupHapiErrorHandler`, which precedes `server.start()`) ran first.\nconst ERROR_HANDLER_STATE = '__SENTRY_HAPI_ERROR_HANDLER_STATE__';\n\ninterface HapiErrorHandlerState {\n shouldHandleError: HapiShouldHandleError;\n}\n\ntype MarkedServerEvents = HapiServerEvents & { [ERROR_HANDLER_STATE]?: HapiErrorHandlerState };\n\nfunction isErrorEvent(event: HapiRequestEvent): boolean {\n return !!(event && typeof event === 'object' && 'error' in event && event.error);\n}\n\n/**\n * Attach a Sentry error listener to a Hapi server's shared event emitter.\n *\n * The listener sets the isolation scope's transaction name from the errored\n * route and captures the error. It is attached once per server: hapi shares one\n * event emitter (`core.events`) across the root server and every plugin clone,\n * so a single listener covers all requests.\n *\n * Idempotent — the emitter carries the handler state, so auto-registration (via\n * the `start` / `initialize` channels) and any explicit `setupHapiErrorHandler`\n * call never stack up multiple listeners.\n *\n * `shouldHandleError` gates which errors are captured (defaults to\n * {@link defaultShouldHandleError}). When omitted, a previously installed\n * predicate is left untouched; when provided, it overrides whatever was set\n * before — so the integration's configured predicate wins over a prior\n * default-valued attach, regardless of ordering.\n */\nexport function attachHapiErrorHandler(server: HapiServer, shouldHandleError?: HapiShouldHandleError): void {\n const events = server?.events as MarkedServerEvents | undefined;\n if (!events) {\n return;\n }\n\n const existingState = events[ERROR_HANDLER_STATE];\n if (existingState) {\n // Listener already attached: only an explicit predicate upgrades it, so a\n // later default-valued attach never downgrades a configured one.\n if (shouldHandleError) {\n existingState.shouldHandleError = shouldHandleError;\n }\n return;\n }\n\n const state: HapiErrorHandlerState = { shouldHandleError: shouldHandleError ?? defaultShouldHandleError };\n addNonEnumerableProperty(events, ERROR_HANDLER_STATE, state);\n\n events.on({ name: 'request', channels: ['error'] }, (request: HapiRequest, event: HapiRequestEvent) => {\n if (getIsolationScope() !== getDefaultIsolationScope()) {\n const route = request.route;\n if (route?.path) {\n getIsolationScope().setTransactionName(`${request.method.toUpperCase()} ${route.path}`);\n }\n } else {\n DEBUG_BUILD &&\n debug.warn('Isolation scope is still the default isolation scope - skipping setting transactionName');\n }\n\n if (isErrorEvent(event) && state.shouldHandleError(event.error, request)) {\n captureException(event.error, {\n mechanism: {\n type: 'auto.function.hapi',\n handled: false,\n },\n });\n }\n });\n}\n","import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ExclusiveEventHintOrCaptureContext, Span } from '@sentry/core';\nimport {\n debug,\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n getAsyncContextStrategy,\n getMainCarrier,\n spanIsIgnored,\n getRootSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n /**\n * The current active span for the traced call.\n */\n _sentrySpan?: Span;\n\n /**\n * The context's active store value, used to restore the context for asyncStart continuations for callback-based tracing.\n */\n _sentryCallerStore?: unknown;\n\n /** Set by Node's tracing channel when the traced operation failed. */\n error?: unknown;\n};\n\n/*\n * A type patch so that we don't have to handle all subscription types.\n */\nexport interface SentryTracingChannel<TData extends object = object> extends Omit<\n TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>,\n 'subscribe' | 'unsubscribe'\n> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n}\n\nexport interface TracingChannelLifeCycleOptions<TData extends object = object> {\n /**\n * Invoked with the span and the channel context object once the traced operation completes\n * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup.\n */\n beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void;\n\n /**\n * Whether a thrown error is captured as a Sentry event. The span is always marked with error status regardless. Defaults to `false`.\n * You can alternatively pass a function that sets the ExclusiveEventHintOrCaptureContext on the captured error.\n * Set `true` for instrumentations that own the error boundary, (e.g: route handlers)\n * For database drivers, it is not recommended to set this at all.\n */\n captureError?: boolean | ((e: unknown) => ExclusiveEventHintOrCaptureContext);\n\n /**\n * Take ownership of *when* the span ends: return `true` and the helper won't end it on\n * `end`/`asyncEnd`. For results that settle out-of-band — e.g. a streamed `EventEmitter` that\n * completes via its own `'end'`/`'error'` events.\n *\n * Call `end` when it settles — `end()` on success, `end(error)` on failure. `end` owns *how* the span\n * ends (error status/attributes, `captureError`, `beforeSpanEnd`) and is idempotent. Default `false`\n * lets the helper end the span as usual.\n */\n deferSpanEnd?: (args: {\n span: Span;\n data: TracingChannelPayloadWithSpan<TData>;\n /** Ends the span: `end()` on success, `end(error)` on failure (which marks `data` as errored). Idempotent. */\n end: (error?: unknown) => void;\n }) => boolean;\n}\n\n/** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */\nexport interface TracingChannelBindingHandle<TData extends object = object> {\n /**\n * The tracing channel with the span bound into async context.\n */\n channel: SentryTracingChannel<TData>;\n\n /**\n * Tears down the binding: unsubscribes lifecycle handlers, when present, and unbinds the start store.\n * Idempotent, and a no-op when no async context binding was available.\n */\n unbind: () => void;\n}\n\nconst NOOP = (): void => {};\n\n/** Runs a span-building callback so a throw inside it can never break the user's traced call. */\nexport function safeChannelCallback<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n DEBUG_BUILD && debug.warn('[instrumentation] error handling channel event', error);\n return undefined;\n }\n}\n\n/**\n * Bind a span and its lifecycle to a tracing channel so the span becomes the active async context\n * for the traced operation and is ended when the operation completes.\n *\n * `getSpan` may return `undefined` to opt a payload out entirely: nothing is bound, no span is\n * tracked, and the active context is left untouched. Use it for events that ride the same channel\n * but should reuse the enclosing span instead of opening (and ending) their own — e.g. an agent\n * loop's per-step events, where ending a freshly opened span would close the parent prematurely.\n */\nexport function bindTracingChannelToSpan<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: TracingChannelLifeCycleOptions<TData>,\n): TracingChannelBindingHandle<TData> {\n const handle = bindSpanToChannelStore(channel, getSpan);\n\n const beforeSpanEnd = opts?.beforeSpanEnd;\n const deferSpanEnd = opts?.deferSpanEnd;\n const getErrorHint = (e: unknown): ExclusiveEventHintOrCaptureContext => {\n if (typeof opts?.captureError === 'function') {\n return opts.captureError(e);\n }\n\n return {\n mechanism: {\n type: 'auto.diagnostic_channels.bind_span',\n handled: false,\n },\n };\n };\n\n // Apply Sentry error status + attributes (and capture, if configured) to a span. Shared by the\n // channel `error` lifecycle and the deferred `end` util so the two can't drift.\n const annotateSpanError = (span: Span, error: unknown): void => {\n if (opts?.captureError) {\n captureException(error, getErrorHint(error));\n }\n\n const { message, attributes } = getErrorInfo(error);\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n span.setAttributes(attributes);\n };\n\n // Creates an end fn for deferred handlers to use, ensures consistent span end behavior\n const makeDeferredEnd = (span: Span, data: TracingChannelPayloadWithSpan<TData>) => {\n let ended = false;\n\n return (error?: unknown): void => {\n if (ended) {\n return;\n }\n\n ended = true;\n if (error !== undefined) {\n annotateSpanError(span, error);\n // Without this the payload still looks successful, so `beforeSpanEnd` enriches the span from\n // a `result` the operation never produced.\n data.error = error;\n }\n\n endBoundSpan(data, beforeSpanEnd);\n };\n };\n\n const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = {\n start: NOOP,\n asyncStart: NOOP,\n end(data) {\n // The operation settled synchronously (returned or threw)\n // Presence checks because caller can return `undefined` result or throw a falsy value.\n if ('error' in data || 'result' in data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n }\n },\n error(data) {\n // No span was bound for this payload (`getSpan` returned undefined), so there is nothing to\n // annotate and no instrumentation that owns capturing this error.\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n\n annotateSpanError(span, data.error);\n },\n asyncEnd(data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n },\n };\n\n handle.channel.subscribe(subscribers);\n\n return {\n channel: handle.channel,\n unbind: () => {\n handle.channel.unsubscribe(subscribers);\n handle.unbind();\n },\n };\n}\n\n/**\n * Bind a span into the channel's async context so it becomes active for the traced operation,\n * without managing its lifecycle. The primitive behind {@link bindTracingChannelToSpan}, which\n * layers span-ending and error handling on top.\n *\n * `getSpan` may return `undefined` to leave the active context untouched for that payload.\n */\nexport function bindSpanToChannelStore<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n): TracingChannelBindingHandle<TData> {\n // Grabs the tracing channel binding defined by the AsyncContext strategy implementation\n const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();\n\n // If no binding, then either the implementer doesn't support tracing channels or there is no active strategy\n // Failure mode here means we would still access the channel and potentially subscribe to it, but parenting will be off.\n if (!binding) {\n DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.');\n\n return {\n channel,\n unbind: NOOP,\n };\n }\n\n // Grab the ALS instance, we don't really care what is in it as long as the AsyncContext strategy can use its value to figure out parenting.\n const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>;\n\n // bindStore activates the ALS for the traced call; any getStore() inside it returns the value bound for that context.\n // 1. Produce: Binds the span to the active context via withActiveSpan(span), and returns the store for the active context.\n // 2. Bind: the courier hands that opaque value to channel.start.bindStore(asyncLocalStorage, producer), which runs the traced op inside asyncLocalStorage.run(value, …); it never inspects the value.\n // 3. Read: inside the op, Sentry's scope machinery calls getScopes() → asyncStorage.getStore() on that same ALS, so getCurrentScope/getIsolationScope/getActiveSpan resolve to the scope carrying our span.\n // 4. Nest: any child span started in the traced op parents to that active span.\n channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n // Stash the caller's store before we swap in the span store, so `asyncStart` can restore it for\n // callback-style channels (see `_sentryCallerStore`).\n data._sentryCallerStore = asyncLocalStorage.getStore();\n\n const span = getSpan(data);\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return data._sentryCallerStore as TData;\n }\n data._sentrySpan = span;\n\n return getStoreWithActiveSpan(asyncLocalStorage, span) as TData;\n });\n\n // Restore the caller's context for the async continuation. Only callback-style channels `runStores`\n // `asyncStart` (so the callback runs inside this store). promise channels `publish` it, leaving this\n // inert, their continuation already inherits the caller's context natively.\n channel.asyncStart.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n return data._sentryCallerStore as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the stores\n channel.start.unbindStore(asyncLocalStorage);\n channel.asyncStart.unbindStore(asyncLocalStorage);\n },\n };\n}\n\nfunction endBoundSpan<TData extends object>(\n data: TracingChannelPayloadWithSpan<TData>,\n beforeSpanEnd: TracingChannelLifeCycleOptions<TData>['beforeSpanEnd'],\n): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n beforeSpanEnd?.(span, data);\n span.end();\n}\n\ntype ErrorInfo = {\n message: string | undefined;\n attributes: Record<string, string>;\n};\n\n/**\n * Best-effort message and attribute extraction for thrown/rejected values.\n */\nfunction getErrorInfo(error: unknown): ErrorInfo {\n const errorIsObject = isObjectLike(error);\n const raw = errorIsObject ? ('message' in error ? error.message : undefined) : error;\n\n // Leave the status message unset if not set (e.g. an `AggregateError` from\n // ECONNREFUSED, whose `.message` is empty). Otherwise cast to string.\n const message = raw ? String(raw) : undefined;\n const type = errorIsObject && 'name' in error ? String(error.name) : 'unknown';\n\n return {\n message,\n attributes: {\n [ERROR_TYPE]: type,\n },\n };\n}\n\nfunction getStoreWithActiveSpan(asyncLocalStorage: AsyncLocalStorage<unknown>, span: Span): unknown {\n // Do not make an ignored *child* the active span: no span is emitted for it, so its children and\n // outgoing requests must propagate from the nearest emitted parent instead. An ignored *root* is\n // still activated so its whole subtree is dropped with it. Mirrors core `startSpan` and the OTel\n // context manager (`spanIsIgnored(span) && getRootSpan(span) !== span`).\n if (spanIsIgnored(span) && getRootSpan(span) !== span) {\n return asyncLocalStorage.getStore();\n }\n\n return withActiveSpan(span, () => {\n return asyncLocalStorage.getStore();\n });\n}\n","import type { Integration } from '@sentry/core';\nimport { getClient, GLOBAL_OBJ } from '@sentry/core';\n\n/**\n * Record a bundler-injected module and notify channel integrations. This is the\n * runtime target of the snippet the `tracingChannelImport` override splices\n * into every instrumented module (see\n * `orchestrion/bundler/moduleInjectedTransform.ts`), so it runs when that module\n * is first evaluated — the moment its diagnostics channels can start publishing.\n *\n * Lives on the main `@sentry/server-utils` entry, not the orchestrion one: it is\n * a plain runtime helper (reads the global marker, emits a client event) with no\n * dependency on the orchestrion bundler/config code, and the injected snippet\n * imports it from the same entry as the subscriber factories.\n *\n * It records the module name on the global orchestrion marker, stores the\n * module's channel-subscriber integration factory (when the module has one)\n * keyed by module name, and emits the `orchestrion.module-injected` client\n * event. Recording happens BEFORE the emit so listeners triggered by the event\n * can read the marker.\n *\n * Deliberately record-and-emit only — no `addIntegration` here. Whether an\n * integration is *installed* is each SDK's policy: `@sentry/node` registers its\n * channel integrations statically and only needs the event to trigger their\n * lazy subscription (so a user who removed one from `integrations` stays opted\n * out), while a bundler-only SDK like `@sentry/cloudflare` instantiates the\n * stored factories at `init()` and listens for this event to pick up modules\n * that evaluate later (e.g. a lazily-required driver after a per-request\n * `init()` already snapshotted the marker).\n */\nexport function orchestrionModuleInjected(moduleName: string, integrationFn?: () => Integration): void {\n const marker = (GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ??= {});\n\n // Runtime guard, not just type narrowing: a banner from another SDK copy or\n // version may have written a non-Set flag here; leave that untouched.\n if (marker.bundler === undefined || marker.bundler instanceof Set) {\n (marker.bundler ??= new Set()).add(moduleName);\n }\n\n if (integrationFn) {\n (marker.integrations ??= new Map()).set(moduleName, integrationFn);\n }\n\n getClient()?.emit('orchestrion.module-injected', moduleName);\n}\n","// oxlint-disable-next-line no-restricted-imports\nimport * as nodeDiagnosticsChannel from 'node:diagnostics_channel';\nimport { isBun } from './runtime';\n\n// Bun garbage-collects a diagnostics channel that no code references, together with its\n// subscribers, so a subscription made at `init()` can stop receiving messages after the next GC.\n// Node and Deno keep a channel alive while it has subscribers. On Bun these wrappers of the\n// `node:diagnostics_channel` functions keep a reference to every channel they return, so the SDK's\n// subscriptions stay active. Other runtimes get the original functions.\n// See https://github.com/oven-sh/bun/issues/43086\nconst keepChannelsReferenced = isBun();\n\nconst channelsByName = new Map<string | symbol, nodeDiagnosticsChannel.Channel>();\nconst tracingChannelsByName = new Map<string, nodeDiagnosticsChannel.TracingChannel>();\n\n/** `diagnostics_channel.channel()`, with the returned channel kept referenced on Bun. */\nexport const channel: typeof nodeDiagnosticsChannel.channel = keepChannelsReferenced\n ? name => {\n let result = channelsByName.get(name);\n if (!result) {\n result = nodeDiagnosticsChannel.channel(name);\n channelsByName.set(name, result);\n }\n return result;\n }\n : nodeDiagnosticsChannel.channel;\n\n/** `diagnostics_channel.subscribe()`, on Bun on a channel kept referenced by {@link channel}. */\nexport const subscribe: typeof nodeDiagnosticsChannel.subscribe = keepChannelsReferenced\n ? (name, onMessage) => {\n channel(name).subscribe(onMessage);\n }\n : nodeDiagnosticsChannel.subscribe;\n\n/**\n * `diagnostics_channel.tracingChannel()`, with the returned tracing channel (and so its five\n * channels) kept referenced on Bun when it is created by name. `undefined` where the runtime has\n * no `tracingChannel` (Node < 18.19), like the original export.\n */\nexport const tracingChannel: typeof nodeDiagnosticsChannel.tracingChannel =\n keepChannelsReferenced && nodeDiagnosticsChannel.tracingChannel\n ? (((nameOrChannels: Parameters<typeof nodeDiagnosticsChannel.tracingChannel>[0]) => {\n if (typeof nameOrChannels !== 'string') {\n return nodeDiagnosticsChannel.tracingChannel(nameOrChannels);\n }\n let result = tracingChannelsByName.get(nameOrChannels);\n if (!result) {\n result = nodeDiagnosticsChannel.tracingChannel(nameOrChannels);\n tracingChannelsByName.set(nameOrChannels, result);\n }\n return result;\n }) as typeof nodeDiagnosticsChannel.tracingChannel)\n : nodeDiagnosticsChannel.tracingChannel;\n","import type { Client } from '@sentry/core';\n\nconst eveRecordingClients = new WeakSet<Client>();\n\n/**\n * Mark this client as running under eve, so the Vercel AI channel subscriber records gen_ai\n * inputs/outputs by default, as far as `ai` still provides them.\n *\n * eve stamps every AI SDK call with `recordInputs`/`recordOutputs: false` as its framework default\n * (its content-capture default is \"public conversations only\"). That per-call flag on the\n * `ai:telemetry` channel event otherwise outranks the global `dataCollection.genAI` setting, so\n * message content would be dropped even when the user wants it. In this mode the per-call flag is\n * treated as eve's default rather than an end-user decision: an explicit `recordInputs`/`recordOutputs`\n * on the integration or a `dataCollection.genAI` setting still takes precedence.\n *\n * `ai` >= 7.0.163 strips content from calls with these flags set to false and publishes no channel result. The\n * subscriber then reads the result itself and honors the per-call flags, so this mode only applies to results\n * `ai` publishes. eve >= 1.0.0-rc.10 sets the flags from `Sentry.eveInstrumentation()`'s `tracePolicy`.\n */\nexport function markEveGenAiRecordingDefault(client: Client): void {\n eveRecordingClients.add(client);\n}\n\nexport function isEveGenAiRecordingDefault(client: Client): boolean {\n return eveRecordingClients.has(client);\n}\n","import { defineIntegration, setConversationId } from '@sentry/core';\nimport { markEveGenAiRecordingDefault } from './integrations/vercel-ai/gen-ai-recording-mode';\n\n/**\n * The subset of eve's hook context (`HookContext` from `eve/hooks`) this helper reads. Typed\n * structurally rather than importing from `eve`, so the SDK carries no dependency on the framework —\n * the shape is checked at the `defineHook(...)` call site in the user's app instead.\n */\ninterface EveHookContext {\n session: { id: string };\n}\n\ntype EveHookHandler = (event: unknown, context: EveHookContext) => void;\n\ninterface EveConversationHookOptions {\n /**\n * Derive the Sentry conversation id from the eve hook context. Defaults to the durable session id\n * (`ctx.session.id`), which is stable across every turn of a session and so groups them into one\n * conversation.\n */\n getConversationId?: (context: EveHookContext) => string | null | undefined;\n}\n\n/**\n * Builds the hook definition for an eve `agent/hooks/*.ts` file that tags a session's AI spans with\n * a Sentry conversation id, linking every turn of the session in the Agents \"Conversations\" view.\n *\n * ```ts\n * // agent/hooks/sentry.ts\n * import * as Sentry from '@sentry/node';\n * import { defineHook } from 'eve/hooks';\n *\n * export default defineHook(Sentry.eveConversationHook());\n * ```\n *\n * The id is set on the isolation scope; the default (always-on) `conversationIdIntegration` then\n * stamps `gen_ai.conversation.id` onto the gen_ai spans the Vercel AI instrumentation records for\n * that turn. That indirection is why the id has to be set here and not on the AI call: eve's session\n * id never reaches the AI SDK's telemetry channel, so it can only be attached via the scope.\n *\n * Subscribes to both `turn.started` and `step.started`. Each eve turn is a fresh durable-workflow\n * request with its own isolation scope, and a turn that parks and resumes (approvals, compaction)\n * resumes in yet another request; `turn.started` alone would miss the model calls after a resume.\n * `step.started` fires before every model call, so together they cover each request that produces\n * spans. Re-setting the same id is idempotent, so the overlap is harmless.\n */\nexport function eveConversationHook(options: EveConversationHookOptions = {}): {\n events: Record<'turn.started' | 'step.started', EveHookHandler>;\n} {\n const { getConversationId } = options;\n\n const setConversationIdFromContext: EveHookHandler = (_event, context) => {\n const conversationId = getConversationId ? getConversationId(context) : context.session.id;\n setConversationId(conversationId);\n };\n\n return {\n events: {\n 'turn.started': setConversationIdFromContext,\n 'step.started': setConversationIdFromContext,\n },\n };\n}\n\n/**\n * Integration that handles tracing instrumentation of [eve](https://eve.dev) apps.\n */\nexport const eveIntegration = defineIntegration(() => {\n return {\n name: 'Eve' as const,\n setup(client) {\n markEveGenAiRecordingDefault(client);\n },\n };\n});\n\n/**\n * The eve `tracePolicy` for Sentry's instrumentation file. It always asks for full results, and Sentry filters content\n * when it builds spans, like the other AI integrations do.\n *\n * On eve >= 1.0.0-rc.10 this also sets the AI SDK's `recordInputs`/`recordOutputs` flags, which `ai` >= 7.0.163\n * enforces. They apply to every AI SDK telemetry integration in the app, so those filter content with their own\n * settings, as eve documents.\n */\nexport function eveTracePolicy(): { emit: true; recordInputs: true; recordOutputs: true } {\n return { emit: true, recordInputs: true, recordOutputs: true };\n}\n","import { isObjectLike } from '@sentry/core';\nimport type { FastifyReply, FastifyRequest } from './types';\n\nexport const INTEGRATION_NAME = 'Fastify' as const;\n\n/**\n * Default function to determine if an error should be sent to Sentry\n *\n * 3xx and 4xx errors are not sent by default.\n */\nexport function defaultShouldHandleError(error: Error, _request: FastifyRequest, reply: FastifyReply): boolean {\n const statusCode = getReplyStatusCode(error, reply);\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Fastify runs `onError` hooks before it applies the error's status to the reply\n * (e.g. for a request body that fails to parse), so `reply.statusCode` can still be\n * the default 200. In that case, resolve the status the same way Fastify will.\n */\nfunction getReplyStatusCode(error: Error, reply: FastifyReply): number {\n if (reply.statusCode !== 200) {\n return reply.statusCode;\n }\n\n const errorStatusCode = Number(getErrorStatusCode(error));\n return errorStatusCode >= 400 ? errorStatusCode : 500;\n}\n\nfunction getErrorStatusCode(error: unknown): unknown {\n if (!isObjectLike(error)) {\n return undefined;\n }\n\n return ('statusCode' in error && error.statusCode) || ('status' in error && error.status);\n}\n","import type { FastifyIntegration, FastifyReply, FastifyRequest } from './types';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { addNonEnumerableProperty, captureException, getClient } from '@sentry/core';\nimport { defaultShouldHandleError, INTEGRATION_NAME } from './utils';\n\n// Marks a request whose error has already been captured, so the two code paths that surface the same\n// error (the diagnostics channel and the `onError` hook on Fastify v5) don't send it twice.\nconst kErrorCaptured = Symbol('sentry.fastifyErrorCaptured');\n\nfunction getFastifyIntegration(): FastifyIntegration | undefined {\n const client = getClient();\n return client?.getIntegrationByName(INTEGRATION_NAME);\n}\n\n/**\n * Subscribe to the Fastify v5 error diagnostics channel.\n */\nexport function subscribeToFastifyErrorChannel(): void {\n diagnosticsChannel.subscribe('tracing:fastify.request.handler:error', message => {\n const { error, request, reply } = message as {\n error: Error;\n request: FastifyRequest;\n reply: FastifyReply;\n };\n\n handleFastifyError(request, reply, error);\n });\n}\n\n/**\n * Handle a Fastify error, and possibly send it to Sentry.\n *\n * On Fastify v5 a route handler error surfaces on both the diagnostics channel\n * and the `onError` hook, so this runs twice for the same request. We mark the\n * request with a non-enumerable symbol once it has been captured, and bail out\n * on subsequent calls, so the same error is only sent once. Errors that reach\n * only one path (e.g. thrown in an `onRequest` hook, or on Fastify v3/v4 which\n * has no channel) are captured once.\n */\nexport function handleFastifyError(request: FastifyRequest, reply: FastifyReply, error: Error): void {\n if ((request as Record<symbol, unknown>)[kErrorCaptured]) {\n return;\n }\n\n const shouldHandleError = getFastifyIntegration()?.getShouldHandleError() || defaultShouldHandleError;\n\n if (shouldHandleError(error, request, reply)) {\n addNonEnumerableProperty(request, kErrorCaptured, true);\n\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.function.fastify',\n },\n });\n }\n}\n","/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_ROUTE,\n SENTRY_OP,\n URL_PATH,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n isObjectLike,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance } from './types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { handleFastifyError } from './errors';\n\nconst ORIGIN = 'auto.http.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return isObjectLike(arg) && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * Wire up the request/hook/handler spans and error handling on a Fastify instance.\n *\n * This runs synchronously from the `fastify.initialization` diagnostics channel, which fires while\n * `Fastify()` is still constructing the instance, before any user code runs. Doing it synchronously\n * (rather than via `instance.register()`, which defers the work until the boot phase) is what lets us\n * patch `addHook`/`setNotFoundHandler` in time: `addHook` runs immediately, so hooks a user adds\n * synchronously before `listen()`/`ready()` would otherwise slip through un-instrumented.\n */\nfunction instrumentFastifyInstance(instance: FastifyInstance): void {\n // oxlint-disable-next-line typescript/unbound-method\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', onRoute);\n instance.addHook('onRequest', onRequest);\n instance.addHook('onResponse', onResponse);\n // Must be an async hook: a sync (callback-style) `onError` hook would have to invoke Fastify's\n // `done` callback\n instance.addHook('onError', async (request, reply, error) => {\n handleFastifyError(request, reply, error);\n });\n\n // Patch last, so the hooks we add above go through the original (un-wrapped) `addHook`.\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n}\n\nfunction onRoute(this: any, routeOptions: any): void {\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction onRequest(this: any, request: any, _reply: any, hookDone: () => void): void {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n\n const attributes: Record<string, string> = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: HANDLER,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n setHttpServerSpanRouteAttribute(route);\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n\n const requestSpan = startInactiveSpan({\n name: isStreamedSpan\n ? route || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : route != null\n ? `${request.method} ${route}`\n : 'request',\n attributes,\n });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction onResponse(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): FastifyInstance {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (!request) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : undefined;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route.\n const isStreamedRequestHandlerSpan = hookType === HOOK_TYPE_HANDLER && !!client && hasSpanStreamingEnabled(client);\n\n const attributeHookName = spanAttributes[ATTRIBUTE_HOOK_NAME];\n\n const name = isStreamedRequestHandlerSpan\n ? spanAttributes[HTTP_ROUTE] || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : op && typeof attributeHookName === 'string'\n ? attributeHookName\n : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n attributes: {\n ...spanAttributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 7) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and synchronously instrumenting every Fastify instance as it is created.\n */\nexport function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n if (fastifyInstance) {\n instrumentFastifyInstance(fastifyInstance);\n }\n });\n}\n","import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { FastifyIntegration, FastifyReply, FastifyRequest } from './types';\nimport { instrumentFastify } from './instrumentation';\nimport { defaultShouldHandleError, INTEGRATION_NAME } from './utils';\nimport { subscribeToFastifyErrorChannel } from './errors';\n\n/**\n * Options for the Fastify integration.\n *\n * `shouldHandleError` - Callback method deciding whether error should be captured and sent to Sentry\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.fastifyIntegration({\n * shouldHandleError(_error, _request, reply) {\n * return reply.statusCode >= 500;\n * },\n * });\n * },\n * });\n * ```\n *\n */\ninterface FastifyIntegrationOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured Fastify error\n * @param request Fastify request (or any object containing at least method, routeOptions.url, and routerPath)\n * @param reply Fastify reply (or any object containing at least statusCode)\n */\n shouldHandleError: (error: Error, request: FastifyRequest, reply: FastifyReply) => boolean;\n}\n\nconst _fastifyIntegration = (({ shouldHandleError }: Partial<FastifyIntegrationOptions> = {}) => {\n let _shouldHandleError: (error: Error, request: FastifyRequest, reply: FastifyReply) => boolean;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n _shouldHandleError = shouldHandleError || defaultShouldHandleError;\n\n subscribeToFastifyErrorChannel();\n instrumentFastify();\n },\n getShouldHandleError() {\n return _shouldHandleError;\n },\n } satisfies FastifyIntegration;\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for [Fastify](https://fastify.dev/).\n * This integration supports Fastify v3.21.0-v6.\n *\n * For more information, see the [fastify documentation](https://docs.sentry.io/platforms/javascript/guides/fastify/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.fastifyIntegration()],\n * })\n * ```\n */\nexport const fastifyIntegration = defineIntegration(_fastifyIntegration);\n\n/**\n * No-op kept so existing `setupFastifyErrorHandler(app)` calls keep working.\n * `fastifyIntegration` captures errors on its own.\n *\n * @deprecated Remove this call. To filter errors, set `shouldHandleError` on `fastifyIntegration` instead.\n */\nexport function setupFastifyErrorHandler(_fastify: unknown): void {\n // noop\n}\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { Client } from '@sentry/core';\nimport { addNonEnumerableProperty, debug, GLOBAL_OBJ, waitForTracingChannelBinding } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { isBun, isCloudflareWorkers, isDeno } from '../utils/runtime';\nimport { getOrchestrionInjectedModules } from './detect';\n\n// Marks an instrumentation callback as already run, so it subscribes at most once\n// even when reached through several integration names (e.g. Deno wraps a shared\n// integration under `DenoMysql`) or several clients.\nconst INSTRUMENTED = Symbol.for('SentryOrchestrionInstrumented');\n\n// generic function arguments can only be `any`\n// oxlint-disable-next-line typescript/no-explicit-any\ntype InstrumentationFn = ((...args: any[]) => void) & { [INSTRUMENTED]?: boolean };\n\n// Labels already warned about, so a client per request does not repeat the warning.\nconst warnedMissingCloudflarePlugin = new Set<string>();\n\n/**\n * Run an integration's channel-subscription callback once one of its modules is\n * orchestrion-injected, and never more than once.\n *\n * Channel integrations must NOT subscribe eagerly at `Sentry.init()`: Node caps\n * the number of `diagnostics_channel` channels in use at 1024, and every default\n * channel integration binding several channels up front would burn that budget\n * for modules the app never loads. So we defer:\n *\n * - If a module is already injected, then a bundler transformed and loaded it\n * (which records it via `orchestrionModuleInjected`), or the runtime hook\n * injected it before `init()`, so subscribe right away.\n * - Otherwise wait for the `orchestrion.module-injected` event, which fires\n * when the module is loaded and transformed, before it can publish to its\n * channels.\n *\n * Bun and Deno have no such channel limit and no reliable per-module injection\n * tracking, so there we just subscribe immediately.\n *\n * `waitForTracingChannelBinding` still wraps the callback: the async-context\n * binding the subscription needs for span parenting may not exist yet.\n *\n * Note: it is possible to register extra event listeners, if the same callback\n * is registered multiple times. However, this is (a) not something that happens\n * normally, and (b) ultimately fine, because it'll only call the callback one\n * time. There'll just be a few no-op client event listeners.\n */\nexport function invokeOrchestrionInstrumentation<Callback extends InstrumentationFn>(\n client: Client,\n moduleNames: readonly string[],\n callback: Callback,\n args: Parameters<Callback>,\n // Most integrations parent spans via `bindTracingChannelToSpan`, which needs\n // the async-context binding set up at subscribe time. A few (e.g. Hapi,\n // KafkaJS, Koa, tedious) subscribe without it and create spans directly;\n // they pass `false` so a missing binding never blocks their subscription.\n { requiresTracingChannelBinding = true }: { requiresTracingChannelBinding?: boolean } = {},\n): void {\n (GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ??= {}).channelIntegrations = true;\n\n const label = moduleNames.join(', ');\n\n // `tracingChannel` is unavailable before Node 18.19; nothing to subscribe to.\n if (!diagnosticsChannel.tracingChannel) {\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] no \\`tracingChannel\\` (Node < 18.19), not subscribing`);\n return;\n }\n\n if (hasBeenInstrumented(callback)) {\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] already subscribed, skipping`);\n return;\n }\n\n // cleanup function is passed in so that we only remove the listener\n // once the callback is actually instrumented and called.\n const run = (cleanup?: () => void): void => {\n const subscribe = (): void => {\n if (hasBeenInstrumented(callback)) {\n return;\n }\n markInstrumented(callback);\n cleanup?.();\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] subscribing to channels`);\n callback(...args);\n };\n\n if (!requiresTracingChannelBinding) {\n subscribe();\n return;\n }\n\n // Mark as instrumented only if the channel binding actually lands.\n // Avoids a very narrow case where the binding never arrives within the\n // retry window. So, don't mark until we know we're actually calling.\n waitForTracingChannelBinding(subscribe);\n\n // `waitForTracingChannelBinding` retries once on a timer and then gives up\n // silently. Not being subscribed by now means we took that path, so say so:\n // without this, an integration that never subscribes leaves no trace at all.\n if (DEBUG_BUILD && !hasBeenInstrumented(callback)) {\n debug.log(`[instrumentation:${label}] async-context binding not ready, retrying before subscribing`);\n }\n };\n\n if (isBun() || isDeno()) {\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] Bun/Deno, subscribing eagerly`);\n run();\n return;\n }\n\n const injected = getOrchestrionInjectedModules();\n const injectedName = moduleNames.find(name => injected.includes(name));\n if (injectedName) {\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] \"${injectedName}\" already injected, subscribing now`);\n run();\n return;\n }\n\n // On Cloudflare, only the `@sentry/cloudflare/vite` plugin injects the channels. An entry banner\n // from the plugin defines `bundler` at boot, so without it the channels never fire.\n if (\n DEBUG_BUILD &&\n isCloudflareWorkers() &&\n !GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.bundler &&\n !warnedMissingCloudflarePlugin.has(label)\n ) {\n warnedMissingCloudflarePlugin.add(label);\n debug.warn(\n `[instrumentation:${label}] The integration for \"${label}\" records nothing, because the ` +\n '`@sentry/cloudflare/vite` plugin did not run. Add `sentryCloudflareVitePlugin()` to your Vite config.',\n );\n }\n\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] not injected yet, waiting for the module to load`);\n\n const cleanup = client.on('orchestrion.module-injected', (moduleName: string) => {\n if (hasBeenInstrumented(callback)) {\n cleanup();\n return;\n }\n if (moduleNames.includes(moduleName)) {\n DEBUG_BUILD && debug.log(`[instrumentation:${label}] \"${moduleName}\" injected at runtime, subscribing now`);\n run(cleanup);\n }\n });\n}\n\nfunction hasBeenInstrumented(callback: InstrumentationFn): boolean {\n return callback[INSTRUMENTED] ?? false;\n}\n\nfunction markInstrumented(callback: InstrumentationFn): void {\n addNonEnumerableProperty(callback, INSTRUMENTED, true);\n}\n","/*\n * Copyright Prisma\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/prisma/prisma/tree/b6feea5565ec577545a79547d24273ccdd11b4c7/packages/instrumentation-contract\n * - Upstream version: @prisma/instrumentation-contract@7.8.0\n * - Replaced `import packageJson from '../package.json'` with hardcoded major version\n */\n\nimport type { PrismaInstrumentationGlobalValue, TracingHelper } from './types';\n\nconst majorVersion = '7';\n\nconst GLOBAL_INSTRUMENTATION_KEY = 'PRISMA_INSTRUMENTATION';\nconst GLOBAL_VERSIONED_INSTRUMENTATION_KEY = `V${majorVersion}_PRISMA_INSTRUMENTATION` as const;\n\ntype GlobalThisWithPrismaInstrumentation = typeof globalThis & {\n [GLOBAL_INSTRUMENTATION_KEY]?: PrismaInstrumentationGlobalValue;\n} & {\n [K in typeof GLOBAL_VERSIONED_INSTRUMENTATION_KEY]?: PrismaInstrumentationGlobalValue;\n};\n\nconst globalThisWithPrismaInstrumentation = globalThis as GlobalThisWithPrismaInstrumentation;\n\nexport function getGlobalTracingHelper(): TracingHelper | undefined {\n const versionedGlobal = globalThisWithPrismaInstrumentation[GLOBAL_VERSIONED_INSTRUMENTATION_KEY];\n\n if (versionedGlobal?.helper) {\n return versionedGlobal.helper;\n }\n\n const fallbackGlobal = globalThisWithPrismaInstrumentation[GLOBAL_INSTRUMENTATION_KEY];\n\n return fallbackGlobal?.helper;\n}\n\nexport function setGlobalTracingHelper(helper: TracingHelper): void {\n const globalValue: PrismaInstrumentationGlobalValue = { helper };\n\n globalThisWithPrismaInstrumentation[GLOBAL_VERSIONED_INSTRUMENTATION_KEY] = globalValue;\n globalThisWithPrismaInstrumentation[GLOBAL_INSTRUMENTATION_KEY] = globalValue;\n}\n\nexport function clearGlobalTracingHelper(): void {\n globalThisWithPrismaInstrumentation[GLOBAL_VERSIONED_INSTRUMENTATION_KEY] = undefined;\n globalThisWithPrismaInstrumentation[GLOBAL_INSTRUMENTATION_KEY] = undefined;\n}\n","/*\n * Copyright Prisma\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/prisma/prisma/tree/b6feea5565ec577545a79547d24273ccdd11b4c7/packages/instrumentation\n * - Upstream version: @prisma/instrumentation@7.8.0\n * - Replaced `@prisma/instrumentation-contract` imports with local vendored types\n * - Span creation uses Sentry's span APIs (`startSpanManual` / `startInactiveSpan`) instead of the OTel tracer\n * - Span creation sets the Sentry origin, renames `db_query` spans to their SQL text, and backfills\n * the db system for older Prisma versions\n * - Added a `createEngineSpan` method so a single helper serves both Prisma v5 (which calls\n * `createEngineSpan`) and v6/v7 (which call `dispatchEngineSpans`)\n */\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { debug, getActiveSpan, LRUMap, startInactiveSpan, startSpanManual } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { EngineSpan, ExtendedSpanOptions, SpanCallback, TracingHelper } from './types';\nimport {\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_STATEMENT,\n DB_SYSTEM,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { getSqlQueryAttributes, getSqlSpanName, type SqlDialect, toSqlDialect } from '../../utils/sql';\n\n// Reading `process.env` can throw in runtimes that gate env access (e.g. Deno without `--allow-env`)\n// and `process` may be absent altogether (edge runtimes), so this degrades to `false` in those cases.\nconst showAllTraces = ((): boolean => {\n try {\n return process.env.PRISMA_SHOW_ALL_TRACES === 'true';\n } catch {\n return false;\n }\n})();\n\nconst nonSampledTraceParent = `00-10-10-00`;\n\nconst PRISMA_ORIGIN = 'auto.db.prisma';\n\ntype Options = {\n ignoreSpanTypes: (string | RegExp)[];\n};\n\n// Vendored in from @prisma/instrumentation v5:\ntype V5EngineSpanEvent = {\n span: boolean;\n spans: V5EngineSpan[];\n};\n\ntype V5EngineSpanKind = 'client' | 'internal';\n\ntype V5EngineSpan = {\n span: boolean;\n name: string;\n trace_id: string;\n span_id: string;\n parent_span_id: string;\n start_time: [number, number];\n end_time: [number, number];\n attributes?: Record<string, string>;\n links?: { trace_id: string; span_id: string }[];\n kind: V5EngineSpanKind;\n};\n\n// Prisma v5 dispatches engine spans (`prisma:engine:*`, which carry the SQL `db.statement`) one batch\n// at a time, out of order, and detached from the active span, naming their parent only by id: a span\n// references either a client span (by the Sentry span id Prisma learned via `getTraceParent`) or a\n// sibling engine span (by the engine's own id), and a batch may not contain the parent it references.\n// By the time the engine reports them the client span may already have ended, so `getActiveSpan()`\n// can't be used to find it. `prismaSpanRegistry` maps span ids to their Sentry span, and an engine\n// span whose parent isn't registered yet waits in `pendingEngineSpans` until a later batch registers it.\nconst MAX_TRACKED_PRISMA_SPANS = 1000;\nconst prismaSpanRegistry = new LRUMap<string, Span>(MAX_TRACKED_PRISMA_SPANS);\nconst pendingEngineSpans: V5EngineSpan[] = [];\n\n/** Register a span so v5 engine spans can later resolve it as a parent by the id Prisma reports it under. */\nfunction registerPrismaSpan(id: string, span: Span): void {\n prismaSpanRegistry.set(id, span);\n}\n\n/**\n * Older Prisma versions emit `prisma:engine:db_query` spans without a db system, so it's backfilled here.\n */\nfunction buildSpanAttributes(name: string, attributes: Record<string, unknown> | undefined): SpanAttributes {\n const spanAttributes: SpanAttributes = (attributes as SpanAttributes) || {};\n const statement = getSqlStatement(name, spanAttributes);\n const queryAttributes = getSqlQueryAttributes(statement, getSqlDialect(spanAttributes));\n\n const merged: SpanAttributes = {\n ...queryAttributes,\n ...spanAttributes,\n [SENTRY_ORIGIN]: PRISMA_ORIGIN,\n // Always ours, so the summary (and the streamed span name built from it) is dialect-aware and\n // consistent across Prisma versions, even if Prisma starts reporting its own.\n [DB_QUERY_SUMMARY]: queryAttributes[DB_QUERY_SUMMARY],\n };\n\n // Prisma itself emits the deprecated `db.system` on older versions, so both spellings are checked\n // before backfilling; the backfilled value goes on the stable one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (name === 'prisma:engine:db_query' && merged[DB_SYSTEM] == null && merged[DB_SYSTEM_NAME] == null) {\n merged[DB_SYSTEM_NAME] = 'prisma';\n }\n\n // oxlint-disable-next-line typescript/no-deprecated\n if (merged[DB_SYSTEM] || merged[DB_SYSTEM_NAME]) {\n merged[SENTRY_OP] = 'db';\n }\n\n return merged;\n}\n\n/**\n * The dialect the reported SQL is written in. Prisma is multi-connector, and on MySQL a `\"...\"` run is\n * a string literal rather than a quoted identifier, so sanitizing it as standard SQL leaves the value\n * in place — and a literal containing `FROM`/`JOIN` then reads as a table name in the summary.\n */\nfunction getSqlDialect(attributes: SpanAttributes): SqlDialect {\n // oxlint-disable-next-line typescript/no-deprecated\n const system = attributes[DB_SYSTEM_NAME] ?? attributes[DB_SYSTEM];\n return toSqlDialect(system);\n}\n\n/**\n * The SQL a span reports, if any. Prisma emits it as the deprecated `db.statement` on older versions\n * and as `db.query.text` on the `db_query` spans of newer ones.\n */\nfunction getSqlStatement(name: string, attributes: SpanAttributes): string | undefined {\n // oxlint-disable-next-line typescript/no-deprecated\n const dbStatement = attributes[DB_STATEMENT];\n if (typeof dbStatement === 'string' && dbStatement) {\n return dbStatement;\n }\n const queryText = attributes[DB_QUERY_TEXT];\n if (isDbQuerySpan(name) && typeof queryText === 'string') {\n return queryText;\n }\n return undefined;\n}\n\n/**\n * Db query spans are named like every other SQL span (see `getSqlSpanName`), falling back to the\n * Prisma span name. v5/v6 emit `prisma:engine:db_query`; v7 inlined the engine and emits\n * `prisma:client:db_query`. Other Prisma spans keep their own name, even when they carry db attributes.\n */\nfunction buildSpanName(name: string, attributes: SpanAttributes): string {\n return isDbQuerySpan(name) ? getSqlSpanName(attributes, name) : name;\n}\n\nfunction isDbQuerySpan(name: string): boolean {\n return name === 'prisma:engine:db_query' || name === 'prisma:client:db_query';\n}\n\n/**\n * Create every pending v5 engine span whose parent is now registered, repeating until no further span\n * resolves (so a child queued before its parent is created once the parent arrives in a later batch).\n * Each span is created under its resolved parent and registered by its engine id so its own children\n * can find it; origin, the `prisma:engine:db_query` to SQL rename, and the db system backfill are\n * applied here, exactly as for v6/v7 engine spans.\n */\nfunction createResolvedEngineSpans(): void {\n // Terminates: `createdSpan` is only set true right after a `splice`, so every pass that keeps the\n // loop going strictly shrinks the finite `pendingEngineSpans`; a pass that resolves nothing exits.\n let createdSpan = true;\n while (createdSpan) {\n createdSpan = false;\n for (let i = pendingEngineSpans.length - 1; i >= 0; i--) {\n const engineSpan = pendingEngineSpans[i]!;\n const parentSpan = prismaSpanRegistry.get(engineSpan.parent_span_id);\n if (!parentSpan) {\n continue;\n }\n\n const attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n const span = startInactiveSpan({\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\n startTime: engineSpan.start_time,\n parentSpan,\n });\n registerPrismaSpan(engineSpan.span_id, span);\n\n // Engine links reference other engine spans by their engine id; re-point them at the Sentry spans\n // we minted (mirroring v6/v7's `dispatchEngineSpan`). Links must be added before the span ends,\n // since the SentryTracerProvider seals spans on end. Links to spans we haven't created are dropped.\n if (engineSpan.links) {\n span.addLinks(\n engineSpan.links.flatMap(link => {\n const linkedSpan = prismaSpanRegistry.get(link.span_id);\n return linkedSpan ? [{ context: linkedSpan.spanContext() }] : [];\n }),\n );\n }\n\n span.end(engineSpan.end_time);\n\n pendingEngineSpans.splice(i, 1);\n createdSpan = true;\n }\n }\n}\n\n/**\n * This satisifes the TracingHelper interface for Prisma v5 and v6/v7.\n */\nexport class ActiveTracingHelper implements TracingHelper {\n private ignoreSpanTypes: (string | RegExp)[];\n\n public constructor({ ignoreSpanTypes }: Options) {\n this.ignoreSpanTypes = ignoreSpanTypes;\n }\n\n public isEnabled(): boolean {\n return true;\n }\n\n public getTraceParent(span?: Span): string {\n const spanContext = (span ?? getActiveSpan())?.spanContext();\n if (spanContext) {\n return `00-${spanContext.traceId}-${spanContext.spanId}-0${spanContext.traceFlags}`;\n }\n return nonSampledTraceParent;\n }\n\n public dispatchEngineSpans(spans: EngineSpan[]): void {\n const linkIds = new Map<string, string>();\n const roots = spans.filter(span => span.parentId === null);\n\n for (const root of roots) {\n dispatchEngineSpan(root, spans, linkIds, this.ignoreSpanTypes);\n }\n }\n\n /**\n * Prisma v5 broke the tracing helper interface with the v6 major, replacing `createEngineSpan` with\n * `dispatchEngineSpans`. We implement the v6/v7 interface (`dispatchEngineSpans`) but also keep this\n * v5-only method so the same helper doesn't blow up in Prisma 5 users' faces, minting v5 engine spans\n * through Sentry's span APIs instead of crashing.\n */\n public createEngineSpan(engineSpanEvent: V5EngineSpanEvent): void {\n pendingEngineSpans.push(...engineSpanEvent.spans);\n\n // Resolve before capping so a span is only ever dropped after a full resolution attempt, never\n // before it had a chance to find its parent. What remains are orphans whose parent was never\n // registered (e.g. evicted from the registry under sustained load); cap that backlog so it can't\n // grow without bound.\n createResolvedEngineSpans();\n\n const overflow = pendingEngineSpans.length - MAX_TRACKED_PRISMA_SPANS;\n if (overflow > 0) {\n DEBUG_BUILD &&\n debug.log(`[Prisma] Dropping ${overflow} unresolved v5 engine span(s) whose parent was never registered.`);\n pendingEngineSpans.splice(0, overflow);\n }\n }\n\n public getActiveContext(): Span | undefined {\n return getActiveSpan();\n }\n\n public runInChildSpan<R>(nameOrOptions: string | ExtendedSpanOptions, callback: SpanCallback<R>): R {\n const options: ExtendedSpanOptions = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n\n if (options.internal && !showAllTraces) {\n return callback();\n }\n\n const name = `prisma:client:${options.name}`;\n\n if (shouldIgnoreSpan(name, this.ignoreSpanTypes)) {\n return callback();\n }\n\n const parentSpan = getActiveSpan();\n\n const attributes = buildSpanAttributes(name, options.attributes);\n const spanOptions = {\n name: buildSpanName(name, attributes),\n attributes,\n kind: options.kind,\n links: options.links,\n startTime: options.startTime,\n parentSpan,\n };\n\n if (options.active === false) {\n const span = startInactiveSpan(spanOptions);\n // Register the client span so a v5 engine span (dispatched later, detached) can resolve it as a\n // parent by the Sentry span id Prisma reported via `getTraceParent` (see `createResolvedEngineSpans`).\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n }\n\n return startSpanManual(spanOptions, span => {\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n });\n }\n}\n\nfunction dispatchEngineSpan(\n engineSpan: EngineSpan,\n allSpans: EngineSpan[],\n linkIds: Map<string, string>,\n ignoreSpanTypes: (string | RegExp)[],\n): void {\n if (shouldIgnoreSpan(engineSpan.name, ignoreSpanTypes)) {\n return;\n }\n\n const attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n\n startSpanManual(\n {\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\n startTime: engineSpan.startTime,\n },\n span => {\n linkIds.set(engineSpan.id, span.spanContext().spanId);\n\n if (engineSpan.links) {\n span.addLinks(\n engineSpan.links.flatMap(link => {\n const linkedId = linkIds.get(link);\n if (!linkedId) {\n return [];\n }\n return {\n context: {\n spanId: linkedId,\n traceId: span.spanContext().traceId,\n traceFlags: span.spanContext().traceFlags,\n },\n };\n }),\n );\n }\n\n const children = allSpans.filter(s => s.parentId === engineSpan.id);\n for (const child of children) {\n dispatchEngineSpan(child, allSpans, linkIds, ignoreSpanTypes);\n }\n\n span.end(engineSpan.endTime);\n },\n );\n}\n\nfunction endSpan<T>(span: Span, run: () => T): T {\n let result: T;\n try {\n result = run();\n } catch (reason) {\n span.end();\n throw reason;\n }\n\n if (isPromiseLike(result)) {\n return result.then(\n value => {\n span.end();\n return value;\n },\n reason => {\n span.end();\n throw reason;\n },\n ) as T;\n }\n span.end();\n return result;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return value != null && typeof (value as Record<string, unknown>)['then'] === 'function';\n}\n\n/** Whether `spanName` matches one of the configured `ignoreSpanTypes` patterns. */\nexport function shouldIgnoreSpan(spanName: string, ignoreSpanTypes: (string | RegExp)[]): boolean {\n return ignoreSpanTypes.some(pattern => (typeof pattern === 'string' ? pattern === spanName : pattern.test(spanName)));\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { Span } from '@sentry/core';\nimport { getActiveSpan, getRootSpan, spanIsIgnored, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport { DB_COLLECTION_NAME, DB_OPERATION_NAME, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { prismaChannels, PRISMA_LAZY_TERMINALS } from '../../orchestrion/config/prisma';\nimport type { TracingChannelLifeCycleOptions } from '../../tracing-channel';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport { shouldIgnoreSpan } from './tracing-helper';\n\n// Same span name as Prisma v5–v7's own operation span, so the tree looks the same across majors.\nconst OPERATION_SPAN_NAME = 'prisma:client:operation';\nconst PRISMA_ORIGIN = 'auto.db.prisma';\n\n// Terminals call each other (`delete` reads the row through `first`); only the outermost call is the operation.\nconst operationSpans = new WeakSet<Span>();\n\ninterface PrismaCollection {\n modelName?: unknown;\n tableName?: unknown;\n}\n\ninterface PrismaTerminalChannelContext extends OrchestrionChannelContext {\n self?: PrismaCollection;\n}\n\n// Prisma's `AsyncIterableResult`: `await`, `.then()` and `.first()` all funnel through `toArray()`; only\n// `for await` goes through the iterator.\ninterface LazyResult {\n toArray: () => Promise<unknown>;\n [Symbol.asyncIterator]: () => AsyncIterator<unknown>;\n}\n\ninterface PrismaV8InstrumentationOptions {\n ignoreSpanTypes: (string | RegExp)[];\n}\n\n/**\n * Opens a `prisma:client:operation` span per ORM call, kept active while the terminal runs so the `pg`\n * query spans nest under it like the `db_query` spans did on v5–v7.\n */\nexport function instrumentPrismaV8(options: PrismaV8InstrumentationOptions): void {\n if (shouldIgnoreSpan(OPERATION_SPAN_NAME, options.ignoreSpanTypes)) {\n return;\n }\n\n for (const channelName of Object.values(prismaChannels)) {\n const method = channelName.slice(channelName.lastIndexOf(':') + 1);\n const isLazy = (PRISMA_LAZY_TERMINALS as readonly string[]).includes(method);\n\n bindTracingChannelToSpan<PrismaTerminalChannelContext>(\n diagnosticsChannel.tracingChannel<PrismaTerminalChannelContext>(channelName),\n data => startOperationSpan(method, data),\n isLazy ? { deferSpanEnd: deferSpanEndUntilConsumed } : undefined,\n );\n }\n}\n\nfunction startOperationSpan(method: string, data: PrismaTerminalChannelContext): Span | undefined {\n const parentSpan = getActiveSpan();\n if (parentSpan && operationSpans.has(parentSpan)) {\n return undefined;\n }\n\n const model = stringOrUndefined(data.self?.modelName);\n const table = stringOrUndefined(data.self?.tableName);\n\n const span = startInactiveSpan({\n name: OPERATION_SPAN_NAME,\n onlyIfParent: true,\n parentSpan,\n attributes: {\n [SENTRY_ORIGIN]: PRISMA_ORIGIN,\n [SENTRY_OP]: DB,\n [DB_OPERATION_NAME]: method,\n [DB_COLLECTION_NAME]: table ?? model,\n // Prisma v5–v7's own attributes, kept so existing queries keep matching across the major.\n method,\n model,\n name: model ? `${model}.${method}` : method,\n },\n });\n operationSpans.add(span);\n return span;\n}\n\n// A lazy terminal returns before anything is queried, so the span stays open until the result is consumed,\n// with consumption re-routed through the span's context so the driver call lands under it. A result that is\n// never consumed never ran a query; its span is simply never ended.\nconst deferSpanEndUntilConsumed: NonNullable<\n TracingChannelLifeCycleOptions<PrismaTerminalChannelContext>['deferSpanEnd']\n> = ({ span, data, end }) => {\n const result = data.result;\n if (!isLazyResult(result)) {\n return false;\n }\n\n // A throw in a channel subscriber is an uncaught exception; an unpatchable (frozen) result ends the span now.\n return safeChannelCallback(() => patchConsumption(result, span, end)) ?? false;\n};\n\nfunction patchConsumption(result: LazyResult, span: Span, end: (error?: unknown) => void): boolean {\n const toArray = result.toArray;\n const asyncIterator = result[Symbol.asyncIterator];\n\n // Built before either is installed, so a failed assignment can't leave a half-patched result.\n const patchedToArray = function (this: LazyResult): Promise<unknown> {\n const rows: Promise<unknown> = runUnderSpan(span, () => toArray.call(this));\n // Chained, not side-observed, so a rejected fire-and-forget `toArray()` still surfaces as unhandled.\n return rows.then(\n value => {\n end();\n return value;\n },\n (error: unknown) => {\n end(error);\n throw error;\n },\n );\n };\n const patchedAsyncIterator = function (this: LazyResult): AsyncIterableIterator<unknown> {\n return wrapIterator(\n runUnderSpan(span, () => asyncIterator.call(this)),\n span,\n end,\n );\n };\n\n result.toArray = patchedToArray;\n result[Symbol.asyncIterator] = patchedAsyncIterator;\n\n return true;\n}\n\n// An ignored child span is never emitted, so its children must keep parenting to the nearest emitted span\n// (same rule as the tracing-channel binding and core `startSpan`).\nfunction runUnderSpan<T>(span: Span, callback: () => T): T {\n if (spanIsIgnored(span) && getRootSpan(span) !== span) {\n return callback();\n }\n return withActiveSpan(span, callback);\n}\n\nfunction wrapIterator(\n iterator: AsyncIterator<unknown>,\n span: Span,\n end: (error?: unknown) => void,\n): AsyncIterableIterator<unknown> {\n const settle = (step: Promise<IteratorResult<unknown>>): Promise<IteratorResult<unknown>> =>\n step.then(\n result => {\n if (result.done) {\n end();\n }\n return result;\n },\n error => {\n end(error);\n throw error;\n },\n );\n\n return {\n next: (...args) => settle(runUnderSpan(span, () => iterator.next(...args))),\n return: value => {\n const iteratorReturn = iterator.return?.bind(iterator);\n if (!iteratorReturn) {\n end();\n return Promise.resolve({ done: true, value });\n }\n return settle(runUnderSpan(span, () => iteratorReturn(value)));\n },\n throw: error => {\n const iteratorThrow = iterator.throw?.bind(iterator);\n if (!iteratorThrow) {\n end(error);\n return Promise.reject(error);\n }\n return settle(runUnderSpan(span, () => iteratorThrow(error)));\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isLazyResult(value: unknown): value is LazyResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as LazyResult).toArray === 'function' &&\n typeof (value as LazyResult)[Symbol.asyncIterator] === 'function'\n );\n}\n","import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { prismaModuleNames } from '../../orchestrion/config/prisma';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { setGlobalTracingHelper } from './global';\nimport { instrumentPrismaV8 } from './orchestrion';\nimport { ActiveTracingHelper } from './tracing-helper';\n\nconst INTEGRATION_NAME = 'Prisma' as const;\n\nexport interface PrismaInstrumentationConfig {\n /**\n * Span types that should not be traced. Matched against the full span name (e.g. `prisma:client:operation`),\n * either exactly (string) or by pattern (RegExp).\n */\n ignoreSpanTypes?: (string | RegExp)[];\n}\n\nexport interface PrismaOptions {\n /**\n * Configuration for the Prisma tracing helper.\n */\n instrumentationConfig?: PrismaInstrumentationConfig;\n}\n\n/**\n * Sets up the global Prisma tracing helper that Prisma looks up on `globalThis` to emit tracing data.\n *\n * Prisma reads `globalThis.PRISMA_INSTRUMENTATION` (and its versioned variant) to find a \"TracingHelper\"\n * which it uses internally to create spans, so it can produce tracing data without depending on\n * OpenTelemetry. The helper we install here mints spans through Sentry's span APIs. A single helper\n * serves both Prisma v5 (which calls `createEngineSpan`) and v6/v7 (which call `dispatchEngineSpans`),\n * so it doesn't blow up on version mismatches.\n */\nexport function instrumentPrisma(options?: PrismaOptions): void {\n setGlobalTracingHelper(\n new ActiveTracingHelper({\n ignoreSpanTypes: options?.instrumentationConfig?.ignoreSpanTypes ?? [],\n }),\n );\n}\n\nconst _prismaIntegration = ((options?: PrismaOptions) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPrisma(options);\n },\n // Prisma 8 has no tracing helper to install; its ORM terminals are instrumented via orchestrion instead.\n setup(client) {\n invokeOrchestrionInstrumentation(client, prismaModuleNames, instrumentPrismaV8, [\n { ignoreSpanTypes: options?.instrumentationConfig?.ignoreSpanTypes ?? [] },\n ]);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the [prisma](https://www.npmjs.com/package/prisma) library.\n * For more information, see the [`prismaIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/).\n *\n * NOTE: This integration works out of the box with Prisma v6, v7 and v8. Prisma v8 (\"Prisma Next\")\n * has no tracing surface of its own, so its ORM calls are instrumented through Sentry's runtime hook\n * or bundler plugin, like the other channel-based integrations.\n * On Prisma versions prior to v6, add `previewFeatures = [\"tracing\"]` to the client generator block of your Prisma schema:\n *\n * ```\n * generator client {\n * provider = \"prisma-client-js\"\n * previewFeatures = [\"tracing\"]\n * }\n * ```\n */\nexport const prismaIntegration = defineIntegration(_prismaIntegration);\n","import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n","/* eslint-disable max-lines */\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport {\n continueTrace,\n defineIntegration,\n getClient,\n getTraceData,\n hasSpanStreamingEnabled,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_ID,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FULL,\n SENTRY_ORIGIN,\n MESSAGING_MESSAGE_CONVERSATION_ID,\n MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { amqplibModuleNames } from '../orchestrion/config/amqplib';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Amqplib' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Amqplib' as const;\n\nconst PUBLISHER_ORIGIN = 'auto.queue.amqplib.publisher';\nconst CONSUMER_ORIGIN = 'auto.queue.amqplib.consumer';\n\nconst MESSAGING_OPERATION_VALUE_PROCESS = 'process';\nconst MESSAGING_OPERATION_VALUE_SEND = 'send';\n\n// To prevent reference leaks from un-acked messages, their spans are closed after this timeout. The\n// upstream instrumentation exposed this as the `consumeTimeoutMs` option; the SDK always used the default.\nconst CONSUME_TIMEOUT_MS = 1000 * 60; // 1 minute\n\n// The end-operation labels used in the consumer span's error status message.\nconst END_OP = {\n Ack: 'ack',\n AckAll: 'ackAll',\n Reject: 'reject',\n Nack: 'nack',\n NackAll: 'nackAll',\n ChannelClosed: 'channel closed',\n ChannelError: 'channel error',\n InstrumentationTimeout: 'instrumentation timeout',\n} as const;\ntype EndOp = (typeof END_OP)[keyof typeof END_OP];\n\n// State stashed on the live amqplib objects (mirrors the vendored OTel instrumentation's symbols).\nconst MESSAGE_STORED_SPAN: unique symbol = Symbol('sentry.amqplib.message.stored-span');\nconst CHANNEL_SPANS_NOT_ENDED: unique symbol = Symbol('sentry.amqplib.channel.spans-not-ended');\nconst CHANNEL_CONSUME_TIMEOUT_TIMER: unique symbol = Symbol('sentry.amqplib.channel.consume-timeout-timer');\nconst CHANNEL_CONSUMER_INFO: unique symbol = Symbol('sentry.amqplib.channel.consumer-info');\nconst CHANNEL_PENDING_CONSUMERS: unique symbol = Symbol('sentry.amqplib.channel.pending-consumers');\nconst CHANNEL_IS_CONFIRM_PUBLISHING: unique symbol = Symbol('sentry.amqplib.channel.is-confirm-publishing');\nconst CONNECTION_ATTRIBUTES: unique symbol = Symbol('sentry.amqplib.connection.attributes');\n\ninterface MessageFields {\n deliveryTag?: number;\n exchange?: string;\n routingKey?: string;\n consumerTag?: string;\n}\n\ninterface MessageProperties {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConsumeMessage {\n fields?: MessageFields;\n properties?: MessageProperties;\n [MESSAGE_STORED_SPAN]?: Span;\n}\n\ninterface PublishOptions {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConnectionLike {\n serverProperties?: { product?: string };\n // Some amqplib versions nest the low-level connection one level deeper.\n connection?: { serverProperties?: { product?: string } };\n [CONNECTION_ATTRIBUTES]?: SpanAttributes;\n}\n\ninterface ConsumerInfo {\n noAck: boolean;\n queue: string;\n}\n\n/** A `consume` call waiting for the broker to assign it a consumer tag. */\ninterface PendingConsumer {\n callback: unknown;\n info: ConsumerInfo;\n}\n\ninterface ChannelLike {\n connection?: ConnectionLike;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n [CHANNEL_SPANS_NOT_ENDED]?: { msg: ConsumeMessage; timeOfConsume: number }[];\n [CHANNEL_CONSUME_TIMEOUT_TIMER]?: ReturnType<typeof setInterval>;\n [CHANNEL_CONSUMER_INFO]?: Map<string, ConsumerInfo>;\n [CHANNEL_PENDING_CONSUMERS]?: PendingConsumer[];\n [CHANNEL_IS_CONFIRM_PUBLISHING]?: boolean;\n}\n\ninterface AmqpChannelContext extends OrchestrionChannelContext {\n self?: ChannelLike;\n}\n\ninterface AmqpDispatchContext extends AmqpChannelContext {\n // Whether the delivering consumer registered with `noAck`; set at span creation so `deferSpanEnd`\n // knows whether the helper should end the span (noAck) or leave it open until ack/nack (manual ack).\n _sentryNoAck?: boolean;\n}\n\ninterface AmqpConsumeContext extends AmqpChannelContext {\n // The entry this call queued, so the error hook can drop it.\n _sentryPendingConsumer?: PendingConsumer;\n}\n\nconst NOOP = (): void => {};\n\nconst _amqplibIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, amqplibModuleNames, instrumentAmqplib, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentAmqplib(): void {\n subscribeConnect();\n subscribePublish();\n subscribeConfirmPublish();\n subscribeConsume();\n subscribeRegisterConsumer();\n subscribeDispatch();\n subscribeSettle();\n}\n\n/**\n * Producer span for `Channel.prototype.publish`. Creates a PRODUCER span, injects the trace headers\n * into the publish options, and ends when the (synchronous) publish call returns. Skips the confirm\n * channel's internal `super.publish` call, which is already handled by {@link subscribeConfirmPublish}.\n */\nfunction subscribePublish(): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_PUBLISH), data => {\n if (data.self?.[CHANNEL_IS_CONFIRM_PUBLISHING]) {\n return undefined;\n }\n return startPublishSpan(data);\n });\n}\n\n/**\n * Producer span for `ConfirmChannel.prototype.publish`. The span ends on the broker-confirm callback\n * (the channel's trailing `cb` arg, wrapped by orchestrion) rather than synchronously. A synchronous\n * flag on the channel suppresses the base `publish` channel that `super.publish` triggers.\n */\nfunction subscribeConfirmPublish(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_CONFIRM_PUBLISH);\n\n bindTracingChannelToSpan(channel, data => {\n if (data.self) {\n data.self[CHANNEL_IS_CONFIRM_PUBLISHING] = true;\n }\n return startPublishSpan(data);\n });\n\n // `super.publish` runs synchronously inside the confirm publish body, so clearing the flag on the\n // synchronous `end` (which fires after the body returns) is enough to guard the base publish.\n channel.end.subscribe(message => {\n const self = (message as AmqpChannelContext).self;\n if (self) {\n self[CHANNEL_IS_CONFIRM_PUBLISHING] = false;\n }\n });\n}\n\n/** Stashes the `{ noAck, queue }` each `consume` asks for until the broker assigns it a tag. */\nfunction subscribeConsume(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpConsumeContext>(CHANNELS.AMQPLIB_CONSUME);\n\n channel.start.subscribe(message => {\n const data = message as AmqpConsumeContext;\n const consumerChannel = data.self;\n if (!consumerChannel) {\n return;\n }\n\n ensureChannelState(consumerChannel);\n const queueArg = data.arguments[0];\n const queue = typeof queueArg === 'string' ? queueArg : '<unknown>';\n const callback = data.arguments[1];\n const options = data.arguments[2] as { noAck?: boolean } | undefined;\n const entry = { callback, info: { noAck: !!options?.noAck, queue } };\n consumerChannel[CHANNEL_PENDING_CONSUMERS]?.push(entry);\n data._sentryPendingConsumer = entry;\n });\n\n // A synchronous throw, such as for invalid `arguments`, leaves the channel open. RPC failures close it.\n // A stale entry would label the next consumer that shares this callback.\n channel.error.subscribe(message => {\n const data = message as AmqpConsumeContext;\n if (data.self && data._sentryPendingConsumer) {\n removePendingConsumer(data.self, data._sentryPendingConsumer);\n }\n });\n}\n\n/**\n * Records `consumerTag -> { noAck, queue }` for the dispatch hook. `consume`'s promise resolves too late,\n * because amqplib can decode `BasicConsumeOk` and the first delivery in one socket read. amqplib always\n * registers a consumer before it dispatches to it.\n */\nfunction subscribeRegisterConsumer(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REGISTER_CONSUMER);\n\n channel.start.subscribe(message => {\n const data = message as AmqpChannelContext;\n const consumerChannel = data.self;\n const consumerTag = data.arguments[0];\n const callback = data.arguments[1];\n if (!consumerChannel || typeof consumerTag !== 'string') {\n return;\n }\n\n const entry = consumerChannel[CHANNEL_PENDING_CONSUMERS]?.find(pending => pending.callback === callback);\n if (!entry) {\n return;\n }\n\n removePendingConsumer(consumerChannel, entry);\n consumerChannel[CHANNEL_CONSUMER_INFO]?.set(consumerTag, entry.info);\n });\n}\n\nfunction removePendingConsumer(channel: ChannelLike, entry: PendingConsumer): void {\n channel[CHANNEL_PENDING_CONSUMERS] = channel[CHANNEL_PENDING_CONSUMERS]?.filter(pending => pending !== entry);\n}\n\n/**\n * Per delivered message (`BaseChannel.prototype.dispatchMessage`): continues the producer's trace,\n * opens a CONSUMER span, and runs the user callback under it. Manual-ack consumers keep the span open\n * until `ack`/`nack`/`reject`/timeout/close; `noAck` consumers end it when dispatch returns.\n */\nfunction subscribeDispatch(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AmqpDispatchContext>(CHANNELS.AMQPLIB_DISPATCH),\n data => {\n const channel = data.self;\n const fields = data.arguments[0] as MessageFields | undefined;\n const msg = data.arguments[1] as ConsumeMessage | null | undefined;\n // `message` is null for a consumer-cancel notification: not a real message, so no span.\n if (!channel || !msg) {\n return undefined;\n }\n\n ensureChannelState(channel);\n const info = fields?.consumerTag ? channel[CHANNEL_CONSUMER_INFO]?.get(fields.consumerTag) : undefined;\n const queue = info?.queue ?? msg.fields?.routingKey;\n const noAck = info?.noAck ?? false;\n\n const headers = msg.properties?.headers;\n const sentryTrace = getHeaderAsString(headers, 'sentry-trace');\n const baggage = getHeaderAsString(headers, 'baggage');\n\n // Continue the producer's trace so the consumer span links back to the publishing service.\n const span = continueTrace({ sentryTrace, baggage }, () => startConsumeSpan(queue, msg, channel));\n\n if (!noAck) {\n // Track the message so its span can be ended when the user calls ack/nack/reject (or on\n // timeout/channel close).\n channel[CHANNEL_SPANS_NOT_ENDED]?.push({ msg, timeOfConsume: timestampInSeconds() });\n msg[MESSAGE_STORED_SPAN] = span;\n }\n\n data._sentryNoAck = noAck;\n return span;\n },\n {\n // Manual-ack consumers: the span outlives the dispatch call and is ended by ack/nack/reject\n // (or timeout/close), so take ownership and don't let the helper end it here. noAck consumers\n // have no settle call, so let the helper end the span when dispatch returns.\n deferSpanEnd({ data }) {\n return !data._sentryNoAck;\n },\n },\n );\n}\n\n/** Ends consumer spans when the user acks/nacks/rejects a message or the channel closes/errors. */\nfunction subscribeSettle(): void {\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, false, END_OP.Ack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Nack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REJECT)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Reject));\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, false, END_OP.AckAll, undefined);\n }\n });\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, true, END_OP.NackAll, data.arguments[0] as boolean | undefined);\n }\n });\n}\n\n/** Captures connection attributes on the connection object for span-time reads via `channel.connection`. */\nfunction subscribeConnect(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.AMQPLIB_CONNECT);\n // A `start` subscriber is required for orchestrion to wrap the callback-style `connect` at all.\n channel.start.subscribe(NOOP);\n channel.asyncEnd.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const conn = data.result as ConnectionLike | undefined;\n if (!conn || typeof conn !== 'object') {\n return;\n }\n conn[CONNECTION_ATTRIBUTES] = {\n ...getConnectionAttributesFromUrl(data.arguments?.[0]),\n ...getConnectionAttributesFromServer(conn),\n };\n });\n}\n\nfunction handleAck(data: AmqpChannelContext, isRejected: boolean, endOperation: EndOp): void {\n const channel = data.self;\n if (!channel) {\n return;\n }\n const message = data.arguments[0] as ConsumeMessage | undefined;\n if (!message) {\n return;\n }\n\n // `reject(message, requeue)` carries requeue in arg 1; `ack`/`nack` carry `allUpTo` in arg 1.\n const allUpToOrRequeue = data.arguments[1] as boolean | undefined;\n const requeue = data.arguments[2] as boolean | undefined;\n const requeueResolved = endOperation === END_OP.Reject ? allUpToOrRequeue : requeue;\n\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n const msgIndex = spansNotEnded.findIndex(msgDetails => msgDetails.msg === message);\n if (msgIndex < 0) {\n // Not tracked (e.g. the user acked the same message twice) — end the stored span directly.\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n } else if (endOperation !== END_OP.Reject && allUpToOrRequeue) {\n for (let i = 0; i <= msgIndex; i++) {\n endConsumerSpan(spansNotEnded[i]!.msg, isRejected, endOperation, requeueResolved);\n }\n spansNotEnded.splice(0, msgIndex + 1);\n } else {\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n spansNotEnded.splice(msgIndex, 1);\n }\n}\n\nfunction ensureChannelState(channel: ChannelLike): void {\n if (Object.prototype.hasOwnProperty.call(channel, CHANNEL_SPANS_NOT_ENDED)) {\n return;\n }\n\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n channel[CHANNEL_CONSUMER_INFO] = new Map();\n channel[CHANNEL_PENDING_CONSUMERS] = [];\n\n const timer = setInterval(() => checkConsumeTimeoutOnChannel(channel), CONSUME_TIMEOUT_MS);\n timer.unref?.();\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = timer;\n\n // End outstanding spans and stop the timer when the channel goes away (replaces patching `emit`).\n // amqplib emits 'close' after 'error', but we clear in both to avoid leaking the interval (which\n // pins the channel via its closure) should a version or edge case ever skip the trailing 'close'.\n if (typeof channel.on === 'function') {\n channel.on('close', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelClosed, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n channel.on('error', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelError, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n }\n}\n\n/** Stops and clears the per-channel consume-timeout interval. Idempotent. */\nfunction clearConsumeTimeoutTimer(channel: ChannelLike): void {\n const activeTimer = channel[CHANNEL_CONSUME_TIMEOUT_TIMER];\n if (activeTimer) {\n clearInterval(activeTimer);\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = undefined;\n }\n}\n\nfunction checkConsumeTimeoutOnChannel(channel: ChannelLike): void {\n const currentTime = timestampInSeconds();\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n let i: number;\n for (i = 0; i < spansNotEnded.length; i++) {\n const currMessage = spansNotEnded[i]!;\n const timeFromConsumeMs = (currentTime - currMessage.timeOfConsume) * 1000;\n if (timeFromConsumeMs < CONSUME_TIMEOUT_MS) {\n break;\n }\n endConsumerSpan(currMessage.msg, null, END_OP.InstrumentationTimeout, true);\n }\n spansNotEnded.splice(0, i);\n}\n\nfunction endAllSpansOnChannel(\n channel: ChannelLike,\n isRejected: boolean,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n spansNotEnded.forEach(msgDetails => {\n endConsumerSpan(msgDetails.msg, isRejected, operation, requeue);\n });\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n}\n\nfunction endConsumerSpan(\n message: ConsumeMessage,\n isRejected: boolean | null,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const storedSpan = message[MESSAGE_STORED_SPAN];\n if (!storedSpan) {\n return;\n }\n if (isRejected !== false) {\n storedSpan.setStatus({\n code: SPAN_STATUS_ERROR,\n message:\n operation !== END_OP.ChannelClosed && operation !== END_OP.ChannelError\n ? `${operation} called on message${\n requeue === true ? ' with requeue' : requeue === false ? ' without requeue' : ''\n }`\n : operation,\n });\n }\n storedSpan.end();\n message[MESSAGE_STORED_SPAN] = undefined;\n}\n\n/** Starts an inactive PRODUCER span and propagates its trace into the publish `options.headers`. */\nfunction startPublishSpan(data: AmqpChannelContext): Span {\n const exchangeArg = data.arguments[0];\n const routingKeyArg = data.arguments[1];\n const exchange = typeof exchangeArg === 'string' ? exchangeArg : '';\n const routingKey = typeof routingKeyArg === 'string' ? routingKeyArg : '';\n let options = data.arguments[3] as PublishOptions | undefined;\n\n const client = getClient();\n const destination = resolveDestination(exchange, routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_SEND} ${destination}`\n : MESSAGING_OPERATION_VALUE_SEND;\n\n const span = startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? streamedName : `publish ${normalizeExchange(exchange)}`,\n attributes: {\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_KIND]: 'producer',\n ...getStoredConnectionAttributes(data.self),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_MESSAGE_ID]: options?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: options?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: PUBLISHER_ORIGIN,\n },\n });\n\n if (!options || typeof options !== 'object') {\n options = {};\n data.arguments[3] = options;\n }\n const headers = options.headers && typeof options.headers === 'object' ? options.headers : (options.headers = {});\n const traceData = getTraceData({ span });\n if (traceData['sentry-trace']) {\n headers['sentry-trace'] = traceData['sentry-trace'];\n }\n if (traceData.baggage) {\n headers['baggage'] = traceData.baggage;\n }\n\n return span;\n}\n\n/** Starts an inactive CONSUMER (process) span carrying the amqplib messaging attributes. */\nfunction startConsumeSpan(queue: string | undefined, msg: ConsumeMessage, channel: ChannelLike): Span {\n const client = getClient();\n const destination = resolveDestination(msg.fields?.exchange, msg.fields?.routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_PROCESS} ${destination}`\n : MESSAGING_OPERATION_VALUE_PROCESS;\n\n return startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? streamedName\n : queue\n ? `${queue} ${MESSAGING_OPERATION_VALUE_PROCESS}`\n : MESSAGING_OPERATION_VALUE_PROCESS,\n attributes: {\n [SENTRY_OP]: QUEUE_PROCESS,\n [SENTRY_KIND]: 'consumer',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'component',\n ...getStoredConnectionAttributes(channel),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: msg.fields?.routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_MESSAGE_ID]: msg.properties?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: msg.properties?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: CONSUMER_ORIGIN,\n },\n });\n}\n\n/**\n * Reads the connection attributes stashed by the `connect` channel, falling back to the live\n * connection's server product so `messaging.system` is populated even when the connection was\n * established before the integration ran.\n */\nfunction getStoredConnectionAttributes(channel: ChannelLike | undefined): SpanAttributes {\n const connection = channel?.connection;\n const stored = connection?.[CONNECTION_ATTRIBUTES];\n if (stored) {\n return stored;\n }\n const product = connection?.serverProperties?.product ?? connection?.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromServer(conn: ConnectionLike): SpanAttributes {\n const product = conn.serverProperties?.product ?? conn.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromUrl(url: unknown): SpanAttributes {\n const attributes: SpanAttributes = {\n // The only protocol supported by the instrumented library.\n [NETWORK_PROTOCOL_VERSION]: '0.9.1',\n };\n\n const resolvedUrl = url || 'amqp://localhost';\n if (typeof resolvedUrl === 'object') {\n const connectOptions = resolvedUrl as { protocol?: string; hostname?: string; port?: number };\n const protocol = getProtocol(connectOptions.protocol);\n const hostname = getHostname(connectOptions.hostname);\n const port = getPort(connectOptions.port, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } else if (typeof resolvedUrl === 'string') {\n const censoredUrl = censorPassword(resolvedUrl);\n // oxlint-disable-next-line sdk/no-unfiltered-url-attributes -- AMQP connection URL, not an HTTP request URL\n attributes[URL_FULL] = censoredUrl;\n\n try {\n const urlParts = new URL(censoredUrl);\n const protocol = getProtocol(urlParts.protocol);\n const hostname = getHostname(urlParts.hostname);\n const port = getPort(urlParts.port ? parseInt(urlParts.port, 10) : undefined, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } catch {\n // best-effort: a malformed url simply yields fewer connection attributes\n }\n }\n return attributes;\n}\n\n/**\n * The default exchange has no name and binds every queue under a key equal to the queue's own name, so\n * a routing key used with it is the queue name. On a named exchange the routing key is per-message\n * (`order.created.12345`), so only the exchange is used.\n *\n * @see https://www.rabbitmq.com/docs/exchanges#default-exchange\n * @internal Exported for tests; every scenario publishes through `sendToQueue`.\n */\nexport function resolveDestination(exchange: string | undefined, routingKey: string | undefined): string | undefined {\n // `undefined` so an absent destination is omitted rather than reported as an empty string.\n return exchange || routingKey || undefined;\n}\n\nfunction normalizeExchange(exchangeName: string): string {\n return exchangeName !== '' ? exchangeName : '<default>';\n}\n\nfunction censorPassword(url: string): string {\n return url.replace(/:[^:@/]*@/, ':***@');\n}\n\nfunction getPort(portFromUrl: number | undefined, resolvedProtocol: string): number {\n // Mimics amqplib's own defaulting; the resolved protocol is upper-cased.\n return portFromUrl || (resolvedProtocol === 'AMQP' ? 5672 : 5671);\n}\n\nfunction getProtocol(protocolFromUrl: string | undefined): string {\n const resolvedProtocol = protocolFromUrl || 'amqp';\n const noEndingColon = resolvedProtocol.endsWith(':')\n ? resolvedProtocol.substring(0, resolvedProtocol.length - 1)\n : resolvedProtocol;\n return noEndingColon.toUpperCase();\n}\n\nfunction getHostname(hostnameFromUrl: string | undefined): string {\n // An empty hostname is forwarded to `net`, which defaults it to localhost.\n return hostnameFromUrl || 'localhost';\n}\n\nfunction getHeaderAsString(headers: Record<string, unknown> | undefined, key: string): string | undefined {\n const value = headers?.[key];\n if (value == null) {\n return undefined;\n }\n return Array.isArray(value) ? String(value[0]) : String(value);\n}\n\n/**\n * Diagnostics-channel-based `amqplib` integration.\n *\n * Subscribes to the `orchestrion:amqplib:*` diagnostics_channels that Sentry's code transform\n * injects into `amqplib`'s channel/connection methods. Requires the Sentry runtime hook or\n * bundler plugin to be active.\n */\nexport const amqplibIntegration = defineIntegration(_amqplibIntegration);\n","import { isObjectLike } from '@sentry/core';\n\ninterface ApiPromise {\n parseResponse: (...args: unknown[]) => unknown;\n asResponse: () => Promise<Response>;\n _thenUnwrap?: (...args: unknown[]) => ApiPromise;\n}\n\nfunction isApiPromise(value: unknown): value is ApiPromise {\n return isObjectLike(value) && typeof value.parseResponse === 'function' && typeof value.asResponse === 'function';\n}\n\n// OpenAI and Anthropic return an APIPromise that extends the native promise objects and redefines .then() in a way that internally triggers body parsing.\n// This can lead to double parsing if our instrumentation triggers .then on this promise.\n// Instead, we need to avoid triggering .then on the APIPromise and instead observe the internal parsing process to get the response body.\n// OpenAI APIPromise: https://github.com/openai/openai-node/blob/71d24120c4cc4e5897a767f16d25f2804fa4ad7c/src/core/api-promise.ts\n// Anthropic APIPromise: https://github.com/anthropics/anthropic-sdk-typescript/blob/d49bdab458000bcdffe77bd84b03293f31824fb3/src/core/api-promise.ts\nexport function wrapApiPromiseResponse(\n result: unknown,\n onResponse: (response: unknown) => void,\n onError: (error: unknown) => void,\n): boolean {\n // e.g. Anthropic's messages.stream() returns an emitter instead of an APIPromise\n if (!isApiPromise(result)) {\n return false;\n }\n\n let parsing = false;\n\n // observe internal parsing method on the APIPromise to read the response body\n result.parseResponse = new Proxy(result.parseResponse, {\n async apply(original, thisArg, args): Promise<unknown> {\n parsing = true;\n try {\n const response = await Reflect.apply(original, thisArg, args);\n onResponse(response);\n return response;\n } catch (error) {\n onError(error);\n throw error;\n }\n },\n });\n\n // end the span in case of request failures before the internal parsing process is triggered\n void result.asResponse().then(undefined, onError);\n\n // asResponse() calls .then() on the native response promise, not on APIPromise so parseResponse never runs\n // therefore we need to handle this path separately\n function wrapRawResponse(apiPromise: ApiPromise): void {\n apiPromise.asResponse = new Proxy(apiPromise.asResponse, {\n apply(original, thisArg, args): Promise<Response> {\n return (Reflect.apply(original, thisArg, args) as Promise<Response>).then(response => {\n if (!parsing) {\n onResponse(undefined);\n }\n return response;\n });\n },\n });\n\n // thenUnwrap internally creates a new APIPromise\n // asResponse() on the derived promise would still be uninstrumented, so we need to recursively wrap the derived promises\n // thenUnwrap is for instance internally used by chat.completions.parse() / responses.parse()\n // so this would cover for instance responses.parse().asResponse() calls\n const thenUnwrap = apiPromise._thenUnwrap;\n if (thenUnwrap) {\n // parse(...).asResponse()\n apiPromise._thenUnwrap = new Proxy(thenUnwrap, {\n apply(original, thisArg, args): ApiPromise {\n const derivedPromise = Reflect.apply(original, thisArg, args);\n wrapRawResponse(derivedPromise);\n return derivedPromise;\n },\n });\n }\n }\n\n wrapRawResponse(result);\n\n return true;\n}\n","import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(\n span,\n data.result as AnthropicAiResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n );\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end, options) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream, options)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream, options),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(\n span: Span,\n data: OrchestrionChannelContext,\n end: (error?: unknown) => void,\n options: AnthropicAiOptions,\n): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n stream: StreamMode,\n options: AnthropicAiOptions,\n): boolean {\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs);\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]));\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n","/**\n * AWS-specific span constants used by the aws-sdk channel integration that are NOT covered by\n * `@sentry/conventions/attributes` (attribute names that exist there are imported from there\n * directly). These are either Sentry-specific (the span origin) or attribute *values* (not keys).\n */\n\n/** The integration name part of every aws-sdk channel span origin (`auto.<category>.aws_sdk`). */\nexport const AWS_SDK_ORIGIN_INTEGRATION_NAME = 'aws_sdk';\n\n/** DynamoDB `db.system.name` value (an attribute value, not a key, so not covered by conventions). */\nexport const DB_SYSTEM_VALUE_DYNAMODB = 'dynamodb';\n\n/** SNS `messaging.destination_kind` value (an attribute value, not a key, so not covered by conventions). */\nexport const MESSAGING_DESTINATION_KIND_VALUE_TOPIC = 'topic';\n\n// Bedrock (gen_ai) attribute values (not keys, so not covered by conventions)\nexport const GEN_AI_OPERATION_NAME_VALUE_CHAT = 'chat';\nexport const GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT = 'generate_content';\nexport const GEN_AI_SYSTEM_VALUE_AWS_BEDROCK = 'aws.bedrock';\n","import type { Span } from '@sentry/core';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n} from '@sentry/conventions/attributes';\nimport { getMessagesAttributes, messagesFromParams } from '../../../ai/anthropic-ai/utils';\nimport type { GenAiMessagePart } from '../../../ai/types';\n\n/**\n * Translate Converse `ContentBlock`s (also used by Amazon Nova `InvokeModel` bodies) and the Anthropic Messages\n * blocks of Claude `InvokeModel` responses into message parts.\n * The conventions require a `type` on each part, and Bedrock's blocks (`{ text }`, `{ toolUse }`, ...) have none.\n *\n * Media is reported by modality only: inline media is raw bytes, which would serialize as a large array of\n * numbers. Blocks without content worth recording (`cachePoint`, redacted\n * reasoning, unknown members) are left out rather than serialized, so no binary payload slips through.\n */\nexport function contentBlocksToParts(content: unknown): GenAiMessagePart[] {\n return Array.isArray(content) ? content.flatMap(contentBlockToParts) : [];\n}\n\nfunction contentBlockToParts(block: unknown): GenAiMessagePart[] {\n if (!isObjectLike(block)) {\n return [];\n }\n\n if (typeof block.text === 'string') {\n return [{ type: 'text', content: block.text }];\n }\n\n if (typeof block.thinking === 'string') {\n return [{ type: 'reasoning', content: block.thinking }];\n }\n\n const {\n toolUse = block.type === 'tool_use' ? block : undefined,\n toolResult,\n reasoningContent,\n guardContent,\n citationsContent,\n } = block;\n\n if (isObjectLike(toolUse)) {\n return [\n {\n type: 'tool_call',\n id: toolUse.toolUseId ?? toolUse.id,\n name: toolUse.name,\n arguments: stringify(toolUse.input ?? {}, String),\n },\n ];\n }\n\n if (isObjectLike(toolResult)) {\n return [{ type: 'tool_call_response', id: toolResult.toolUseId, result: toolResultToString(toolResult.content) }];\n }\n\n if (isObjectLike(reasoningContent)) {\n const reasoningText = reasoningContent.reasoningText;\n return isObjectLike(reasoningText) && typeof reasoningText.text === 'string'\n ? [{ type: 'reasoning', content: reasoningText.text }]\n : [];\n }\n\n if (isObjectLike(guardContent)) {\n // `guardContent.text` is a `{ text }` block, `guardContent.image` an image block.\n return contentBlockToParts(isObjectLike(guardContent.text) ? guardContent.text : guardContent);\n }\n\n if (isObjectLike(citationsContent)) {\n return contentBlocksToParts(citationsContent.content);\n }\n\n for (const modality of ['image', 'video', 'audio', 'document']) {\n const media = block[modality];\n if (isObjectLike(media)) {\n // Only image formats (`png`, ...) map to a MIME type by prefix; `undefined` is left out of the JSON.\n const format = modality === 'image' && typeof media.format === 'string' ? `image/${media.format}` : undefined;\n return [{ type: 'blob', modality, mime_type: format }];\n }\n }\n\n return [];\n}\n\nfunction toolResultToString(content: unknown): string {\n if (!Array.isArray(content)) {\n return '';\n }\n\n return content\n .map(block => {\n if (!isObjectLike(block)) {\n return undefined;\n }\n if (typeof block.text === 'string') {\n return block.text;\n }\n return block.json !== undefined ? stringify(block.json, String) : undefined;\n })\n .filter((text): text is string => text !== undefined)\n .join('\\n');\n}\n\nfunction converseMessagesToMessages(messages: unknown): Array<{ role: string; parts: GenAiMessagePart[] }> {\n if (!Array.isArray(messages)) {\n return [];\n }\n\n return messages\n .filter(isObjectLike)\n .map(message => ({\n role: typeof message.role === 'string' ? message.role : 'user',\n parts: contentBlocksToParts(message.content),\n }))\n .filter(message => message.parts.length > 0);\n}\n\n/**\n * Input attributes of a Converse-shaped request (`Converse`, `ConverseStream`, and Amazon Nova\n * `InvokeModel` bodies, which use the same `messages`/`system`/`toolConfig` shape).\n */\nexport function getConverseInputAttributes(input: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n\n const systemInstructions = contentBlocksToParts(input.system);\n if (systemInstructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = JSON.stringify(systemInstructions);\n }\n\n const messages = converseMessagesToMessages(input.messages);\n if (messages.length) {\n attributes[GEN_AI_INPUT_MESSAGES] = JSON.stringify(messages);\n }\n\n const toolConfig = input.toolConfig;\n if (isObjectLike(toolConfig) && Array.isArray(toolConfig.tools)) {\n // `cachePoint` entries share the list with the `toolSpec`s; they are not tools.\n const toolSpecs = toolConfig.tools\n .map(tool => (isObjectLike(tool) ? tool.toolSpec : undefined))\n .filter(isObjectLike);\n if (toolSpecs.length) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(toolSpecs);\n }\n }\n\n return attributes;\n}\n\n/**\n * Claude `InvokeModel` bodies are Anthropic Messages API requests, so they are recorded like the Anthropic\n * integration records them.\n */\nexport function getClaudeInputAttributes(body: Record<string, unknown>): Record<string, unknown> {\n const attributes = getMessagesAttributes(messagesFromParams(body));\n if (Array.isArray(body.tools)) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(body.tools);\n }\n return attributes;\n}\n\n/** Input attributes of the single-prompt `InvokeModel` bodies (Titan, Llama, Cohere, Mistral, ...). */\nexport function getPromptInputAttributes(prompt: unknown): Record<string, unknown> {\n if (typeof prompt !== 'string') {\n return {};\n }\n return { [GEN_AI_INPUT_MESSAGES]: JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: prompt }] }]) };\n}\n\n/** Record the parts as one assistant message. Parts of a stream are kept at their block index, so skip the gaps. */\nexport function setOutputMessages(span: Span, parts: GenAiMessagePart[]): void {\n const filledParts = parts.filter(Boolean);\n if (filledParts.length) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, JSON.stringify([{ role: 'assistant', parts: filledParts }]));\n }\n}\n\n/** Append a streamed fragment to the part at the block `index`, and open a `type` part there if there is none. */\nexport function appendStreamPart(\n parts: GenAiMessagePart[] | undefined,\n index: unknown,\n type: 'text' | 'reasoning' | 'tool_call',\n fragment: unknown,\n): void {\n if (!parts || typeof fragment !== 'string') {\n return;\n }\n // Tool call arguments stream in as fragments of their JSON.\n const field = type === 'tool_call' ? 'arguments' : 'content';\n const part = (parts[typeof index === 'number' ? index : 0] ??= { type, [field]: '' });\n part[field] = `${part[field]}${fragment}`;\n}\n\nexport function startStreamToolCall(\n parts: GenAiMessagePart[] | undefined,\n index: unknown,\n id: unknown,\n name: unknown,\n): void {\n if (parts) {\n parts[typeof index === 'number' ? index : 0] = { type: 'tool_call', id, name, arguments: '' };\n }\n}\n","import type { Span } from '@sentry/core';\nimport { debug } from '@sentry/core';\nimport {\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_STOP_SEQUENCES as ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op';\nimport type { GenAiOptions, StreamResponseState } from '../../../ai/core/utils';\nimport type { GenAiMessagePart } from '../../../ai/types';\nimport {\n endStreamSpan,\n getErrorStatus,\n getTokenUsageAttributes,\n resolveAIRecordingOptions,\n} from '../../../ai/core/utils';\nimport { isInsidePiAiSpan } from '../../../ai/pi-ai/providers';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport {\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n} from '../constants';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport {\n appendStreamPart,\n contentBlocksToParts,\n getClaudeInputAttributes,\n getConverseInputAttributes,\n getPromptInputAttributes,\n setOutputMessages,\n startStreamToolCall,\n} from './bedrock-runtime-content';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\n// Simplified types inlined from @aws-sdk/client-bedrock-runtime\n// Only the fields accessed by this instrumentation are included\ninterface TokenUsage {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n}\n\ninterface ConverseStreamOutput {\n messageStop?: { stopReason?: string };\n metadata?: { usage?: TokenUsage };\n [key: string]: unknown;\n}\n\n// Streamed `InvokeModel` chunks and response bodies are model-family-specific JSON (titan, nova,\n// claude, llama, cohere, mistral); the record helpers probe the shapes defensively, so `any` instead\n// of one structural type per family.\ntype ParsedChunk = any;\n\n/** The output parts are only collected when outputs are recorded. */\ntype BedrockStreamState = StreamResponseState & { parts?: GenAiMessagePart[] };\n\nconst textDecoder = new TextDecoder();\n\nexport class BedrockRuntimeServiceExtension implements ServiceExtension {\n // Requests pi-ai sends, which its own `gen_ai.chat` span already reports. They keep the plain AWS\n // client span, without the model call on it.\n private _piAiRequests: WeakSet<NormalizedRequest> = new WeakSet();\n\n public constructor(private readonly _options: GenAiOptions = {}) {}\n\n private _recordingOptions(): Required<GenAiOptions> {\n return resolveAIRecordingOptions(this._options);\n }\n\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n if (isInsidePiAiSpan()) {\n this._piAiRequests.add(request);\n return {};\n }\n\n switch (request.commandName) {\n case 'Converse':\n return this._requestPreSpanHookConverse(request, false);\n case 'ConverseStream':\n return this._requestPreSpanHookConverse(request, true);\n case 'InvokeModel':\n return this._requestPreSpanHookInvokeModel(request, false);\n case 'InvokeModelWithResponseStream':\n return this._requestPreSpanHookInvokeModel(request, true);\n }\n\n return {};\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n if (this._piAiRequests.has(response.request)) {\n return;\n }\n\n const commandName = response.request.commandName;\n\n if (!span.isRecording()) {\n // Streaming spans are ended by the wrapped stream (the subscriber's `deferSpanEnd` suppresses\n // the helper's own `end()`). When the span isn't recording we skip wrapping, so end it here to\n // avoid leaking an open span. Non-streaming commands are ended by the helper, so leave them.\n if (commandName === 'ConverseStream' || commandName === 'InvokeModelWithResponseStream') {\n span.end();\n }\n return;\n }\n\n switch (commandName) {\n case 'Converse':\n return this._responseHookConverse(response, span);\n case 'ConverseStream':\n return this._responseHookConverseStream(response, span);\n case 'InvokeModel':\n return this._responseHookInvokeModel(response, span);\n case 'InvokeModelWithResponseStream':\n return this._responseHookInvokeModelWithResponseStream(response, span);\n }\n }\n\n private _requestPreSpanHookConverse(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_CHAT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n };\n\n const modelId = request.commandInput.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n if (spanName) {\n spanName += ` ${modelId}`;\n }\n }\n\n const inferenceConfig = request.commandInput.inferenceConfig;\n if (inferenceConfig) {\n const { maxTokens, temperature, topP, stopSequences } = inferenceConfig;\n if (maxTokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = maxTokens;\n }\n if (temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = temperature;\n }\n if (topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = topP;\n }\n if (stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = stopSequences;\n }\n }\n\n if (this._recordingOptions().recordInputs) {\n Object.assign(spanAttributes, getConverseInputAttributes(request.commandInput));\n }\n\n return {\n spanName,\n spanOp: GEN_AI_CHAT,\n isStream,\n spanAttributes,\n };\n }\n\n private _requestPreSpanHookInvokeModel(request: NormalizedRequest, isStream: boolean): RequestMetadata {\n let spanName = GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT;\n const spanAttributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: GEN_AI_SYSTEM_VALUE_AWS_BEDROCK,\n [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n };\n\n const modelId = request.commandInput?.modelId;\n if (modelId) {\n spanAttributes[GEN_AI_REQUEST_MODEL] = modelId;\n spanName += ` ${modelId}`;\n }\n\n const requestBody = parseRequestBody(request.commandInput?.body);\n if (requestBody && typeof modelId === 'string') {\n if (modelId.includes('amazon.titan')) {\n if (requestBody.textGenerationConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.textGenerationConfig.temperature;\n }\n if (requestBody.textGenerationConfig?.topP !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.textGenerationConfig.topP;\n }\n if (requestBody.textGenerationConfig?.maxTokenCount !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.textGenerationConfig.maxTokenCount;\n }\n if (requestBody.textGenerationConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.textGenerationConfig.stopSequences;\n }\n } else if (modelId.includes('amazon.nova')) {\n if (requestBody.inferenceConfig?.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.inferenceConfig.temperature;\n }\n if (requestBody.inferenceConfig?.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.inferenceConfig.top_p;\n }\n if (requestBody.inferenceConfig?.max_new_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.inferenceConfig.max_new_tokens;\n }\n if (requestBody.inferenceConfig?.stopSequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.inferenceConfig.stopSequences;\n }\n } else if (modelId.includes('anthropic.claude')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('meta.llama')) {\n if (requestBody.max_gen_len !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_gen_len;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n // request for meta llama models does not contain stop_sequences field\n } else if (modelId.includes('cohere.command-r')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.message !== undefined) {\n // NOTE: We approximate the token count since this value is not directly available in the body.\n // According to Bedrock docs they use (total_chars / 6) to approximate token count for pricing.\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.message.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('cohere.command')) {\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.p;\n }\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.stop_sequences !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop_sequences;\n }\n } else if (modelId.includes('mistral')) {\n if (requestBody.prompt !== undefined) {\n spanAttributes[GEN_AI_USAGE_INPUT_TOKENS] = Math.ceil(requestBody.prompt.length / 6);\n }\n if (requestBody.max_tokens !== undefined) {\n spanAttributes[GEN_AI_REQUEST_MAX_TOKENS] = requestBody.max_tokens;\n }\n if (requestBody.temperature !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TEMPERATURE] = requestBody.temperature;\n }\n if (requestBody.top_p !== undefined) {\n spanAttributes[GEN_AI_REQUEST_TOP_P] = requestBody.top_p;\n }\n if (requestBody.stop !== undefined) {\n spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop;\n }\n }\n\n if (this._recordingOptions().recordInputs) {\n Object.assign(spanAttributes, getInvokeModelInputAttributes(modelId, requestBody));\n }\n }\n\n return {\n spanName,\n spanOp: GEN_AI_GENERATE_CONTENT,\n isStream,\n spanAttributes,\n };\n }\n\n private _responseHookConverse(response: NormalizedResponse, span: Span): void {\n const { stopReason, usage, output } = response.data;\n\n setStopReason(span, stopReason);\n if (this._recordingOptions().recordOutputs) {\n setOutputMessages(span, contentBlocksToParts(output?.message?.content));\n }\n span.setAttributes(\n getTokenUsageAttributes(\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined,\n usage?.outputTokens,\n usage?.cacheWriteInputTokens,\n usage?.cacheReadInputTokens,\n ),\n );\n }\n\n private _responseHookConverseStream(response: NormalizedResponse, span: Span): void {\n if (!response.data?.stream) {\n span.end();\n return;\n }\n\n // Wrap and replace the response stream in place to process events into telemetry\n // before yielding to the user.\n response.data.stream = instrumentStream(\n response.data.stream as AsyncIterable<ConverseStreamOutput>,\n span,\n response.request.abortSignal,\n this._recordingOptions().recordOutputs,\n processConverseStreamEvent,\n );\n }\n\n private _responseHookInvokeModel(response: NormalizedResponse, span: Span): void {\n const currentModelId = response.request.commandInput?.modelId;\n if (response.data?.body) {\n const decodedResponseBody = textDecoder.decode(response.data.body);\n const responseBody = JSON.parse(decodedResponseBody);\n // Nova; Claude and Llama; Cohere Command R; Titan; Cohere Command; Mistral.\n const finishReason =\n responseBody.stopReason ??\n responseBody.stop_reason ??\n responseBody.finish_reason ??\n responseBody.results?.[0]?.completionReason ??\n responseBody.generations?.[0]?.finish_reason ??\n responseBody.outputs?.[0]?.stop_reason;\n setStopReason(span, finishReason);\n if (currentModelId.includes('amazon.titan')) {\n if (responseBody.inputTextTokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.inputTextTokenCount);\n }\n if (responseBody.results?.[0]?.tokenCount !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.results[0].tokenCount);\n }\n } else if (currentModelId.includes('amazon.nova')) {\n if (responseBody.usage !== undefined) {\n if (responseBody.usage.inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.usage.inputTokens);\n }\n if (responseBody.usage.outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.usage.outputTokens);\n }\n }\n } else if (currentModelId.includes('anthropic.claude')) {\n const usage = responseBody.usage;\n span.setAttributes(\n getTokenUsageAttributes(\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n typeof usage?.input_tokens === 'number'\n ? usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0)\n : undefined,\n usage?.output_tokens,\n usage?.cache_creation_input_tokens,\n usage?.cache_read_input_tokens,\n ),\n );\n } else if (currentModelId.includes('meta.llama')) {\n if (responseBody.prompt_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, responseBody.prompt_token_count);\n }\n if (responseBody.generation_token_count !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, responseBody.generation_token_count);\n }\n } else if (currentModelId.includes('cohere.command-r')) {\n if (responseBody.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.text.length / 6));\n }\n } else if (currentModelId.includes('cohere.command')) {\n if (responseBody.generations?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.generations[0].text.length / 6));\n }\n } else if (currentModelId.includes('mistral')) {\n if (responseBody.outputs?.[0]?.text !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, Math.ceil(responseBody.outputs[0].text.length / 6));\n }\n }\n if (this._recordingOptions().recordOutputs) {\n setOutputMessages(span, getInvokeModelOutputParts(responseBody));\n }\n }\n }\n\n private _responseHookInvokeModelWithResponseStream(response: NormalizedResponse, span: Span): void {\n const stream = response.data?.body;\n const modelId = response.request.commandInput?.modelId;\n if (!stream) {\n span.end();\n return;\n }\n\n // Resolved once: the model family is fixed for the whole stream, and for unrecognized families\n // the chunks don't need to be parsed at all.\n const processChunk = typeof modelId === 'string' ? resolveStreamProcessor(modelId) : undefined;\n\n // Replace the original response body with our instrumented stream, deferring span.end() until the\n // entire stream is consumed. Downstream consumers still receive the full stream.\n response.data.body = instrumentStream(\n stream as AsyncIterable<{ chunk?: { bytes?: Uint8Array } }>,\n span,\n response.request.abortSignal,\n this._recordingOptions().recordOutputs,\n (item, state) => {\n if (processChunk) {\n const parsedChunk = parseChunk(item?.chunk?.bytes);\n if (parsedChunk) {\n appendStreamPart(state.parts, 0, 'text', getResponseText(parsedChunk));\n processChunk(parsedChunk, state);\n }\n }\n },\n );\n }\n}\n\nfunction getInvokeModelOutputParts(responseBody: ParsedChunk): GenAiMessagePart[] {\n // Nova and Claude return content blocks, the other families one text.\n return contentBlocksToParts(\n responseBody.output?.message?.content ?? responseBody.content ?? [{ text: getResponseText(responseBody) }],\n );\n}\n\n/** The text of a Titan, Llama, Cohere Command R, Cohere Command, or Mistral response body or stream chunk. */\nfunction getResponseText(body: ParsedChunk): unknown {\n return (\n body.outputText ??\n body.results?.[0]?.outputText ??\n body.generation ??\n body.text ??\n body.generations?.[0]?.text ??\n body.outputs?.[0]?.text\n );\n}\n\nfunction getInvokeModelInputAttributes(modelId: string, requestBody: ParsedChunk): Record<string, unknown> {\n if (modelId.includes('amazon.nova')) return getConverseInputAttributes(requestBody);\n if (modelId.includes('anthropic.claude')) return getClaudeInputAttributes(requestBody);\n // The other families send one prompt string: Titan as `inputText`, Cohere Command R as `message`.\n return getPromptInputAttributes(requestBody.inputText ?? requestBody.message ?? requestBody.prompt);\n}\n\ntype StreamProcessor = (parsedChunk: ParsedChunk, state: BedrockStreamState) => void;\n\nfunction resolveStreamProcessor(modelId: string): StreamProcessor | undefined {\n if (modelId.includes('amazon.titan')) return processTitanChunk;\n if (modelId.includes('anthropic.claude')) return processClaudeChunk;\n if (modelId.includes('amazon.nova')) return processNovaChunk;\n if (modelId.includes('meta.llama')) return processLlamaChunk;\n if (modelId.includes('cohere.command-r')) return processCohereRChunk;\n if (modelId.includes('cohere.command')) return processCohereChunk;\n if (modelId.includes('mistral')) return processMistralChunk;\n return undefined;\n}\n\n/** Collects the stream items into a state and sets the span attributes from it when the stream ends. */\nasync function* instrumentStream<T>(\n stream: AsyncIterable<T>,\n span: Span,\n abortSignal: AbortSignal | undefined,\n recordOutputs: boolean,\n processItem: (item: T, state: BedrockStreamState) => void,\n): AsyncGenerator<T> {\n const state: BedrockStreamState = {\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n parts: recordOutputs ? [] : undefined,\n };\n try {\n for await (const item of stream) {\n processItem(item, state);\n yield item;\n }\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n } finally {\n if (state.parts) {\n setOutputMessages(span, state.parts);\n }\n endStreamSpan(span, state, false);\n }\n}\n\nfunction processConverseStreamEvent(event: ConverseStreamOutput, state: BedrockStreamState): void {\n appendConverseStreamContent(event, state);\n pushFinishReason(state, event.messageStop?.stopReason);\n const usage = event.metadata?.usage;\n if (usage) {\n // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n typeof usage.inputTokens === 'number'\n ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0)\n : undefined;\n state.completionTokens = usage.outputTokens;\n state.cacheReadInputTokens = usage.cacheReadInputTokens;\n state.cacheCreationInputTokens = usage.cacheWriteInputTokens;\n }\n}\n\n/** `ConverseStream` events, and Amazon Nova `InvokeModelWithResponseStream` chunks, which share their shape. */\nfunction appendConverseStreamContent(\n { contentBlockStart, contentBlockDelta }: ParsedChunk,\n state: BedrockStreamState,\n): void {\n const toolUse = contentBlockStart?.start?.toolUse;\n if (toolUse) {\n startStreamToolCall(state.parts, contentBlockStart.contentBlockIndex, toolUse.toolUseId, toolUse.name);\n }\n const delta = contentBlockDelta?.delta;\n const index = contentBlockDelta?.contentBlockIndex;\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.toolUse?.input);\n appendStreamPart(state.parts, index, 'reasoning', delta?.reasoningContent?.text);\n}\n\nfunction setStopReason(span: Span, stopReason: string | undefined): void {\n if (stopReason !== undefined) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([stopReason]));\n }\n}\n\nfunction pushFinishReason(state: StreamResponseState, reason: unknown): void {\n if (typeof reason === 'string') {\n state.finishReasons.push(reason);\n }\n}\n\nfunction parseRequestBody(body: unknown): ParsedChunk {\n // `InvokeModel` takes the body as a JSON string or as bytes.\n const text = typeof body === 'string' ? body : body instanceof Uint8Array ? textDecoder.decode(body) : undefined;\n if (!text) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction parseChunk(bytes?: Uint8Array): ParsedChunk {\n if (!bytes || !(bytes instanceof Uint8Array)) {\n return null;\n }\n try {\n const str = Buffer.from(bytes).toString('utf-8');\n return JSON.parse(str);\n } catch (err) {\n DEBUG_BUILD && debug.warn('[instrumentation:aws-sdk] failed to parse streamed bedrock chunk', err);\n return null;\n }\n}\n\nfunction processNovaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n appendConverseStreamContent(parsedChunk, state);\n const usage = parsedChunk.metadata?.usage;\n if (typeof usage?.inputTokens === 'number') {\n state.promptTokens = usage.inputTokens;\n }\n if (typeof usage?.outputTokens === 'number') {\n state.completionTokens = usage.outputTokens;\n }\n pushFinishReason(state, parsedChunk.messageStop?.stopReason);\n}\n\n/** Claude chunks are Anthropic Messages streaming events. */\nfunction processClaudeChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n const { index, content_block: block, delta } = parsedChunk;\n if (block?.type === 'tool_use') {\n startStreamToolCall(state.parts, index, block.id, block.name);\n }\n appendStreamPart(state.parts, index, 'text', delta?.text);\n appendStreamPart(state.parts, index, 'tool_call', delta?.partial_json);\n appendStreamPart(state.parts, index, 'reasoning', delta?.thinking);\n const inputUsage = parsedChunk.message?.usage;\n if (typeof inputUsage?.cache_read_input_tokens === 'number') {\n state.cacheReadInputTokens = inputUsage.cache_read_input_tokens;\n }\n if (typeof inputUsage?.cache_creation_input_tokens === 'number') {\n state.cacheCreationInputTokens = inputUsage.cache_creation_input_tokens;\n }\n if (typeof inputUsage?.input_tokens === 'number') {\n // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input.\n state.promptTokens =\n inputUsage.input_tokens + (state.cacheReadInputTokens ?? 0) + (state.cacheCreationInputTokens ?? 0);\n }\n // `message_start` carries only a placeholder output count. The final count arrives in `message_delta`.\n if (typeof parsedChunk.usage?.output_tokens === 'number') {\n state.completionTokens = parsedChunk.usage.output_tokens;\n }\n pushFinishReason(state, parsedChunk.delta?.stop_reason);\n}\n\nfunction processTitanChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.inputTextTokenCount === 'number') {\n state.promptTokens = parsedChunk.inputTextTokenCount;\n }\n if (typeof parsedChunk.totalOutputTextTokenCount === 'number') {\n state.completionTokens = parsedChunk.totalOutputTextTokenCount;\n }\n pushFinishReason(state, parsedChunk.completionReason);\n}\n\nfunction processLlamaChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n if (typeof parsedChunk.prompt_token_count === 'number') {\n state.promptTokens = parsedChunk.prompt_token_count;\n }\n if (typeof parsedChunk.generation_token_count === 'number') {\n state.completionTokens = parsedChunk.generation_token_count;\n }\n pushFinishReason(state, parsedChunk.stop_reason);\n}\n\n/**\n * Bedrock adds the token counts to the last chunk of a stream. For models that send no counts of their own,\n * this is the only real count.\n */\nfunction processInvocationMetrics(parsedChunk: ParsedChunk, state: StreamResponseState): void {\n const metrics = parsedChunk['amazon-bedrock-invocationMetrics'];\n if (typeof metrics?.inputTokenCount === 'number') {\n state.promptTokens = metrics.inputTokenCount;\n }\n if (typeof metrics?.outputTokenCount === 'number') {\n state.completionTokens = metrics.outputTokenCount;\n }\n}\n\nfunction processMistralChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.outputs?.[0]?.stop_reason);\n}\n\nfunction processCohereChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.generations?.[0]?.finish_reason);\n}\n\nfunction processCohereRChunk(parsedChunk: ParsedChunk, state: BedrockStreamState): void {\n processInvocationMetrics(parsedChunk, state);\n pushFinishReason(state, parsedChunk.finish_reason);\n}\n","import type { Span } from '@sentry/core';\nimport {\n AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS as ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,\n AWS_DYNAMODB_CONSISTENT_READ as ATTR_AWS_DYNAMODB_CONSISTENT_READ,\n AWS_DYNAMODB_CONSUMED_CAPACITY as ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY,\n AWS_DYNAMODB_COUNT as ATTR_AWS_DYNAMODB_COUNT,\n AWS_DYNAMODB_EXCLUSIVE_START_TABLE as ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES as ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,\n AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES as ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,\n AWS_DYNAMODB_INDEX_NAME as ATTR_AWS_DYNAMODB_INDEX_NAME,\n AWS_DYNAMODB_ITEM_COLLECTION_METRICS as ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,\n AWS_DYNAMODB_LIMIT as ATTR_AWS_DYNAMODB_LIMIT,\n AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES as ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,\n AWS_DYNAMODB_PROJECTION as ATTR_AWS_DYNAMODB_PROJECTION,\n AWS_DYNAMODB_PROVISIONED_READ_CAPACITY as ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,\n AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY as ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,\n AWS_DYNAMODB_SCAN_FORWARD as ATTR_AWS_DYNAMODB_SCAN_FORWARD,\n AWS_DYNAMODB_SCANNED_COUNT as ATTR_AWS_DYNAMODB_SCANNED_COUNT,\n AWS_DYNAMODB_SEGMENT as ATTR_AWS_DYNAMODB_SEGMENT,\n AWS_DYNAMODB_SELECT as ATTR_AWS_DYNAMODB_SELECT,\n AWS_DYNAMODB_TABLE_COUNT as ATTR_AWS_DYNAMODB_TABLE_COUNT,\n AWS_DYNAMODB_TABLE_NAMES as ATTR_AWS_DYNAMODB_TABLE_NAMES,\n AWS_DYNAMODB_TOTAL_SEGMENTS as ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport { DB_SYSTEM_VALUE_DYNAMODB } from '../constants';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nfunction toArray<T>(values: T | T[]): T[] {\n return Array.isArray(values) ? values : [values];\n}\n\nexport class DynamodbServiceExtension implements ServiceExtension {\n public requestPreSpanHook(normalizedRequest: NormalizedRequest): RequestMetadata {\n const operation = normalizedRequest.commandName;\n const tableName = normalizedRequest.commandInput?.TableName;\n\n const spanAttributes: Record<string, unknown> = {};\n\n spanAttributes[DB_SYSTEM_NAME] = DB_SYSTEM_VALUE_DYNAMODB;\n spanAttributes[DB_NAMESPACE] = tableName;\n spanAttributes[DB_OPERATION_NAME] = operation;\n\n // `RequestItems` is undefined when no table names are returned; its keys are the table names.\n if (normalizedRequest.commandInput?.TableName) {\n // Necessary for commands with only 1 table name (e.g. CreateTable). Attribute is `TableName`, not keys of `RequestItems`.\n spanAttributes[ATTR_AWS_DYNAMODB_TABLE_NAMES] = [normalizedRequest.commandInput.TableName];\n } else if (normalizedRequest.commandInput?.RequestItems) {\n spanAttributes[ATTR_AWS_DYNAMODB_TABLE_NAMES] = Object.keys(normalizedRequest.commandInput.RequestItems);\n }\n\n if (operation === 'CreateTable' || operation === 'UpdateTable') {\n // only check for ProvisionedThroughput since ReadCapacityUnits and WriteCapacityUnits are required attributes\n if (normalizedRequest.commandInput?.ProvisionedThroughput) {\n spanAttributes[ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY] =\n normalizedRequest.commandInput.ProvisionedThroughput.ReadCapacityUnits;\n spanAttributes[ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY] =\n normalizedRequest.commandInput.ProvisionedThroughput.WriteCapacityUnits;\n }\n }\n\n if (operation === 'GetItem' || operation === 'Scan' || operation === 'Query') {\n if (normalizedRequest.commandInput?.ConsistentRead) {\n spanAttributes[ATTR_AWS_DYNAMODB_CONSISTENT_READ] = normalizedRequest.commandInput.ConsistentRead;\n }\n }\n\n if (operation === 'Query' || operation === 'Scan') {\n if (normalizedRequest.commandInput?.ProjectionExpression) {\n spanAttributes[ATTR_AWS_DYNAMODB_PROJECTION] = normalizedRequest.commandInput.ProjectionExpression;\n }\n }\n\n if (operation === 'CreateTable') {\n if (normalizedRequest.commandInput?.GlobalSecondaryIndexes) {\n spanAttributes[ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES] = toArray(\n normalizedRequest.commandInput.GlobalSecondaryIndexes,\n ).map((x: unknown) => JSON.stringify(x));\n }\n\n if (normalizedRequest.commandInput?.LocalSecondaryIndexes) {\n spanAttributes[ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES] = toArray(\n normalizedRequest.commandInput.LocalSecondaryIndexes,\n ).map((x: unknown) => JSON.stringify(x));\n }\n }\n\n if (operation === 'ListTables' || operation === 'Query' || operation === 'Scan') {\n if (normalizedRequest.commandInput?.Limit) {\n spanAttributes[ATTR_AWS_DYNAMODB_LIMIT] = normalizedRequest.commandInput.Limit;\n }\n }\n\n if (operation === 'ListTables') {\n if (normalizedRequest.commandInput?.ExclusiveStartTableName) {\n spanAttributes[ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE] =\n normalizedRequest.commandInput.ExclusiveStartTableName;\n }\n }\n\n if (operation === 'Query') {\n if (normalizedRequest.commandInput?.ScanIndexForward) {\n spanAttributes[ATTR_AWS_DYNAMODB_SCAN_FORWARD] = normalizedRequest.commandInput.ScanIndexForward;\n }\n\n if (normalizedRequest.commandInput?.IndexName) {\n spanAttributes[ATTR_AWS_DYNAMODB_INDEX_NAME] = normalizedRequest.commandInput.IndexName;\n }\n\n if (normalizedRequest.commandInput?.Select) {\n spanAttributes[ATTR_AWS_DYNAMODB_SELECT] = normalizedRequest.commandInput.Select;\n }\n }\n\n if (operation === 'Scan') {\n if (normalizedRequest.commandInput?.Segment) {\n spanAttributes[ATTR_AWS_DYNAMODB_SEGMENT] = normalizedRequest.commandInput?.Segment;\n }\n\n if (normalizedRequest.commandInput?.TotalSegments) {\n spanAttributes[ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS] = normalizedRequest.commandInput?.TotalSegments;\n }\n\n if (normalizedRequest.commandInput?.IndexName) {\n spanAttributes[ATTR_AWS_DYNAMODB_INDEX_NAME] = normalizedRequest.commandInput.IndexName;\n }\n\n if (normalizedRequest.commandInput?.Select) {\n spanAttributes[ATTR_AWS_DYNAMODB_SELECT] = normalizedRequest.commandInput.Select;\n }\n }\n\n if (operation === 'UpdateTable') {\n if (normalizedRequest.commandInput?.AttributeDefinitions) {\n spanAttributes[ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS] = toArray(\n normalizedRequest.commandInput.AttributeDefinitions,\n ).map((x: unknown) => JSON.stringify(x));\n }\n\n if (normalizedRequest.commandInput?.GlobalSecondaryIndexUpdates) {\n spanAttributes[ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES] = toArray(\n normalizedRequest.commandInput.GlobalSecondaryIndexUpdates,\n ).map((x: unknown) => JSON.stringify(x));\n }\n }\n\n return {\n spanAttributes,\n // Matches what the exporter infers from the db system for the OTel DynamoDB spans.\n spanOp: DB,\n };\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n if (response.data?.ConsumedCapacity) {\n span.setAttribute(\n ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY,\n toArray(response.data.ConsumedCapacity).map((x: unknown) => JSON.stringify(x)),\n );\n }\n\n if (response.data?.ItemCollectionMetrics) {\n span.setAttribute(\n ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,\n toArray(response.data.ItemCollectionMetrics).map((x: unknown) => JSON.stringify(x)),\n );\n }\n\n if (response.data?.TableNames) {\n span.setAttribute(ATTR_AWS_DYNAMODB_TABLE_COUNT, response.data?.TableNames.length);\n }\n\n if (response.data?.Count) {\n span.setAttribute(ATTR_AWS_DYNAMODB_COUNT, response.data?.Count);\n }\n\n if (response.data?.ScannedCount) {\n span.setAttribute(ATTR_AWS_DYNAMODB_SCANNED_COUNT, response.data?.ScannedCount);\n }\n }\n}\n","import { _AWS_KINESIS_STREAM_NAME as AWS_KINESIS_STREAM_NAME } from '@sentry/conventions/attributes';\nimport type { NormalizedRequest } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class KinesisServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const streamName = request.commandInput?.StreamName;\n const spanAttributes: Record<string, unknown> = {};\n\n if (streamName) {\n // oxlint-disable-next-line typescript/no-deprecated -- old-semconv aws.kinesis.stream.name, matched to the OTel aws-sdk integration\n spanAttributes[AWS_KINESIS_STREAM_NAME] = streamName;\n }\n\n return {\n spanAttributes,\n };\n }\n}\n","import type { Span } from '@sentry/core';\nimport { debug, getTraceData } from '@sentry/core';\nimport {\n FAAS_INVOCATION_ID as ATTR_FAAS_INVOCATION_ID,\n FAAS_INVOKED_NAME as ATTR_FAAS_INVOKED_NAME,\n FAAS_INVOKED_PROVIDER as ATTR_FAAS_INVOKED_PROVIDER,\n FAAS_INVOKED_REGION as ATTR_FAAS_INVOKED_REGION,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nconst INVOKE_COMMAND = 'Invoke';\n\nexport class LambdaServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const functionName = request.commandInput?.FunctionName;\n\n const spanAttributes: Record<string, unknown> = {};\n let spanName: string | undefined;\n\n if (request.commandName === INVOKE_COMMAND) {\n spanAttributes[ATTR_FAAS_INVOKED_NAME] = functionName;\n spanAttributes[ATTR_FAAS_INVOKED_PROVIDER] = 'aws';\n spanName = `${functionName} ${INVOKE_COMMAND}`;\n }\n\n return {\n spanAttributes,\n spanName,\n };\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n if (request.commandName === INVOKE_COMMAND && request.commandInput) {\n request.commandInput.ClientContext = injectLambdaPropagationContext(request.commandInput.ClientContext, span);\n }\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n if (response.request.commandName === INVOKE_COMMAND) {\n span.setAttribute(ATTR_FAAS_INVOCATION_ID, response.requestId);\n // Region resolves asynchronously after `requestPreSpanHook`, so it's backfilled onto the\n // normalized request and read here (same timing as `cloud.region`).\n if (response.request.region) {\n span.setAttribute(ATTR_FAAS_INVOKED_REGION, response.request.region);\n }\n }\n }\n}\n\nfunction injectLambdaPropagationContext(clientContext: string | undefined, span: Span): string | undefined {\n try {\n const propagatedContext = getTraceData({ span });\n\n const parsedClientContext = clientContext ? JSON.parse(Buffer.from(clientContext, 'base64').toString('utf8')) : {};\n\n const updatedClientContext = {\n ...parsedClientContext,\n custom: {\n ...parsedClientContext.custom,\n ...propagatedContext,\n },\n };\n\n const encodedClientContext = Buffer.from(JSON.stringify(updatedClientContext)).toString('base64');\n\n // The length of client context is capped at 3583 bytes of base64 encoded data\n // (https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax)\n if (encodedClientContext.length > 3583) {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:aws-sdk] cannot set trace propagation on lambda invoke parameters due to ClientContext length limitations.',\n );\n return clientContext;\n }\n\n return encodedClientContext;\n } catch (e) {\n DEBUG_BUILD && debug.log('[instrumentation:aws-sdk] failed to set trace propagation on lambda ClientContext', e);\n return clientContext;\n }\n}\n","import { AWS_S3_BUCKET } from '@sentry/conventions/attributes';\nimport type { NormalizedRequest } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class S3ServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const bucketName = request.commandInput?.Bucket;\n const spanAttributes: Record<string, unknown> = {};\n\n if (bucketName) {\n spanAttributes[AWS_S3_BUCKET] = bucketName;\n }\n\n return {\n spanAttributes,\n };\n }\n}\n","import type { Span } from '@sentry/core';\nimport { AWS_SECRETSMANAGER_SECRET_ARN as ATTR_AWS_SECRETSMANAGER_SECRET_ARN } from '@sentry/conventions/attributes';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class SecretsManagerServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const secretId = request.commandInput?.SecretId;\n const spanAttributes: Record<string, unknown> = {};\n if (typeof secretId === 'string' && secretId.startsWith('arn:aws:secretsmanager:')) {\n spanAttributes[ATTR_AWS_SECRETSMANAGER_SECRET_ARN] = secretId;\n }\n\n return {\n spanAttributes,\n };\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n const secretArn = response.data?.ARN;\n if (secretArn) {\n span.setAttribute(ATTR_AWS_SECRETSMANAGER_SECRET_ARN, secretArn);\n }\n }\n}\n","import type { SerializedTraceData } from '@sentry/core';\nimport { debug, uniq } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport type { SNS, SQS } from '../aws-sdk.types';\n\n// https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html\nexport const MAX_MESSAGE_ATTRIBUTES = 10;\n\n// Sentry trace-propagation headers written into / read from AWS message attributes.\nconst SENTRY_TRACE_HEADER = 'sentry-trace';\nconst BAGGAGE_HEADER = 'baggage';\nconst PROPAGATION_FIELDS = [SENTRY_TRACE_HEADER, BAGGAGE_HEADER];\n\nexport interface AwsSdkContextObject {\n [key: string]: {\n StringValue?: string;\n Value?: string;\n };\n}\n\n/**\n * Inject trace-propagation headers (from `getTraceData({ span })`) into an SQS/SNS message-attribute\n * map, so the consumer can continue the trace. Respects the SQS 10-attribute quota. Mirrors the OTel\n * integration's `injectPropagationContext`, but writes Sentry's `sentry-trace`/`baggage` instead of\n * W3C headers. Callers pass the precomputed headers so batch sends serialize them only once.\n */\nexport function injectPropagationContext(\n attributesMap: SQS.MessageBodyAttributeMap | SNS.MessageAttributeMap | undefined,\n traceData: SerializedTraceData,\n): SQS.MessageBodyAttributeMap | SNS.MessageAttributeMap {\n const attributes = attributesMap ?? {};\n const headerKeys = Object.keys(traceData) as (keyof SerializedTraceData)[];\n\n if (Object.keys(attributes).length + headerKeys.length <= MAX_MESSAGE_ATTRIBUTES) {\n for (const key of headerKeys) {\n const value = traceData[key];\n if (value) {\n // Index-assigning into the SQS/SNS map union needs one concrete map type; the written value\n // shape is valid for both.\n attributes[key] = { DataType: 'String', StringValue: value };\n }\n }\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:aws-sdk] cannot set trace propagation on SQS/SNS message due to maximum amount of MessageAttributes',\n );\n }\n return attributes;\n}\n\n/** Read the propagation headers back off a received SQS message, if present. */\nexport function extractPropagationHeaders(\n message: SQS.Message,\n): { sentryTrace?: string; baggage?: string } | undefined {\n const carrier = (message.MessageAttributes ?? {}) as AwsSdkContextObject;\n const sentryTrace = carrier[SENTRY_TRACE_HEADER]?.StringValue ?? carrier[SENTRY_TRACE_HEADER]?.Value;\n if (!sentryTrace) {\n return undefined;\n }\n return {\n sentryTrace,\n baggage: carrier[BAGGAGE_HEADER]?.StringValue ?? carrier[BAGGAGE_HEADER]?.Value,\n };\n}\n\nexport function addPropagationFieldsToAttributeNames(messageAttributeNames: string[] = []): string[] {\n return uniq([...messageAttributeNames, ...PROPAGATION_FIELDS]);\n}\n","import type { Span } from '@sentry/core';\nimport { getClient, getTraceData, hasSpanStreamingEnabled } from '@sentry/core';\nimport {\n AWS_SNS_TOPIC_ARN as ATTR_AWS_SNS_TOPIC_ARN,\n MESSAGING_DESTINATION as ATTR_MESSAGING_DESTINATION,\n MESSAGING_DESTINATION_KIND as ATTR_MESSAGING_DESTINATION_KIND,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n SENTRY_KIND,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport { MESSAGING_DESTINATION_KIND_VALUE_TOPIC } from '../constants';\nimport type { NormalizedRequest, NormalizedResponse } from '../types';\nimport { injectPropagationContext } from './MessageAttributes';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\n/** Stands in for a destination the command does not name. */\nconst UNKNOWN_DESTINATION = 'unknown';\nconst SEND_OPERATION = 'send';\n\n/**\n * Streamed names follow the messaging conventions, `<operation type> <destination>`. Transaction-mode\n * names keep the order they had. A destination the command does not name drops out of both.\n */\nfunction buildSpanName(operation: string, destination: string | undefined, isStreamed: boolean): string {\n if (!destination) {\n return operation;\n }\n return isStreamed ? `${operation} ${destination}` : `${destination} ${operation}`;\n}\n\nexport class SnsServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n let spanName = `SNS ${request.commandName}`;\n let spanOp: string | undefined;\n\n const spanAttributes: Record<string, unknown> = {\n [MESSAGING_SYSTEM]: 'aws.sns',\n [SENTRY_KIND]: 'client',\n };\n\n if (request.commandName === 'Publish') {\n spanOp = QUEUE_PUBLISH;\n spanAttributes[SENTRY_KIND] = 'producer';\n\n // oxlint-disable-next-line typescript/no-deprecated -- old-semconv messaging.destination_kind, matched to the OTel aws-sdk integration\n spanAttributes[ATTR_MESSAGING_DESTINATION_KIND] = MESSAGING_DESTINATION_KIND_VALUE_TOPIC;\n const { TopicArn, TargetArn, PhoneNumber } = request.commandInput;\n const destinationName = extractDestinationName(TopicArn, TargetArn, PhoneNumber);\n // oxlint-disable-next-line typescript/no-deprecated -- old-semconv messaging.destination, matched to the OTel aws-sdk integration\n spanAttributes[ATTR_MESSAGING_DESTINATION] = destinationName;\n spanAttributes[MESSAGING_DESTINATION_NAME] = TopicArn || TargetArn || PhoneNumber || UNKNOWN_DESTINATION;\n spanAttributes[MESSAGING_OPERATION_TYPE] = SEND_OPERATION;\n\n const client = getClient();\n\n const isStreamed = !!client && hasSpanStreamingEnabled(client);\n // The raw phone number never goes in a name. A `/` in the suffix means a platform-endpoint ARN\n // (`endpoint/GCM/myapp/<uuid>`) rather than a topic, so only a streamed name drops it.\n const named = PhoneNumber ? 'phone_number' : destinationName;\n const destinationForName =\n named === UNKNOWN_DESTINATION || (isStreamed && !PhoneNumber && named.includes('/')) ? undefined : named;\n\n spanName = buildSpanName(SEND_OPERATION, destinationForName, isStreamed);\n }\n\n const topicArn = request.commandInput?.TopicArn;\n if (topicArn) {\n spanAttributes[ATTR_AWS_SNS_TOPIC_ARN] = topicArn;\n }\n\n return {\n spanAttributes,\n spanName,\n spanOp,\n };\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n if (request.commandName === 'Publish') {\n const origMessageAttributes = request.commandInput.MessageAttributes ?? {};\n request.commandInput.MessageAttributes = injectPropagationContext(origMessageAttributes, getTraceData({ span }));\n }\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n const topicArn = response.data?.TopicArn;\n if (topicArn) {\n span.setAttribute(ATTR_AWS_SNS_TOPIC_ARN, topicArn);\n }\n }\n}\n\nfunction extractDestinationName(topicArn: string, targetArn: string, phoneNumber: string): string {\n if (topicArn || targetArn) {\n const arn = topicArn ?? targetArn;\n try {\n return arn.substring(arn.lastIndexOf(':') + 1);\n } catch {\n return arn;\n }\n } else if (phoneNumber) {\n return phoneNumber;\n } else {\n return UNKNOWN_DESTINATION;\n }\n}\n","import type { Span } from '@sentry/core';\nimport { getClient, getTraceData, hasSpanStreamingEnabled, propagationContextFromHeaders } from '@sentry/core';\nimport {\n MESSAGING_BATCH_MESSAGE_COUNT,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_ID,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n SENTRY_KIND,\n URL_FULL,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PUBLISH, QUEUE_RECEIVE } from '@sentry/conventions/op';\nimport type { SQS } from '../aws-sdk.types';\nimport type { CommandInput, NormalizedRequest, NormalizedResponse } from '../types';\nimport {\n addPropagationFieldsToAttributeNames,\n extractPropagationHeaders,\n injectPropagationContext,\n} from './MessageAttributes';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class SqsServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const queueUrl = extractQueueUrl(request.commandInput);\n const queueName = extractQueueNameFromUrl(queueUrl);\n let operation: string | undefined;\n let spanOp: string | undefined;\n\n const spanAttributes: Record<string, unknown> = {\n [MESSAGING_SYSTEM]: 'aws_sqs',\n [MESSAGING_DESTINATION_NAME]: queueName,\n // oxlint-disable-next-line sdk/no-unfiltered-url-attributes -- SQS queue identifier, not an HTTP request URL\n [URL_FULL]: queueUrl,\n [SENTRY_KIND]: 'client',\n };\n\n switch (request.commandName) {\n case 'ReceiveMessage':\n {\n operation = 'receive';\n spanOp = QUEUE_RECEIVE;\n spanAttributes[SENTRY_KIND] = 'consumer';\n\n request.commandInput.MessageAttributeNames = addPropagationFieldsToAttributeNames(\n request.commandInput.MessageAttributeNames,\n );\n }\n break;\n\n case 'SendMessage':\n case 'SendMessageBatch':\n operation = 'send';\n spanOp = QUEUE_PUBLISH;\n spanAttributes[SENTRY_KIND] = 'producer';\n break;\n }\n\n if (operation) {\n spanAttributes[MESSAGING_OPERATION_TYPE] = operation;\n }\n\n const client = getClient();\n const isStreamed = !!client && hasSpanStreamingEnabled(client);\n\n return {\n spanAttributes,\n spanName: buildSpanName(operation, queueName, isStreamed),\n // Fallback to `rpc` if there's no messaging operation\n spanOp,\n };\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n switch (request.commandName) {\n case 'SendMessage':\n {\n const origMessageAttributes = request.commandInput.MessageAttributes ?? {};\n request.commandInput.MessageAttributes = injectPropagationContext(\n origMessageAttributes,\n getTraceData({ span }),\n );\n }\n break;\n\n case 'SendMessageBatch':\n {\n const entries = request.commandInput?.Entries;\n if (Array.isArray(entries)) {\n // Serialized once; the headers are identical for every entry of the batch.\n const traceData = getTraceData({ span });\n entries.forEach((messageParams: { MessageAttributes: SQS.MessageBodyAttributeMap }) => {\n messageParams.MessageAttributes = injectPropagationContext(\n messageParams.MessageAttributes ?? {},\n traceData,\n );\n });\n }\n }\n break;\n }\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n switch (response.request.commandName) {\n case 'SendMessage':\n span.setAttribute(MESSAGING_MESSAGE_ID, response?.data?.MessageId);\n break;\n\n case 'SendMessageBatch':\n break;\n\n case 'ReceiveMessage': {\n const messages: SQS.Message[] = response?.data?.Messages || [];\n\n span.setAttribute(MESSAGING_BATCH_MESSAGE_COUNT, messages.length);\n\n for (const message of messages) {\n linkReceivedMessageToProducer(span, message);\n }\n break;\n }\n }\n }\n}\n\n/**\n * Link a received SQS message's span back to the producer trace carried in its propagation headers.\n * No-op when the message has no (valid) `sentry-trace`/`baggage` attributes.\n */\nfunction linkReceivedMessageToProducer(span: Span, message: SQS.Message): void {\n const headers = extractPropagationHeaders(message);\n if (!headers) {\n return;\n }\n\n const { parentSpanId, traceId, sampled } = propagationContextFromHeaders(headers.sentryTrace, headers.baggage);\n if (traceId && parentSpanId) {\n span.addLink({\n context: {\n traceId,\n spanId: parentSpanId,\n traceFlags: sampled ? 1 : 0,\n },\n attributes: {\n [MESSAGING_MESSAGE_ID]: message.MessageId,\n },\n });\n }\n}\n\n/**\n * Streamed names follow the messaging conventions, `<operation type> <destination>`. Transaction-mode\n * names keep the order they had. Either way a command with no `QueueUrl` drops to the operation alone,\n * which wins over the aws-sdk house style (`SQS.ReceiveMessage`). That style still names the commands\n * with no messaging operation, which is why this returns undefined for them.\n */\nfunction buildSpanName(\n operation: string | undefined,\n queueName: string | undefined,\n isStreamed: boolean,\n): string | undefined {\n if (!operation) {\n return undefined;\n }\n if (!queueName) {\n return operation;\n }\n return isStreamed ? `${operation} ${queueName}` : `${queueName} ${operation}`;\n}\n\nfunction extractQueueUrl(commandInput: CommandInput): string {\n return commandInput?.QueueUrl;\n}\n\nfunction extractQueueNameFromUrl(queueUrl: string): string | undefined {\n if (!queueUrl) return undefined;\n\n const segments = queueUrl.split('/');\n if (segments.length === 0) return undefined;\n\n // A trailing slash leaves an empty last segment, which is not a queue name\n return segments[segments.length - 1] || undefined;\n}\n","import {\n AWS_STEP_FUNCTIONS_ACTIVITY_ARN as ATTR_AWS_STEP_FUNCTIONS_ACTIVITY_ARN,\n AWS_STEP_FUNCTIONS_STATE_MACHINE_ARN as ATTR_AWS_STEP_FUNCTIONS_STATE_MACHINE_ARN,\n} from '@sentry/conventions/attributes';\nimport type { NormalizedRequest } from '../types';\nimport type { RequestMetadata, ServiceExtension } from './ServiceExtension';\n\nexport class StepFunctionsServiceExtension implements ServiceExtension {\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const stateMachineArn = request.commandInput?.stateMachineArn;\n const activityArn = request.commandInput?.activityArn;\n const spanAttributes: Record<string, unknown> = {};\n\n if (stateMachineArn) {\n spanAttributes[ATTR_AWS_STEP_FUNCTIONS_STATE_MACHINE_ARN] = stateMachineArn;\n }\n\n if (activityArn) {\n spanAttributes[ATTR_AWS_STEP_FUNCTIONS_ACTIVITY_ARN] = activityArn;\n }\n\n return {\n spanAttributes,\n };\n }\n}\n","import type { Span } from '@sentry/core';\nimport type { GenAiOptions } from '../../../ai/core/utils';\nimport type { NormalizedRequest, NormalizedResponse, RequestMetadata } from '../types';\nimport { BedrockRuntimeServiceExtension } from './bedrock-runtime';\nimport { DynamodbServiceExtension } from './dynamodb';\nimport { KinesisServiceExtension } from './kinesis';\nimport { LambdaServiceExtension } from './lambda';\nimport { S3ServiceExtension } from './s3';\nimport { SecretsManagerServiceExtension } from './secretsmanager';\nimport type { ServiceExtension } from './ServiceExtension';\nimport { SnsServiceExtension } from './sns';\nimport { SqsServiceExtension } from './sqs';\nimport { StepFunctionsServiceExtension } from './stepfunctions';\n\nexport class ServicesExtensions implements ServiceExtension {\n // Per-service extensions, keyed by the client's `serviceId` (e.g. `'S3'`). Services without a\n // registered extension still get the base rpc span from the subscriber.\n private _services: Map<string, ServiceExtension>;\n\n public constructor(genAiOptions?: GenAiOptions) {\n this._services = new Map<string, ServiceExtension>([\n ['SecretsManager', new SecretsManagerServiceExtension()],\n ['SFN', new StepFunctionsServiceExtension()],\n ['SQS', new SqsServiceExtension()],\n ['SNS', new SnsServiceExtension()],\n ['DynamoDB', new DynamodbServiceExtension()],\n ['Lambda', new LambdaServiceExtension()],\n ['S3', new S3ServiceExtension()],\n ['Kinesis', new KinesisServiceExtension()],\n ['BedrockRuntime', new BedrockRuntimeServiceExtension(genAiOptions)],\n ]);\n }\n\n public requestPreSpanHook(request: NormalizedRequest): RequestMetadata {\n const serviceExtension = this._services.get(request.serviceName);\n if (!serviceExtension) {\n return {};\n }\n return serviceExtension.requestPreSpanHook(request);\n }\n\n public requestPostSpanHook(request: NormalizedRequest, span: Span): void {\n const serviceExtension = this._services.get(request.serviceName);\n serviceExtension?.requestPostSpanHook?.(request, span);\n }\n\n public responseHook(response: NormalizedResponse, span: Span): void {\n const serviceExtension = this._services.get(response.request.serviceName);\n serviceExtension?.responseHook?.(response, span);\n }\n}\n","import { CLOUD_REGION, RPC_METHOD, RPC_SERVICE, RPC_SYSTEM } from '@sentry/conventions/attributes';\nimport type { CommandInput, NormalizedRequest } from './types';\n\nexport function removeSuffixFromStringIfExists(str: string, suffixToRemove: string): string {\n const suffixLength = suffixToRemove.length;\n return str?.slice(-suffixLength) === suffixToRemove ? str.slice(0, -suffixLength) : str;\n}\n\nexport function normalizeV3Request(\n serviceName: string,\n commandNameWithSuffix: string,\n commandInput: CommandInput,\n region: string | undefined,\n): NormalizedRequest {\n return {\n serviceName: serviceName?.replace(/\\s+/g, ''),\n commandName: removeSuffixFromStringIfExists(commandNameWithSuffix, 'Command'),\n commandInput,\n region,\n };\n}\n\nexport function extractAttributesFromNormalizedRequest(normalizedRequest: NormalizedRequest): Record<string, unknown> {\n return {\n // oxlint-disable-next-line typescript/no-deprecated -- old-semconv rpc.system, matched to the OTel aws-sdk integration\n [RPC_SYSTEM]: 'aws-api',\n [RPC_METHOD]: normalizedRequest.commandName,\n [RPC_SERVICE]: normalizedRequest.serviceName,\n [CLOUD_REGION]: normalizedRequest.region,\n };\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport {\n _AWS_REQUEST_ID as AWS_REQUEST_ID,\n AWS_REQUEST_EXTENDED_ID,\n CLOUD_REGION,\n SENTRY_KIND,\n HTTP_RESPONSE_STATUS_CODE,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { RPC } from '@sentry/conventions/op';\nimport type { GenAiOptions } from '../../ai/core/utils';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { awsSdkModuleNames } from '../../orchestrion/config/aws-sdk';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport type { TracingChannelLifeCycleOptions } from '../../tracing-channel';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport { AWS_SDK_ORIGIN_INTEGRATION_NAME } from './constants';\nimport { ServicesExtensions } from './services';\nimport type { NormalizedRequest, NormalizedResponse, RequestMetadata } from './types';\nimport { extractAttributesFromNormalizedRequest, normalizeV3Request, removeSuffixFromStringIfExists } from './utils';\n\n// Same name as the OTel `Aws` integration by design, so enabling injection swaps this in for it.\nconst INTEGRATION_NAME = 'Aws' as const;\n\n// The context orchestrion's transform attaches to the channel: `arguments` is the live args of the\n// wrapped `Client.prototype.send` call (`[command, ...]`), `self` the client, `result`/`error` the\n// settled value. The `_sentry*` fields are stashed by us across the call's lifecycle.\ninterface AwsSendChannelContext extends OrchestrionChannelContext {\n self?: { config?: AwsClientConfig; constructor?: { name?: string } };\n _sentryNormalizedRequest?: NormalizedRequest;\n _sentryRequestMetadata?: RequestMetadata;\n _sentryRegion?: { settled: boolean; promise: Promise<void> };\n}\n\ninterface AwsClientConfig {\n serviceId?: string;\n region?: () => string | Promise<string> | undefined;\n}\n\ninterface AwsV3Command {\n input?: Record<string, unknown>;\n constructor?: { name?: string };\n}\n\n// `metadata` is smithy's `ResponseMetadata`, read off the untyped channel result/error (`any` for the\n// same reason as `CommandInput`, see types.ts).\nfunction setMetadataAttributes(span: Span, metadata: Record<string, any> | undefined): void {\n if (!metadata) {\n return;\n }\n if (metadata.requestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_ID, metadata.requestId);\n }\n if (metadata.httpStatusCode) {\n span.setAttribute(HTTP_RESPONSE_STATUS_CODE, metadata.httpStatusCode);\n }\n if (metadata.extendedRequestId) {\n // oxlint-disable-next-line typescript/no-deprecated\n span.setAttribute(AWS_REQUEST_EXTENDED_ID, metadata.extendedRequestId);\n }\n}\n\n// `recordInputs` and `recordOutputs` apply to Bedrock Runtime calls, the only AWS calls that carry prompts and responses.\nexport type AwsIntegrationOptions = GenAiOptions;\n\nconst _awsIntegration = ((options?: AwsIntegrationOptions) => {\n const servicesExtensions = new ServicesExtensions(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, awsSdkModuleNames, instrumentAwsSdk, [servicesExtensions]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction getSpanOrigin(op: string): string {\n const opCategory = op.split('.')[0];\n // AI integrations use `ai` as their origin category, although their ops are `gen_ai.*`.\n const category = opCategory === 'gen_ai' ? 'ai' : opCategory;\n return `auto.${category}.${AWS_SDK_ORIGIN_INTEGRATION_NAME}`;\n}\n\nfunction instrumentAwsSdk(servicesExtensions: ServicesExtensions): void {\n const getSpan = (data: AwsSendChannelContext): Span | undefined =>\n safeChannelCallback(() => {\n const command = data.arguments[0] as AwsV3Command | undefined;\n const commandName = command?.constructor?.name;\n if (!command || !commandName) {\n // Not a recognizable v3 command call; leave the active context untouched.\n return undefined;\n }\n\n const clientConfig = data.self?.config;\n const serviceName =\n clientConfig?.serviceId ??\n // `clientName` isn't available at the `send` boundary; fall back to the client's\n // constructor name (e.g. `S3Client` -> `S3`). `serviceId` is set for all AWS clients.\n removeSuffixFromStringIfExists(data.self?.constructor?.name || 'AWS', 'Client');\n\n // Commands with all-optional members can be constructed without an input (`new\n // ListBucketsCommand()`); the OTel path traces those too, so default rather than bail.\n // The default is assigned back onto the command (not kept detached) because service hooks\n // mutate `commandInput` (trace-propagation headers, `MessageAttributeNames`) and those\n // writes must reach the serialized request. Current smithy clients already default `input`\n // to `{}` in the command constructor; this only affects older clients in our range.\n if (!command.input) {\n command.input = {};\n }\n const normalizedRequest = normalizeV3Request(serviceName, commandName, command.input, undefined);\n normalizedRequest.abortSignal = (data.arguments[1] as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n const requestMetadata = servicesExtensions.requestPreSpanHook(normalizedRequest);\n\n // `rpc` matches what the exporter infers from `rpc.service` for the OTel aws-sdk spans;\n // service extensions override it where inference yields a different op (DynamoDB: `db`).\n const op = requestMetadata.spanOp || RPC;\n const span = startInactiveSpan({\n name: requestMetadata.spanName ?? `${normalizedRequest.serviceName}.${normalizedRequest.commandName}`,\n op,\n attributes: {\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: getSpanOrigin(op),\n ...extractAttributesFromNormalizedRequest(normalizedRequest),\n ...requestMetadata.spanAttributes,\n },\n });\n\n data._sentryNormalizedRequest = normalizedRequest;\n data._sentryRequestMetadata = requestMetadata;\n\n // `region` resolves asynchronously while `send` proceeds (a channel subscriber cannot delay\n // the traced call the way the OTel middleware does). Backfill it onto the span and the\n // normalized request once available; `deferSpanEnd` holds the span open until this settles\n // so `cloud.region` cannot be lost when `send` settles first (e.g. an early failure).\n //\n // The provider call is guarded separately: the span is already started, so a synchronous\n // throw bubbling into the enclosing `safeChannelCallback` would discard it without ending it (a leaked\n // open span).\n let regionResult: string | Promise<string> | undefined;\n try {\n regionResult = clientConfig?.region?.();\n } catch {\n // Nothing to do; continue without a region.\n }\n // The `.finally` self-reference is safe: the callback only runs after initialization.\n const regionHolder: { settled: boolean; promise: Promise<void> } = {\n settled: false,\n promise: Promise.resolve(regionResult)\n .then(region => {\n if (region) {\n normalizedRequest.region = region;\n span.setAttribute(CLOUD_REGION, region);\n }\n })\n .catch(() => {\n // Nothing to do; continue without a region.\n })\n .finally(() => {\n regionHolder.settled = true;\n }),\n };\n data._sentryRegion = regionHolder;\n\n // Inject trace-propagation headers into outgoing messages (SQS/SNS/Lambda). Runs before\n // `send` proceeds, so the mutated `commandInput` is used to build the request.\n safeChannelCallback(() => servicesExtensions.requestPostSpanHook(normalizedRequest, span));\n\n return span;\n });\n\n const opts: TracingChannelLifeCycleOptions<AwsSendChannelContext> = {\n deferSpanEnd({ span, data, end }) {\n const normalizedRequest = data._sentryNormalizedRequest;\n const requestMetadata = data._sentryRequestMetadata;\n if (!normalizedRequest) {\n return false;\n }\n\n const failed = 'error' in data;\n\n // The channel `result`/`error` are untyped; the `$metadata` casts below name smithy's\n // `ResponseMetadata` shape (`any`-valued, see `setMetadataAttributes`).\n safeChannelCallback(() => {\n if (failed) {\n const err = data.error as\n | { $metadata?: Record<string, any>; RequestId?: string; extendedRequestId?: string }\n | undefined;\n const errMetadata = err?.$metadata;\n // Like the OTel path, read RequestId/extendedRequestId off the error itself, with\n // `$metadata` (which smithy service errors also carry) as the fallback. A spread won't\n // do: `$metadata` includes these keys with `undefined` values, clobbering the fallback.\n setMetadataAttributes(span, {\n requestId: err?.RequestId ?? errMetadata?.requestId,\n httpStatusCode: errMetadata?.httpStatusCode,\n extendedRequestId: err?.extendedRequestId ?? errMetadata?.extendedRequestId,\n });\n return;\n }\n\n const output = data.result as { $metadata?: Record<string, any> } | undefined;\n setMetadataAttributes(span, output?.$metadata);\n\n const normalizedResponse: NormalizedResponse = {\n data: output,\n request: normalizedRequest,\n requestId: output?.$metadata?.requestId,\n };\n servicesExtensions.responseHook(normalizedResponse, span);\n });\n\n // Streaming responses end the span when their wrapped stream is consumed (see\n // bedrock-runtime); the helper must not end it on `send` settling. Errors always end here.\n if (requestMetadata?.isStream && !failed) {\n return true;\n }\n\n // Normally the region settles long before `send` does (the SDK awaits it internally to\n // build the endpoint), but when `send` settles first (e.g. an early failure) hold the span\n // open until the region backfill lands. The error status was already applied by the\n // helper's `error` subscriber, so a plain `end()` suffices.\n const region = data._sentryRegion;\n if (region && !region.settled) {\n void region.promise.then(() => end());\n return true;\n }\n\n return false;\n },\n };\n\n // The AWS SDK's `Client.prototype.send` lives in different smithy packages across versions; the\n // transform injects one channel per package. Only the package hosting the app's client fires, so\n // subscribing to all of them is safe and never double-instruments a single call.\n const awsSendChannels = [\n CHANNELS.AWS_SMITHY_CORE_SEND,\n CHANNELS.AWS_SMITHY_CLIENT_SEND,\n CHANNELS.AWS_SDK_SMITHY_CLIENT_SEND,\n ] as const;\n\n for (const channelName of awsSendChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AwsSendChannelContext>(channelName), getSpan, opts);\n }\n}\n\n/**\n * Diagnostics-channel-based aws-sdk (v3) integration.\n *\n * Subscribes to the `orchestrion:@smithy/smithy-client:send` (and equivalent) diagnostics_channel\n * Sentry's code transform injects into the AWS SDK's smithy `Client.prototype.send`, emitting\n * spans identical to the OTel `@opentelemetry/instrumentation-aws-sdk` integration. Requires the\n * Sentry runtime hook or bundler plugin.\n */\nexport const awsIntegration = defineIntegration(_awsIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n CACHE_KEY,\n CACHE_OPERATION,\n DB_COLLECTION_NAME,\n DB_OPERATION_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, StartSpanOptions } from '@sentry/core';\nimport {\n CACHE_OPERATION_NAMES,\n debug,\n defineIntegration,\n getClient,\n hasSpanStreamingEnabled,\n startInactiveSpan,\n startSpan,\n waitForTracingChannelBinding,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport type { ChannelName } from '../orchestrion/channels';\nimport { CHANNELS } from '../orchestrion/channels';\nimport type { TracingChannelPayloadWithSpan } from '../tracing-channel';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Dataloader' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Dataloader' as const;\n\nconst MODULE_NAME = 'dataloader';\nconst ORIGIN = 'auto.db.dataloader';\n\ntype Operation = 'load' | 'loadMany' | 'batch' | 'prime' | 'clear' | 'clearAll';\n\n/**\n * Maps each operation to a convention cache op. `load`, `loadMany` and `batch` are cache reads,\n * `prime` writes an entry, and `clear`/`clearAll` remove entries. The precise operation stays\n * available on `db.operation.name`.\n */\nconst OPERATION_SPAN_OPS = {\n load: CACHE_GET,\n loadMany: CACHE_GET,\n batch: CACHE_GET,\n prime: CACHE_PUT,\n clear: CACHE_REMOVE,\n clearAll: CACHE_REMOVE,\n} as const satisfies Record<Operation, string>;\n\n// The link shape shared between a `load` span and the `batch` span it triggers.\ntype DataLoaderSpanLink = { context: ReturnType<Span['spanContext']> };\n\n// The private batch object `dataloader` stores on the loader. We stash the pending `load` span links\n// here (matching the vendored OTel instrumentation) so the batch span can link back to them.\ninterface DataLoaderBatch {\n spanLinks?: DataLoaderSpanLink[];\n}\n\ninterface DataLoaderInstance {\n name?: string | null;\n _batch?: DataLoaderBatch | null;\n}\n\ninterface DataLoaderChannelContext extends OrchestrionChannelContext {\n self?: DataLoaderInstance;\n}\n\n// Marks a wrapped `batchLoadFn` so a re-used loader (or a double construct) isn't wrapped twice.\nconst WRAPPED = Symbol('sentry.dataloader.wrapped');\n\nfunction getSpanName(loader: DataLoaderInstance | undefined, operation: Operation): string {\n const name = loader?.name;\n\n return name ? `${MODULE_NAME}.${operation} ${name}` : `${MODULE_NAME}.${operation}`;\n}\n\n// `load`/`prime`/`clear` receive a single key, `loadMany`/`batch` receive a key array. Normalize\n// both to the `string[]` shape `cache.key` expects. `clearAll` takes no key and yields `undefined`.\nfunction getCacheKey(keyArg: unknown): string[] | undefined {\n if (Array.isArray(keyArg)) {\n return keyArg.map(key => String(key));\n }\n\n return keyArg == null ? undefined : [String(keyArg)];\n}\n\nfunction makeSpanOptions(\n loader: DataLoaderInstance | undefined,\n operation: Operation,\n keyArg?: unknown,\n): StartSpanOptions {\n const cacheOperation = OPERATION_SPAN_OPS[operation];\n const client = getClient();\n\n return {\n // With span streaming, span names have to be low cardinality, so the loader name is dropped from\n // the name and reported on `db.collection.name` instead.\n name: client && hasSpanStreamingEnabled(client) ? cacheOperation : getSpanName(loader, operation),\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: cacheOperation,\n [CACHE_OPERATION]: CACHE_OPERATION_NAMES[cacheOperation],\n // Every direct operation (`load`/`loadMany`/`prime`/`clear`/`clearAll`) is a client call, matching\n // the vendored OTel instrumentation. The `batch` runs off a deferred tick with no obvious network\n // peer, so it gets no kind.\n [SENTRY_KIND]: operation === 'batch' ? undefined : 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n [DB_OPERATION_NAME]: operation,\n // A loader batches and caches one entity type, so it is the closest thing dataloader has to a\n // collection. Unnamed loaders report nothing.\n [DB_COLLECTION_NAME]: loader?.name ?? undefined,\n [CACHE_KEY]: getCacheKey(keyArg),\n },\n };\n}\n\nconst _dataloaderIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n DEBUG_BUILD && debug.log('[instrumentation:dataloader] subscribing to dataloader tracing channels');\n\n waitForTracingChannelBinding(() => {\n subscribeConstruct();\n subscribeLoad();\n subscribeSimpleOperation(CHANNELS.DATALOADER_LOAD_MANY, 'loadMany');\n subscribeSimpleOperation(CHANNELS.DATALOADER_PRIME, 'prime');\n subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR, 'clear');\n subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR_ALL, 'clearAll');\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Wraps the user's `batchLoadFn` (constructor arg 0) so the batch span opens when it runs on the\n * deferred dispatch tick. The span links back to the `load` calls that populated the batch.\n */\nfunction subscribeConstruct(): void {\n diagnosticsChannel\n .tracingChannel<DataLoaderChannelContext>(CHANNELS.DATALOADER_CONSTRUCT)\n .start.subscribe(message => {\n const data = message as DataLoaderChannelContext;\n const batchLoadFn = data.arguments[0];\n if (typeof batchLoadFn !== 'function' || (batchLoadFn as { [WRAPPED]?: boolean })[WRAPPED]) {\n return;\n }\n\n const original = batchLoadFn as (...args: unknown[]) => unknown;\n const wrapped = function (this: DataLoaderInstance, ...args: unknown[]): unknown {\n // `batchLoadFn` receives the batched keys as its first argument.\n return startSpan({ ...makeSpanOptions(this, 'batch', args[0]), links: this._batch?.spanLinks }, () =>\n original.apply(this, args),\n );\n };\n (wrapped as { [WRAPPED]?: boolean })[WRAPPED] = true;\n data.arguments[0] = wrapped;\n });\n}\n\n/**\n * `load` is a cache read that additionally records its span so the batch it feeds into can link back.\n *\n * The span itself is `Async` (ends on `asyncEnd`, so its duration covers the awaited load). But the\n * link has to be recorded earlier, on the synchronous `end` (fired when `load` returns): the batch\n * dispatches on a deferred tick and reads `spanLinks` at batch-span creation, which happens BEFORE\n * `load`'s promise resolves (`asyncEnd`) — so recording at span end would be too late and drop the\n * link. The sync `end` runs after `dataloader` has assigned `this._batch` in `load`'s body and before\n * the deferred dispatch, so the link lands in time.\n */\nfunction subscribeLoad(): void {\n const channel = diagnosticsChannel.tracingChannel<DataLoaderChannelContext>(CHANNELS.DATALOADER_LOAD);\n\n bindTracingChannelToSpan(channel, data => startInactiveSpanFor(data.self, 'load', data.arguments[0]));\n\n channel.end.subscribe(message => {\n const data = message as TracingChannelPayloadWithSpan<DataLoaderChannelContext>;\n const span = data._sentrySpan;\n const batch = data.self?._batch;\n if (span && batch && span.isRecording()) {\n (batch.spanLinks ??= []).push({ context: span.spanContext() });\n }\n });\n}\n\nfunction subscribeSimpleOperation(channelName: ChannelName, operation: Operation): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<DataLoaderChannelContext>(channelName), data =>\n startInactiveSpanFor(data.self, operation, data.arguments[0]),\n );\n}\n\nfunction startInactiveSpanFor(loader: DataLoaderInstance | undefined, operation: Operation, keyArg?: unknown): Span {\n return startInactiveSpan(makeSpanOptions(loader, operation, keyArg));\n}\n\n/**\n * Diagnostics-channel-based `dataloader` integration.\n *\n * Subscribes to the `orchestrion:dataloader:*` diagnostics_channels that Sentry's code\n * transform injects into `dataloader`'s constructor and prototype methods. Requires the Sentry\n * runtime hook or bundler plugin to be active.\n */\nexport const dataloaderIntegration = defineIntegration(_dataloaderIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { genericPoolModuleNames } from '../orchestrion/config/generic-pool';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// Same name as the OTel integration by design — when enabled, the OTel\n// 'GenericPool' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'GenericPool' as const;\n\nconst _genericPoolIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, genericPoolModuleNames, instrumentGenericPool, []);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Diagnostics-channel-based generic-pool integration. Subscribes to\n * `orchestrion:generic-pool:acquire` (injected into `generic-pool/lib/Pool.js`'s\n * `Pool.prototype.acquire`). Creates a `generic-pool.acquire` span for each\n * acquisition. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const genericPoolIntegration = defineIntegration(_genericPoolIntegration);\n\nfunction instrumentGenericPool(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.GENERIC_POOL_ACQUIRE),\n () =>\n startInactiveSpan({\n name: 'generic-pool.acquire',\n attributes: {\n [SENTRY_OP]: DB,\n [SENTRY_ORIGIN]: 'auto.db.generic_pool',\n },\n }),\n );\n}\n","import type { MonitorConfig } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n debug,\n isThenable,\n startNewTrace,\n stringMatchesSomePattern,\n withMonitor,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport * as diagnosticsChannel from './diagnosticsChannel';\n\nexport type AnyFn = (this: unknown, ...args: unknown[]) => unknown;\n\n// Set by `Sentry.cron.instrumentCron`, `instrumentNodeCron`, `instrumentNodeSchedule` and `wrapScheduledJob`, which already\n// send check-ins.\nconst MONITORED = Symbol.for('sentry.cron.monitored');\n\n/**\n * Calls `onJob` with the arguments of each call on a scheduler's job-creation channel, so it can wrap the job.\n * Errors are logged and the job is created unmonitored.\n */\nexport function subscribeToJobCreation(\n channelName: string,\n integrationName: string,\n onJob: (args: unknown[]) => void,\n): void {\n diagnosticsChannel.tracingChannel<{ arguments: unknown[] }>(channelName).start.subscribe(message => {\n try {\n onJob((message as { arguments: unknown[] }).arguments);\n } catch (e) {\n DEBUG_BUILD && debug.error(`[${integrationName}] Failed to set up the cron monitor:`, e);\n }\n });\n}\n\n/** A call on a schedule-change channel: its arguments, the job it was called on, and what it returned. */\nexport interface ScheduleChange {\n arguments: unknown[];\n self?: unknown;\n result?: unknown;\n}\n\n/**\n * Calls `onChange` after each call on a scheduler's schedule-change channel, so it can update the job's monitor config.\n * `onStart` gets the same object before the call. Errors are logged and the job keeps its config.\n */\nexport function subscribeToScheduleChange(\n channelName: string,\n integrationName: string,\n onChange: (change: ScheduleChange) => void,\n onStart?: (change: ScheduleChange) => void,\n): void {\n const channel = diagnosticsChannel.tracingChannel<ScheduleChange>(channelName);\n const handle = (handler: (change: ScheduleChange) => void) => (message: unknown) => {\n try {\n handler(message as ScheduleChange);\n } catch (e) {\n DEBUG_BUILD && debug.error(`[${integrationName}] Failed to update the cron monitor:`, e);\n }\n };\n if (onStart) {\n channel.start.subscribe(handle(onStart));\n }\n channel.end.subscribe(handle(onChange));\n}\n\n/** Whether a job is named, not excluded, and not already monitored by `Sentry.cron.instrument*` or `wrapScheduledJob`. */\nexport function shouldMonitorJob(\n name: unknown,\n job: unknown,\n excludeJobs: Array<string | RegExp> | undefined,\n): name is string {\n return (\n typeof name === 'string' &&\n !!name &&\n typeof job === 'function' &&\n !(job as { [MONITORED]?: boolean })[MONITORED] &&\n !stringMatchesSomePattern(name, excludeJobs, true)\n );\n}\n\n/**\n * The library that parses a scheduler's cron expressions: `node-cron`, `cron` (also behind `@nestjs/schedule`), or\n * `cron-parser` 4 or 5 (behind `node-schedule` and BullMQ).\n */\nexport type CronDialect = 'node-cron' | 'cron' | 'cron-parser';\n\nconst COMMON_NICKNAMES: Record<string, string> = {\n '@yearly': '0 0 1 1 *',\n '@monthly': '0 0 1 * *',\n '@weekly': '0 0 * * 0',\n '@daily': '0 0 * * *',\n '@hourly': '0 * * * *',\n};\n\nconst NICKNAMES: Record<CronDialect, Record<string, string>> = {\n 'node-cron': { ...COMMON_NICKNAMES, '@annually': '0 0 1 1 *', '@midnight': '0 0 * * *' },\n cron: { ...COMMON_NICKNAMES, '@minutely': '* * * * *', '@weekdays': '0 0 * * 1-5', '@weekends': '0 0 * * 0,6' },\n 'cron-parser': COMMON_NICKNAMES,\n};\n\nconst MONTHS = [\n 'january',\n 'february',\n 'march',\n 'april',\n 'may',\n 'june',\n 'july',\n 'august',\n 'september',\n 'october',\n 'november',\n 'december',\n];\nconst WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n\n/**\n * The Sentry monitor config for a cron expression, or `undefined` if Sentry would read it differently.\n * Without a `timezone`, the server's time zone is used, like the schedulers do.\n */\nexport function cronExpressionToMonitorConfig(\n expression: string,\n timezone: unknown,\n dialect: CronDialect,\n): MonitorConfig | undefined {\n const trimmed = expression.trim();\n const fields = (NICKNAMES[dialect][trimmed.toLowerCase()] || trimmed).split(/\\s+/);\n\n // Sentry schedules have minute granularity, so only a fixed second can be dropped.\n if (fields.length === 6 && /^\\d+$/.test(fields[0] as string)) {\n fields.shift();\n }\n if (fields.length !== 5 || !fields.every(field => /^[\\d*,/a-z#-]+$/i.test(field))) {\n return undefined;\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string];\n const monthNumbers = replaceNames(month, MONTHS, 1, dialect);\n const weekdayNames = replaceNames(dayOfWeek, WEEKDAYS, 0, dialect);\n const weekdayNumbers = dialect === 'node-cron' ? endRangesOnSundayAsSeven(weekdayNames) : weekdayNames;\n const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers];\n if (\n crontab.some(\n (field, index) =>\n hasUnsupportedCharacter(field, dialect === 'cron-parser' ? CRON_PARSER_DAY_TOKENS[index] : undefined) ||\n hasReversedRange(field) ||\n hasSteppedSingleValueRange(field),\n ) ||\n !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) ||\n !hasDayInSelectedMonths(dayOfMonth, monthNumbers)\n ) {\n return undefined;\n }\n\n const sentryTimezone = toSentryTimezone(typeof timezone === 'string' && timezone ? timezone : undefined);\n if (!sentryTimezone) {\n return undefined;\n }\n\n return { schedule: { type: 'crontab', value: crontab.join(' ') }, timezone: sentryTimezone };\n}\n\n// `cron-parser` reads these like Sentry: `L` is the last day of the month, `5L` the last Friday, `5#2` the second Friday.\nconst CRON_PARSER_DAY_TOKENS = [undefined, undefined, /^L$/, undefined, /^[0-7](?:L|#[1-5])$/];\n\nfunction hasUnsupportedCharacter(field: string, dayToken: RegExp | undefined): boolean {\n return field.split(',').some(part => /[a-z#]/i.test(part) && !dayToken?.test(part));\n}\n\n// Sentry needs both day fields to match when one starts with `*`, and either otherwise.\nfunction isSameDayMatching(dayOfMonth: string, dayOfWeek: string, dialect: CronDialect): boolean {\n const monthDays = parseDayField(dayOfMonth, 1, 31);\n const weekdays = parseDayField(dayOfWeek, 0, 7);\n if (!monthDays || !weekdays) {\n return false;\n }\n const sentryNeedsBoth = dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*');\n if (dialect === 'cron-parser') {\n return isSameDayMatchingInCronParser(dayOfMonth, dayOfWeek, monthDays, weekdays, sentryNeedsBoth);\n }\n // `cron` needs either day field to match, but ignores one that lists every day, like `1-31` or `sun-sat`.\n const allMonthDays = monthDays.days === 31;\n const allWeekdays = weekdays.days === 7;\n const schedulerNeedsBoth = dialect === 'node-cron' || allMonthDays || allWeekdays;\n return (allMonthDays && allWeekdays) || schedulerNeedsBoth === sentryNeedsBoth;\n}\n\n// `cron-parser` ignores a day-of-week with 8 values, and a day-of-month with at least as many values as the month has\n// days (29 in February), duplicates included. Then only the other field has to match, and otherwise either.\nfunction isSameDayMatchingInCronParser(\n dayOfMonth: string,\n dayOfWeek: string,\n monthDays: DayField,\n weekdays: DayField,\n sentryNeedsBoth: boolean,\n): boolean {\n // `cron-parser` 4 ignores a restricted day of month when the day of week has a `#`.\n if (weekdays.cronParserAddsSunday || (dayOfWeek.includes('#') && (dayOfMonth !== '*' || dayOfWeek.includes(',')))) {\n return false;\n }\n if (dayOfWeek === '*') {\n return true;\n }\n if (dayOfMonth === '*') {\n return weekdays.cronParserValues !== 8 || weekdays.days === 7;\n }\n return !sentryNeedsBoth && monthDays.cronParserValues < 29 && weekdays.cronParserValues !== 8;\n}\n\nconst DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n// Sentry rejects a day of month that none of the months have, like `31` in `0 9 31 2,4 *`. The schedulers run these on\n// the day of week or not at all.\nfunction hasDayInSelectedMonths(dayOfMonth: string, month: string): boolean {\n const days = parseDayField(dayOfMonth, 1, 31)?.values;\n const months = parseDayField(month, 1, 12)?.values;\n if (!days || !months) {\n return false;\n }\n return !days.size || Math.min(...days) <= Math.max(...[...months].map(m => DAYS_IN_MONTH[m - 1] as number));\n}\n\ninterface DayField {\n values: Set<number>;\n days: number;\n cronParserValues: number;\n cronParserAddsSunday: boolean;\n}\n\nfunction parseDayField(field: string, low: number, high: number): DayField | undefined {\n const days = new Set<number>();\n let cronParserValues = 0;\n let cronParserListsSunday = false;\n for (const part of field.split(',')) {\n // `L`, `5L` and `5#2` stand for one day each. Only the `cron-parser` dialect lets them through.\n if (/^(?:L|[0-7](?:L|#[1-5]))$/.test(part)) {\n cronParserValues++;\n continue;\n }\n const match = /^(?:(\\*)|(\\d+)(?:-(\\d+))?)(?:\\/(\\d+))?$/.exec(part);\n if (!match) {\n return undefined;\n }\n const [, wildcard, from, to, step] = match;\n const lower = wildcard ? low : Number(from);\n const upper = wildcard || (step && !to) ? high : Number(to ?? from);\n const increment = Number(step ?? 1);\n if (!increment || lower < low || upper > high || lower > upper) {\n return undefined;\n }\n // `cron-parser` starts a weekday range that ends on 7 with a Sunday, whatever the step.\n if (high === 7 && upper === 7 && lower !== 0 && (to || step)) {\n cronParserValues++;\n cronParserListsSunday = true;\n }\n for (let day = lower; day <= upper; day += increment) {\n days.add(high === 7 && day === 7 ? 0 : day);\n cronParserValues++;\n }\n }\n return {\n values: days,\n days: days.size,\n cronParserValues,\n cronParserAddsSunday: cronParserListsSunday && !days.has(0),\n };\n}\n\nfunction replaceNames(field: string, names: string[], offset: number, dialect: CronDialect): string {\n return field.replace(/[a-z]+/gi, word => {\n const lowerCase = word.toLowerCase();\n const index = names.findIndex(\n name => lowerCase === name.slice(0, 3) || (dialect === 'node-cron' && lowerCase === name),\n );\n return index === -1 ? word : String(index + offset);\n });\n}\n\n// `sat-sun` is `6-0`, which node-cron 4.6+ runs on Saturday and Sunday. Sentry only accepts it as `6-7`. The other\n// schedulers reject it.\nfunction endRangesOnSundayAsSeven(field: string): string {\n return field\n .split(',')\n .map(part => part.replace(/^(\\d+)-0(?!\\d)/, (range, start: string) => (Number(start) ? `${start}-7` : range)))\n .join(',');\n}\n\n// node-cron 4.6+ wraps these around (`22-2` hours), earlier versions swap them, the other schedulers reject them,\n// and so does Sentry.\nfunction hasReversedRange(field: string): boolean {\n return field.split(',').some(part => {\n const range = /^(\\d+)-(\\d+)/.exec(part);\n return !!range && Number(range[1]) > Number(range[2]);\n });\n}\n\n// The schedulers run `13-13/3` only on the 13th, but Sentry reads it as `13/3`.\nfunction hasSteppedSingleValueRange(field: string): boolean {\n return field.split(',').some(part => {\n const range = /^(\\d+)-(\\d+)\\//.exec(part);\n return !!range && Number(range[1]) === Number(range[2]);\n });\n}\n\nfunction toSentryTimezone(timezone: string | undefined): string | undefined {\n if (timezone && /^(?:utc|gmt)?[+-]/i.test(timezone)) {\n return undefined;\n }\n try {\n const resolved = new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone;\n return resolved && resolved !== 'Etc/Unknown' ? resolved : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst monitorConfigs = new WeakMap<AnyFn, MonitorConfig | undefined>();\n\n/**\n * Wraps a scheduled job with check-ins. Errors are captured, because schedulers catch them, and rethrown.\n * Jobs without a monitor config send no check-ins.\n */\nexport function wrapScheduledJob(\n func: AnyFn,\n monitorSlug: string,\n monitorConfig: MonitorConfig | undefined,\n mechanismType: string,\n): AnyFn {\n const captureAndRethrow = (error: unknown): never => {\n captureException(error, { mechanism: { handled: false, type: mechanismType } });\n throw error;\n };\n\n const wrapped = function (this: unknown, ...args: unknown[]): unknown {\n const run = (): unknown => {\n try {\n const result: unknown = func.apply(this, args);\n return isThenable(result) ? result.then(undefined, captureAndRethrow) : result;\n } catch (e) {\n return captureAndRethrow(e);\n }\n };\n const currentConfig = monitorConfigs.get(wrapped);\n return startNewTrace(() => (currentConfig ? withMonitor(monitorSlug, run, currentConfig) : run()));\n };\n monitorConfigs.set(wrapped, monitorConfig);\n addNonEnumerableProperty(wrapped, MONITORED, true);\n return wrapped;\n}\n\n/** Sets the monitor config a job from `wrapScheduledJob` sends on its next runs. Other functions are ignored. */\nexport function updateMonitorConfig(job: unknown, monitorConfig: MonitorConfig | undefined): void {\n if (typeof job === 'function' && monitorConfigs.has(job as AnyFn)) {\n monitorConfigs.set(job as AnyFn, monitorConfig);\n }\n}\n","import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { cronModuleNames } from '../orchestrion/config/cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'CronJob' as const;\n\nexport interface CronJobIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _cronJobIntegration = ((options: CronJobIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, cronModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every `CronJob` of the `cron` package (4.3+) that has a `name`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const cronJobIntegration = defineIntegration(_cronJobIntegration);\n\nfunction subscribe(options: CronJobIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.CRON_JOB_CONSTRUCTOR, INTEGRATION_NAME, args => wrapJob(args, options));\n subscribeToScheduleChange(CHANNELS.CRON_JOB_SET_TIME, INTEGRATION_NAME, onSetTime);\n}\n\n/** Sets the new time's config after `job.setTime(cronTime)`. Without one, the job doesn't check in. */\nexport function onSetTime({ arguments: [cronTime], self }: ScheduleChange): void {\n const job = self as { cronTime?: unknown; _callbacks?: unknown[] } | undefined;\n // `setTime` throws and keeps the old time when it isn't given a `CronTime`.\n if (!job || job.cronTime !== cronTime) {\n return;\n }\n const { source, timeZone, utcOffset } = cronTime as { source?: unknown; timeZone?: unknown; utcOffset?: unknown };\n const monitorConfig: MonitorConfig | undefined =\n typeof source === 'string' && utcOffset == null\n ? cronExpressionToMonitorConfig(source, timeZone, 'cron')\n : undefined;\n for (const callback of job._callbacks || []) {\n updateMonitorConfig(callback, monitorConfig);\n }\n}\n\n// `new CronJob(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, ..., name)`\nfunction wrapJob(args: unknown[], options: CronJobIntegrationOptions): void {\n const [cronTime, onTick, , , timeZone] = args;\n const utcOffset = args[7];\n const name = args[11];\n if (typeof cronTime !== 'string' || !shouldMonitorJob(name, onTick, options.excludeJobs)) {\n return;\n }\n const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, 'cron') : undefined;\n args[1] = wrapScheduledJob(onTick as AnyFn, name, monitorConfig, 'auto.function.cron');\n}\n","import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeCronModuleNames } from '../orchestrion/config/node-cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeCron' as const;\n\nexport interface NodeCronIntegrationOptions {\n /** Task names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeCronIntegration = ((options: NodeCronIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeCronModuleNames, subscribe, [options], {\n // The binding only parents spans, and this integration creates none.\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-cron` task, with its schedule as the monitor config.\n * The monitor slug is the task's `name` option. Tasks without a name, or with a schedule Sentry can't express, are not\n * monitored.\n */\nexport const nodeCronIntegration = defineIntegration(_nodeCronIntegration);\n\nfunction subscribe(options: NodeCronIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.NODE_CRON_CREATE_TASK, INTEGRATION_NAME, args => wrapTask(args, options));\n subscribeToJobCreation(CHANNELS.NODE_CRON_V4_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron4),\n );\n subscribeToJobCreation(CHANNELS.NODE_CRON_V3_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron3),\n );\n}\n\n// `createTask(expression, func, options)`\nfunction wrapTask(\n args: unknown[],\n options: NodeCronIntegrationOptions,\n isReadAlike?: (expression: string) => boolean,\n): void {\n const [expression, func, taskOptions] = args;\n const { name, timezone } = (taskOptions || {}) as { name?: unknown; timezone?: unknown };\n if (!shouldMonitorJob(name, func, options.excludeJobs)) {\n return;\n }\n const monitorConfig = getMonitorConfig(String(expression), timezone, isReadAlike);\n args[1] = wrapScheduledJob(func as AnyFn, name, monitorConfig, 'auto.function.node-cron');\n}\n\n/** The monitor config for a task, or `undefined` if `isReadAlike` says this node-cron version reads it differently. */\nexport function getMonitorConfig(\n expression: string,\n timezone: unknown,\n isReadAlike?: (expression: string) => boolean,\n): MonitorConfig | undefined {\n return isReadAlike && !isReadAlike(expression)\n ? undefined\n : cronExpressionToMonitorConfig(expression, timezone, 'node-cron');\n}\n\nconst NODE_CRON_3_FIELD_MINIMUMS = [0, 0, 1, 1, 0];\n\n/**\n * node-cron before 4.6 reads `7` as `0` and swaps reversed ranges, so it runs `sat-sun`, `6-0` and `6-7` every day.\n * It also reads a step without a range, like `5/10`, as its start. Returns `false` where that could differ.\n */\nexport function isReadAlikeByNodeCron4(expression: string): boolean {\n const fields = expression.trim().split(/\\s+/);\n const weekday = fields[fields.length - 1] || '';\n return (\n !(weekday.includes('-') && (weekday.includes('7') || /-(?:0|sun)/i.test(weekday))) &&\n !fields.some(field => field.split(',').some(part => /^[a-z\\d]+\\//i.test(part)))\n );\n}\n\n/**\n * node-cron 3 keeps the values of a stepped field that are multiples of the step (`*\\/2` days are 2, 4, ...)\n * and reads weekday ranges like node-cron 4 before 4.6. Returns `false` where that differs from standard cron.\n */\nexport function isReadAlikeByNodeCron3(expression: string): boolean {\n const fields = expression.trim().split(/\\s+/);\n const minimums = fields.length === 6 ? [0, ...NODE_CRON_3_FIELD_MINIMUMS] : NODE_CRON_3_FIELD_MINIMUMS;\n return (\n isReadAlikeByNodeCron4(expression) &&\n fields.every((field, index) => {\n if (!field.includes('/')) {\n return true;\n }\n const match = /^(?:\\*|(\\d+)-\\d+)\\/(\\d+)$/.exec(field);\n return !!match && Number(match[1] ?? minimums[index]) % Number(match[2]) === 0;\n })\n );\n}\n","import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeScheduleModuleNames } from '../orchestrion/config/node-schedule';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeSchedule' as const;\n\nexport interface NodeScheduleIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeScheduleIntegration = ((options: NodeScheduleIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeScheduleModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-schedule` job, whether it's created with `scheduleJob` or `new Job()`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const nodeScheduleIntegration = defineIntegration(_nodeScheduleIntegration);\n\nfunction subscribe(options: NodeScheduleIntegrationOptions): void {\n subscribeToScheduleChange(CHANNELS.NODE_SCHEDULE_SCHEDULE, INTEGRATION_NAME, onSchedule, change =>\n beforeSchedule(change, options),\n );\n}\n\ninterface Job {\n name?: unknown;\n job?: unknown;\n nextInvocation?: () => unknown;\n}\n\n// The name node-schedule gives jobs created without one.\nconst ANONYMOUS_NAME = /^<Anonymous Job \\d+[ >]/;\n\n// `job.schedule(spec)` calls that add to runs the job already has pending, rather than replace them.\nconst addsToPendingRuns = new WeakSet<ScheduleChange>();\n\n/** Wraps a named job's method before `job.schedule(spec)` with a recurring spec, unless it's already wrapped. */\nexport function beforeSchedule(change: ScheduleChange, options: NodeScheduleIntegrationOptions): void {\n const job = change.self as Job | undefined;\n if (!job) {\n return;\n }\n if (typeof job.nextInvocation === 'function' && job.nextInvocation() != null) {\n addsToPendingRuns.add(change);\n }\n const name = typeof job.name === 'string' && !ANONYMOUS_NAME.test(job.name) ? job.name : undefined;\n if (isOneOffSpec(change.arguments[0]) || !shouldMonitorJob(name, job.job, options.excludeJobs)) {\n return;\n }\n job.job = wrapScheduledJob(job.job as AnyFn, name, undefined, 'auto.function.node-schedule');\n}\n\n/**\n * Sets the spec's config after `job.schedule(spec)`. Without one, from a spec Crons can't express or a job that also\n * keeps runs from an earlier spec, the job doesn't check in.\n */\nexport function onSchedule(change: ScheduleChange): void {\n // `schedule` returns false when it scheduled nothing, and `reschedule` then keeps the old schedule.\n if (change.result === true) {\n const job = change.self as Job | undefined;\n updateMonitorConfig(job?.job, addsToPendingRuns.has(change) ? undefined : getMonitorConfig(change.arguments[0]));\n }\n}\n\n/** Whether node-schedule runs a job with this spec once: a `Date`, a timestamp, or a date string. */\nexport function isOneOffSpec(spec: unknown): boolean {\n const { rule } = (spec || {}) as { rule?: unknown };\n const when = typeof spec === 'object' && rule ? rule : spec;\n if (typeof when === 'string') {\n // `Date.parse` also accepts some crons, like `0 9 * * *`.\n return !isCronShaped(when) && !Number.isNaN(Date.parse(when));\n }\n return when instanceof Date || typeof when === 'number';\n}\n\nfunction isCronShaped(value: string): boolean {\n const fields = value.trim().split(/\\s+/);\n return (\n /^@[a-z]+$/i.test(value.trim()) ||\n ((fields.length === 5 || fields.length === 6) && fields.every(field => /^[\\d*,/?#a-z-]+$/i.test(field)))\n );\n}\n\n// Only cron strings convert; recurrence rules and rules limited by `start` or `end` don't.\nexport function getMonitorConfig(spec: unknown): MonitorConfig | undefined {\n if (typeof spec === 'string') {\n return cronExpressionToMonitorConfig(spec, undefined, 'cron-parser');\n }\n const { rule, tz, start, end } = (spec || {}) as { rule?: unknown; tz?: unknown; start?: unknown; end?: unknown };\n return typeof rule === 'string' && !start && !end\n ? cronExpressionToMonitorConfig(rule, tz, 'cron-parser')\n : undefined;\n}\n","import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n defineIntegration,\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport {\n addPrivateRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getAbortSignal,\n getCallAbortSignal,\n resolveChatParams,\n} from '../ai/google-genai';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport { instrumentStream } from '../ai/google-genai/streaming';\nimport type { GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { googleGenAiModuleNames } from '../orchestrion/config/google-genai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Google_GenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Google_GenAI' as const;\n\nconst ORIGIN = 'auto.ai.google_genai';\n\n// Each instrumented method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT, operation: 'generate_content' },\n { channel: CHANNELS.GOOGLE_GENAI_EMBED_CONTENT, operation: 'embeddings' },\n { channel: CHANNELS.GOOGLE_GENAI_CHAT, operation: 'chat' },\n { channel: CHANNELS.GOOGLE_GENAI_DECIDE, operation: 'decide' },\n] as const;\n\nconst _googleGenAIIntegration = ((options: GoogleGenAIOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, googleGenAiModuleNames, instrumentGoogleGenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGoogleGenai(options: GoogleGenAIOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n const params = resolveChatParams(\n operation,\n data.arguments?.[0] as Record<string, unknown> | undefined,\n data.self,\n );\n markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));\n }\n // Embeddings responses carry no content attributes.\n if (operation !== 'embeddings') {\n addResponseAttributes(\n span,\n data.result as GoogleGenAIResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n operation,\n );\n }\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `chat.sendMessage()`/`sendMessageStream()` internally call `Models.generateContent(Stream)`, which\n // publishes the `generate-content` channel while the chat span is active. Skip that nested event so a\n // chat call yields a single `gen_ai.chat` span instead of a chat span wrapping a generate_content one.\n if (operation !== 'chat') {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const {\n attributes: { [SENTRY_OP]: op, [SENTRY_ORIGIN]: origin },\n } = spanToJSON(activeSpan);\n if (origin === ORIGIN && op === 'gen_ai.chat') {\n return undefined;\n }\n }\n }\n\n const args = data.arguments ?? [];\n // `chat.sendMessage()` carries no config of its own unless the caller passes one, so recover the\n // one `chats.create()` left on the chat instance that the transform stashed in `data.self`.\n const params = resolveChatParams(operation, args[0] as Record<string, unknown> | undefined, data.self);\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * Only the streaming methods (`generateContentStream`/`sendMessageStream`) resolve to an async iterable.\n * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the\n * span when iteration finishes.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const params = resolveChatParams(operation, data.arguments?.[0] as Record<string, unknown> | undefined, data.self);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs ?? false,\n getAbortSignal(params),\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based Google GenAI integration. Subscribes to the\n * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`\n * (`generateContent`/`generateContentStream`/`embedContent`), `Chat`\n * (`sendMessage`/`sendMessageStream`) and decisions (`create`) methods, so it requires the Sentry\n * runtime hook or bundler plugin.\n */\nexport const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);\n","// Shared by both graphql paths (orchestrion for v14–16, diagnostics channels for >= 17) so they emit\n// identical spans.\n\nexport const ORIGIN = 'auto.graphql.graphql';\n\nexport const SPAN_NAME_PARSE = 'graphql.parse';\nexport const SPAN_NAME_VALIDATE = 'graphql.validate';\nexport const SPAN_NAME_EXECUTE = 'graphql.execute';\nexport const SPAN_NAME_SUBSCRIBE = 'graphql.subscribe';\nexport const SPAN_NAME_RESOLVE = 'graphql.resolve';\n\nexport { GRAPHQL_PROCESSING_TYPE } from '@sentry/conventions/attributes';\n\nexport const PROCESSING_TYPE_PARSE = 'parse';\nexport const PROCESSING_TYPE_VALIDATE = 'validate';\nexport const PROCESSING_TYPE_EXECUTE = 'execute';\nexport const PROCESSING_TYPE_RESOLVE = 'resolve';\n\n// Field-level resolver-span attributes; not in `@sentry/conventions`.\nexport const GRAPHQL_FIELD_NAME = 'graphql.field.name';\nexport const GRAPHQL_FIELD_PATH = 'graphql.field.path';\nexport const GRAPHQL_FIELD_TYPE = 'graphql.field.type';\nexport const GRAPHQL_PARENT_NAME = 'graphql.parent.name';\n\n// `Symbol.for` keys shared with any co-resident OTel graphql instrumentation on purpose: the paths are\n// mutually exclusive at runtime, and reusing the key keeps nested-execute detection and resolver\n// parenting consistent if both ever load.\nexport const GRAPHQL_DATA_SYMBOL = Symbol.for('opentelemetry.graphql_data');\nexport const GRAPHQL_PATCHED_SYMBOL = Symbol.for('opentelemetry.patched');\n","import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_GRAPHQL_OPERATION } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, getRootSpan, spanToJSON } from '@sentry/core';\nimport type { GraphqlDocumentNode, GraphqlToken } from './types';\n\n// Same key the OTel path uses, so renames stay consistent across both.\nconst ORIGINAL_DESCRIPTION_ATTRIBUTE = 'original-description';\n\n// graphql-js token kinds whose values may carry user data (literal arguments). We\n// replace them in the serialized document so raw inline values can never reach\n// `graphql.document`. Mirrors the legacy OTel instrumentation's redaction set.\nconst REDACTED_LITERAL_KINDS = new Set(['Int', 'Float', 'String', 'BlockString']);\n\n/**\n * Record the operation name(s) on the enclosing root span and, unless span streaming is enabled,\n * rename it to include them, e.g. `GET /graphql (query GetUser)`.\n */\nexport function renameRootSpanWithOperation(span: Span, operationType: string, operationName?: string): void {\n const rootSpan = getRootSpan(span);\n // Nothing to rename if the operation span is itself the root (graphql ran outside any span).\n if (rootSpan === span) {\n return;\n }\n\n const rootSpanJson = spanToJSON(rootSpan);\n\n const newOperation = operationName ? `${operationType} ${operationName}` : operationType;\n\n // A single operation is stored as a string, multiple as an array.\n const existingOperations = rootSpanJson.attributes[SENTRY_GRAPHQL_OPERATION];\n let operations: string | string[];\n if (Array.isArray(existingOperations)) {\n operations = [...(existingOperations as string[]), newOperation];\n } else if (typeof existingOperations === 'string') {\n operations = [existingOperations, newOperation];\n } else {\n operations = newOperation;\n }\n rootSpan.setAttribute(SENTRY_GRAPHQL_OPERATION, operations);\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return;\n }\n\n // Keep the pre-rename name so repeated renames don't compound.\n const originalDescription =\n (rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE] as string | undefined) ?? rootSpanJson.name;\n if (!rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE]) {\n rootSpan.setAttribute(ORIGINAL_DESCRIPTION_ATTRIBUTE, originalDescription);\n }\n\n // `updateName` stamps `source: 'custom'`, so re-set the original source afterwards to preserve it.\n const source = rootSpanJson.attributes[SENTRY_SEGMENT_NAME_SOURCE];\n rootSpan.updateName(`${originalDescription} (${getGraphqlOperationNamesFromAttribute(operations)})`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source as SpanAttributeValue);\n}\n\n/** Format the accumulated operations for the root span name: up to 5 sorted names, then `+N`. */\nfunction getGraphqlOperationNamesFromAttribute(attr: string | string[]): string {\n if (Array.isArray(attr)) {\n // oxlint-disable-next-line typescript/require-array-sort-compare\n const sorted = attr.slice().sort();\n if (sorted.length <= 5) {\n return sorted.join(', ');\n }\n\n return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;\n }\n\n return attr;\n}\n\n/**\n * Span name follows the GraphQL semantic conventions: `<operation.type> <operation.name>` when both\n * are available, `<operation.type>` when only the type is, otherwise a static fallback.\n */\nexport function getOperationSpanName(\n operationType: string | undefined,\n operationName: string | undefined,\n fallbackName: string,\n): string {\n if (operationType && operationName) {\n return `${operationType} ${operationName}`;\n }\n if (operationType) {\n return operationType;\n }\n\n return fallbackName;\n}\n\n/** Whether a graphql execution result carries GraphQL errors (returned on `result.errors`). */\nexport function hasResultErrors(result: unknown): boolean {\n if (isObjectLike(result) && 'errors' in result) {\n const errors = (result as { errors?: unknown }).errors;\n\n return Array.isArray(errors) && errors.length > 0;\n }\n\n return false;\n}\n\n/**\n * Serialize a parsed document into `graphql.document` while redacting every literal argument value:\n * the original source text is preserved verbatim except that string/number literal spans are\n * replaced (`\"foo\"` -> `\"*\"`, `42` -> `*`). graphql does not sanitize its channel payload, so this\n * prevents raw inline values (potential PII) from leaving the process. Variable values are never\n * included. Returns `undefined` (rather than throwing) on anything it cannot serialize.\n */\nfunction redactGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n const loc = document?.loc;\n const body = loc?.source?.body;\n if (typeof body !== 'string' || !loc?.startToken) {\n return undefined;\n }\n\n try {\n // Collect literal token spans, then splice them out back-to-front so earlier offsets stay valid.\n const ranges: Array<{ start: number; end: number; kind: string }> = [];\n for (let token: GraphqlToken | null | undefined = loc.startToken; token; token = token.next) {\n if (REDACTED_LITERAL_KINDS.has(token.kind)) {\n ranges.push({ start: token.start, end: token.end, kind: token.kind });\n }\n }\n\n let out = body;\n // Reverse index loop (not `for...of`) so we splice back-to-front; `i` is bounded by the loop, so\n // `ranges[i]` is always present and the `!` just satisfies `noUncheckedIndexedAccess`.\n for (let i = ranges.length - 1; i >= 0; i--) {\n const { start, end, kind } = ranges[i]!;\n const replacement = kind === 'String' || kind === 'BlockString' ? '\"*\"' : '*';\n out = out.slice(0, start) + replacement + out.slice(end);\n }\n\n return out;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the redacted document if `dataCollection.graphQL.document` is enabled, `undefined` otherwise.\n */\nexport function collectGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n if (getClient()?.getDataCollectionOptions().graphQL.document !== true) {\n return undefined;\n }\n return redactGraphqlDocument(document);\n}\n","import type { TracingChannel } from 'node:diagnostics_channel';\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GRAPHQL } from '@sentry/conventions/op';\nimport { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startInactiveSpan } from '@sentry/core';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n GRAPHQL_FIELD_NAME,\n GRAPHQL_FIELD_PATH,\n GRAPHQL_FIELD_TYPE,\n GRAPHQL_PARENT_NAME,\n GRAPHQL_PROCESSING_TYPE,\n ORIGIN,\n PROCESSING_TYPE_EXECUTE,\n PROCESSING_TYPE_PARSE,\n PROCESSING_TYPE_RESOLVE,\n PROCESSING_TYPE_VALIDATE,\n SPAN_NAME_EXECUTE,\n SPAN_NAME_PARSE,\n SPAN_NAME_RESOLVE,\n SPAN_NAME_SUBSCRIBE,\n SPAN_NAME_VALIDATE,\n} from './constants';\nimport type { GraphqlDocumentNode } from './types';\nimport { collectGraphqlDocument, getOperationSpanName, hasResultErrors, renameRootSpanWithOperation } from './utils';\n\n// Channel names published by graphql >= 17.0.0 (see graphql-js `src/diagnostics.ts`).\n// Hardcoded so the subscriber does not have to import graphql — the channels just\n// have to be subscribed to before the user's graphql code publishes.\nexport const GRAPHQL_DC_CHANNEL_PARSE = 'graphql:parse';\nexport const GRAPHQL_DC_CHANNEL_VALIDATE = 'graphql:validate';\nexport const GRAPHQL_DC_CHANNEL_EXECUTE = 'graphql:execute';\nexport const GRAPHQL_DC_CHANNEL_SUBSCRIBE = 'graphql:subscribe';\nexport const GRAPHQL_DC_CHANNEL_RESOLVE = 'graphql:resolve';\n\n/** Context published on the sync-only `graphql:parse` channel. */\nexport interface GraphqlParseData {\n source: string | { body?: string };\n result?: GraphqlDocumentNode;\n error?: unknown;\n}\n\n/** Context published on the sync-only `graphql:validate` channel. */\nexport interface GraphqlValidateData {\n document: GraphqlDocumentNode;\n /** Validation errors returned by validation; an empty array means the document is valid. */\n result?: ReadonlyArray<unknown>;\n error?: unknown;\n}\n\n/**\n * Context published on the `graphql:execute` and `graphql:subscribe` channels.\n *\n * `result` carries an `ExecutionResult` (or, for subscriptions, an async generator); GraphQL errors\n * collected during execution surface on `result.errors` rather than as the channel's `error`\n * lifecycle event, which only fires on an abrupt throw.\n */\nexport interface GraphqlOperationData {\n document: GraphqlDocumentNode;\n operationName?: string;\n operationType?: string;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Context published on the per-field `graphql:resolve` channel.\n *\n * A resolver throw or rejection publishes the `error` lifecycle event here; the same failure also\n * surfaces in the enclosing execution result.\n */\nexport interface GraphqlResolveData {\n fieldName: string;\n parentType: string;\n fieldType: string;\n fieldPath: string;\n /** Whether the field is handled by graphql's default property resolver (vs. a user resolver). */\n isDefaultResolver: boolean;\n alias?: string;\n args?: unknown;\n result?: unknown;\n error?: unknown;\n}\n\n/** Options controlling which graphql channels the subscriber emits spans for. */\nexport interface GraphQLOptions {\n /**\n * Do not create spans for resolvers. Resolver spans are per-field and can be very high volume.\n * Defaults to `true`.\n */\n ignoreResolveSpans?: boolean;\n\n /**\n * When resolver spans are enabled, do not create them for graphql's default property resolver\n * (fields without a user-defined resolver), which are rarely interesting. Defaults to `true`.\n */\n ignoreTrivialResolveSpans?: boolean;\n\n /**\n * Record the operation name(s) on the enclosing root span as `sentry.graphql.operation`, and rename\n * that span to include them, e.g. `GET /graphql` -> `GET /graphql (query GetUser)`. Defaults to\n * `true`; when disabled, neither happens.\n *\n * With span streaming only the attribute is recorded, since the operation name is supplied by the\n * client and would make the root span name high cardinality.\n */\n useOperationNameForRootSpan?: boolean;\n}\n\n/**\n * Platform-provided factory that creates a native tracing channel for the given name. The\n * subscriber binds the span and its lifecycle onto the channel via `bindTracingChannelToSpan`,\n * which propagates the active span through the runtime's async context.\n *\n * Node passes `node:diagnostics_channel`'s `tracingChannel` directly.\n */\nexport type GraphqlTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * Subscribe Sentry span handlers to graphql's diagnostics-channel events\n * (`graphql:parse`, `:validate`, `:execute`, `:subscribe`), published by graphql >= 17.0.0.\n *\n * On older graphql versions the channels are never published to, so the subscribers are inert —\n * there is no double-instrumentation against the vendored OTel patcher, which is gated to `< 17`.\n *\n * The per-field `graphql:resolve` channel is only subscribed when `ignoreResolveSpans` is `false`:\n * resolver spans are per-field and can be extremely high-volume, so they are off by default (matching\n * the legacy OTel path). When enabled, `ignoreTrivialResolveSpans` (default `true`) additionally skips\n * graphql's default property resolver.\n */\nexport function subscribeGraphqlDiagnosticChannels(\n tracingChannel: GraphqlTracingChannelFactory,\n options: GraphQLOptions = {},\n): void {\n const ignoreResolveSpans = options.ignoreResolveSpans !== false;\n const ignoreTrivialResolveSpans = options.ignoreTrivialResolveSpans !== false;\n const useOperationNameForRootSpan = options.useOperationNameForRootSpan !== false;\n\n setupParseChannel(tracingChannel);\n setupValidateChannel(tracingChannel);\n setupOperationChannel(tracingChannel, GRAPHQL_DC_CHANNEL_EXECUTE, SPAN_NAME_EXECUTE, useOperationNameForRootSpan);\n setupOperationChannel(tracingChannel, GRAPHQL_DC_CHANNEL_SUBSCRIBE, SPAN_NAME_SUBSCRIBE, useOperationNameForRootSpan);\n\n if (!ignoreResolveSpans) {\n setupResolveChannel(tracingChannel, ignoreTrivialResolveSpans);\n }\n}\n\nfunction setupParseChannel(tracingChannel: GraphqlTracingChannelFactory): void {\n bindTracingChannelToSpan(tracingChannel<GraphqlParseData>(GRAPHQL_DC_CHANNEL_PARSE), () => {\n const client = getClient();\n\n return startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? `GraphQL ${PROCESSING_TYPE_PARSE}` : SPAN_NAME_PARSE,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_PARSE,\n },\n });\n });\n}\n\nfunction setupValidateChannel(tracingChannel: GraphqlTracingChannelFactory): void {\n bindTracingChannelToSpan(\n tracingChannel<GraphqlValidateData>(GRAPHQL_DC_CHANNEL_VALIDATE),\n data => {\n const client = getClient();\n\n return startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? `GraphQL ${PROCESSING_TYPE_VALIDATE}` : SPAN_NAME_VALIDATE,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_VALIDATE,\n [GRAPHQL_DOCUMENT]: collectGraphqlDocument(data.document),\n },\n });\n },\n {\n beforeSpanEnd: (span, data) => {\n // Validation completes normally even when it returns errors, so flag the span here.\n if (Array.isArray(data.result) && data.result.length > 0) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'invalid_argument' });\n }\n },\n },\n );\n}\n\nfunction setupOperationChannel(\n tracingChannel: GraphqlTracingChannelFactory,\n channelName: string,\n fallbackName: string,\n useOperationNameForRootSpan: boolean,\n): void {\n bindTracingChannelToSpan(\n tracingChannel<GraphqlOperationData>(channelName),\n data => {\n const client = getClient();\n const streamedName = `GraphQL ${data.operationType || PROCESSING_TYPE_EXECUTE}`;\n\n const span = startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? streamedName\n : getOperationSpanName(data.operationType, data.operationName, fallbackName),\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_EXECUTE,\n [GRAPHQL_OPERATION_TYPE]: data.operationType,\n [GRAPHQL_OPERATION_NAME]: data.operationName || undefined,\n [GRAPHQL_DOCUMENT]: collectGraphqlDocument(data.document),\n },\n });\n\n if (useOperationNameForRootSpan && data.operationType) {\n renameRootSpanWithOperation(span, data.operationType, data.operationName);\n }\n\n return span;\n },\n {\n beforeSpanEnd: (span, data) => {\n // GraphQL errors are returned on `result.errors`, not as a thrown error, so flag the span here.\n if (hasResultErrors(data.result)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n },\n );\n}\n\nfunction setupResolveChannel(tracingChannel: GraphqlTracingChannelFactory, ignoreTrivialResolveSpans: boolean): void {\n bindTracingChannelToSpan(tracingChannel<GraphqlResolveData>(GRAPHQL_DC_CHANNEL_RESOLVE), data => {\n // Returning `undefined` opts this field out: no span is created and the active context is left\n // untouched, so the field still resolves under its parent span.\n if (ignoreTrivialResolveSpans && data.isDefaultResolver) {\n return undefined;\n }\n\n const client = getClient();\n\n return startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? `GraphQL ${PROCESSING_TYPE_RESOLVE}`\n : `${SPAN_NAME_RESOLVE} ${data.fieldPath}`,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_RESOLVE,\n [GRAPHQL_FIELD_NAME]: data.fieldName,\n [GRAPHQL_FIELD_PATH]: data.fieldPath,\n [GRAPHQL_FIELD_TYPE]: data.fieldType,\n [GRAPHQL_PARENT_NAME]: data.parentType,\n },\n });\n });\n}\n","/*\n * Resolver-span wrapping for the orchestrion graphql path. graphql v14–16 publishes no per-field\n * `resolve` channel (unlike v17's native one), so the schema's field resolvers are swapped for\n * span-creating proxies under the execute channel's `start` (the \"consumer trick\" — the transform\n * can't target user resolvers, but `execute` receives the schema, so we mutate it before the wrapped\n * call runs). Resolver spans use the same origin/op/field attributes as the native subscriber.\n */\n\nimport { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GRAPHQL } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GRAPHQL_DATA_SYMBOL,\n GRAPHQL_FIELD_NAME,\n GRAPHQL_FIELD_PATH,\n GRAPHQL_FIELD_TYPE,\n GRAPHQL_PARENT_NAME,\n GRAPHQL_PATCHED_SYMBOL,\n GRAPHQL_PROCESSING_TYPE,\n ORIGIN,\n PROCESSING_TYPE_RESOLVE,\n SPAN_NAME_RESOLVE,\n} from './constants';\nimport type {\n DefinitionNode,\n DocumentNode,\n GraphQLFieldResolver,\n GraphQLObjectType,\n GraphQLOutputType,\n GraphQLPath,\n GraphQLResolveInfo,\n GraphQLType,\n GraphQLUnionType,\n GraphqlResolvedConfig,\n Maybe,\n ObjectWithGraphQLData,\n Patched,\n} from './types';\n\nfunction isPromise(value: unknown): value is Promise<unknown> {\n return typeof (value as { then?: unknown } | undefined)?.then === 'function';\n}\n\n/**\n * Walks the query/mutation type tree and swaps each field's `resolve` for a span-creating proxy.\n * Idempotent per type via {@link GRAPHQL_PATCHED_SYMBOL}.\n */\nexport function wrapFields(type: Maybe<GraphQLObjectType & Patched>, getConfig: () => GraphqlResolvedConfig): void {\n if (!type || type[GRAPHQL_PATCHED_SYMBOL]) {\n return;\n }\n\n type[GRAPHQL_PATCHED_SYMBOL] = true;\n const fields = type.getFields();\n\n Object.keys(fields).forEach(key => {\n const field = fields[key];\n if (!field) {\n return;\n }\n\n if (field.resolve) {\n field.resolve = wrapFieldResolver(getConfig, field.resolve);\n }\n\n if (field.type) {\n for (const unwrappedType of unwrapType(field.type)) {\n wrapFields(unwrappedType, getConfig);\n }\n }\n });\n}\n\nexport function wrapFieldResolver(\n getConfig: () => GraphqlResolvedConfig,\n fieldResolver: Maybe<GraphQLFieldResolver & Patched>,\n isDefaultResolver = false,\n): GraphQLFieldResolver & Patched {\n // Return the resolver untouched if it isn't a function or is already a wrapped one — the wrapper we\n // return is marked with `GRAPHQL_PATCHED_SYMBOL` below precisely so it can be detected here. (The\n // guard must test the incoming `fieldResolver`, not the freshly-hoisted `wrappedFieldResolver`.)\n if (typeof fieldResolver !== 'function' || fieldResolver[GRAPHQL_PATCHED_SYMBOL]) {\n return fieldResolver as GraphQLFieldResolver;\n }\n\n function wrappedFieldResolver(\n this: unknown,\n source: unknown,\n args: unknown,\n rawContextValue: unknown,\n info: GraphQLResolveInfo,\n ): unknown {\n if (!fieldResolver) {\n return undefined;\n }\n\n const contextValue = (rawContextValue ?? {}) as ObjectWithGraphQLData;\n const config = getConfig();\n\n // Mirror graphql's own \"trivial resolver\" check: a default resolver that just reads a\n // non-function property is not worth a span.\n if (\n config.ignoreTrivialResolveSpans &&\n isDefaultResolver &&\n (isObjectLike(source) || typeof source === 'function')\n ) {\n const property = (source as Record<string, unknown>)[info.fieldName];\n if (typeof property !== 'function') {\n return fieldResolver.call(this, source, args, contextValue, info);\n }\n }\n\n if (!contextValue[GRAPHQL_DATA_SYMBOL]) {\n return fieldResolver.call(this, source, args, contextValue, info);\n }\n\n const path = pathToArray(info.path);\n const { field, spanAdded } = createFieldIfNotExists(contextValue, info, path);\n const span = field.span;\n\n return withActiveSpan(span, () => {\n try {\n const res = fieldResolver.call(this, source, args, contextValue, info);\n if (isPromise(res)) {\n return res.then(\n r => {\n endResolveSpan(span, spanAdded);\n return r;\n },\n (err: Error) => {\n endResolveSpan(span, spanAdded, err);\n throw err;\n },\n );\n }\n endResolveSpan(span, spanAdded);\n return res;\n } catch (err) {\n endResolveSpan(span, spanAdded, err as Error);\n throw err;\n }\n });\n }\n\n (wrappedFieldResolver as Patched)[GRAPHQL_PATCHED_SYMBOL] = true;\n return wrappedFieldResolver;\n}\n\nfunction endResolveSpan(span: Span, shouldEndSpan: boolean, error?: Error): void {\n if (!shouldEndSpan) {\n return;\n }\n if (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n span.end();\n}\n\nfunction createFieldIfNotExists(\n contextValue: ObjectWithGraphQLData,\n info: GraphQLResolveInfo,\n path: string[],\n): { field: { span: Span }; spanAdded: boolean } {\n const existing = getField(contextValue, path);\n if (existing) {\n return { field: existing, spanAdded: false };\n }\n\n const field = { span: createResolverSpan(info, path, getParentFieldSpan(contextValue, path)) };\n addField(contextValue, path, field);\n return { field, spanAdded: true };\n}\n\nfunction createResolverSpan(info: GraphQLResolveInfo, path: string[], parentSpan?: Span): Span {\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_RESOLVE,\n [GRAPHQL_FIELD_NAME]: info.fieldName,\n [GRAPHQL_FIELD_PATH]: path.join('.'),\n [GRAPHQL_FIELD_TYPE]: info.returnType.toString(),\n [GRAPHQL_PARENT_NAME]: info.parentType.name,\n };\n\n const client = getClient();\n\n return startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? `GraphQL ${PROCESSING_TYPE_RESOLVE}`\n : `${SPAN_NAME_RESOLVE} ${path.join('.')}`,\n attributes,\n parentSpan,\n });\n}\n\nfunction addField(contextValue: ObjectWithGraphQLData, path: string[], field: { span: Span }): void {\n const data = contextValue[GRAPHQL_DATA_SYMBOL];\n if (data) {\n data.fields[path.join('.')] = field;\n }\n}\n\nfunction getField(contextValue: ObjectWithGraphQLData, path: string[]): { span: Span } | undefined {\n return contextValue[GRAPHQL_DATA_SYMBOL]?.fields[path.join('.')];\n}\n\nfunction getParentFieldSpan(contextValue: ObjectWithGraphQLData, path: string[]): Span | undefined {\n for (let i = path.length - 1; i > 0; i--) {\n const field = getField(contextValue, path.slice(0, i));\n if (field) {\n return field.span;\n }\n }\n return contextValue[GRAPHQL_DATA_SYMBOL]?.span;\n}\n\nfunction pathToArray(path: GraphQLPath): string[] {\n const flattened: string[] = [];\n let curr: GraphQLPath | undefined = path;\n while (curr) {\n flattened.push(String(curr.key));\n curr = curr.prev;\n }\n return flattened.reverse();\n}\n\nfunction unwrapType(type: GraphQLOutputType): readonly (GraphQLObjectType & Patched)[] {\n // The structural index signature widens `ofType` to `unknown`, so narrow it back explicitly.\n if ('ofType' in type && type.ofType) {\n return unwrapType(type.ofType as GraphQLOutputType);\n }\n if (isGraphQLUnionType(type)) {\n return type.getTypes();\n }\n if (isGraphQLObjectType(type)) {\n return [type];\n }\n return [];\n}\n\nfunction isGraphQLUnionType(type: GraphQLType): type is GraphQLUnionType {\n return 'getTypes' in type && typeof type.getTypes === 'function';\n}\n\nfunction isGraphQLObjectType(type: GraphQLType): type is GraphQLObjectType {\n return 'getFields' in type && typeof (type as GraphQLObjectType).getFields === 'function';\n}\n\n/**\n * Returns the operation definition for `operationName` (or the first operation) from a parsed\n * document, or `undefined` for schema documents / when no operation is present.\n */\nexport function getOperation(document: DocumentNode, operationName?: Maybe<string>): DefinitionNode | undefined {\n const definitions: readonly DefinitionNode[] | undefined = document?.definitions;\n if (!definitions || !Array.isArray(definitions)) {\n return undefined;\n }\n\n const isOperation = (def: DefinitionNode): boolean =>\n !!def?.operation && ['query', 'mutation', 'subscription'].indexOf(def.operation) !== -1;\n\n if (operationName) {\n return definitions.filter(isOperation).find((def: DefinitionNode) => operationName === def?.name?.value);\n }\n return definitions.find(isOperation);\n}\n","/*\n * Span builders for the orchestrion graphql channels (v14–16). They emit the same spans as the native\n * `diagnostics_channel` subscriber (`../../../graphql/graphql-dc-subscriber.ts`, graphql >= 17) by\n * reusing its `utils` and conventions — only the data source differs: here the payloads are the raw\n * arguments of the injected `parse`/`validate`/`execute` calls rather than graphql's native events.\n */\n\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GRAPHQL } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startInactiveSpan } from '@sentry/core';\nimport type { GraphqlDocumentNode } from './types';\nimport { collectGraphqlDocument, getOperationSpanName, hasResultErrors, renameRootSpanWithOperation } from './utils';\nimport {\n GRAPHQL_DATA_SYMBOL,\n GRAPHQL_PROCESSING_TYPE,\n ORIGIN,\n PROCESSING_TYPE_EXECUTE,\n PROCESSING_TYPE_PARSE,\n PROCESSING_TYPE_VALIDATE,\n SPAN_NAME_EXECUTE,\n SPAN_NAME_PARSE,\n SPAN_NAME_VALIDATE,\n} from './constants';\nimport { getOperation, wrapFields, wrapFieldResolver } from './resolvers';\nimport type {\n DocumentNode,\n GraphQLFieldResolver,\n GraphQLSchema,\n GraphqlResolvedConfig,\n Maybe,\n ObjectWithGraphQLData,\n} from './types';\n\nconst BASE_ATTRIBUTES = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: GRAPHQL,\n} as const;\n\nexport function startParseSpan(): Span {\n const client = getClient();\n\n return startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? `GraphQL ${PROCESSING_TYPE_PARSE}` : SPAN_NAME_PARSE,\n attributes: { ...BASE_ATTRIBUTES, [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_PARSE },\n });\n}\n\n/** `documentAST` is the 2nd argument to `validate(schema, documentAST, …)`. */\nexport function startValidateSpan(documentAST: unknown): Span {\n const client = getClient();\n\n return startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? `GraphQL ${PROCESSING_TYPE_VALIDATE}` : SPAN_NAME_VALIDATE,\n attributes: {\n ...BASE_ATTRIBUTES,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_VALIDATE,\n [GRAPHQL_DOCUMENT]: collectGraphqlDocument(documentAST as GraphqlDocumentNode),\n },\n });\n}\n\n/** `result` is validation's return value: a (possibly empty) array of errors. */\nexport function finalizeValidateSpan(span: Span, result: unknown): void {\n if (Array.isArray(result) && result.length > 0) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'invalid_argument' });\n }\n}\n\n/** Positional slots of a `graphql.execute(schema, document, …)` call (v14/v15 legacy signature). */\nconst enum ExecuteArg {\n SCHEMA = 0,\n DOCUMENT = 1,\n CONTEXT_VALUE = 3,\n OPERATION_NAME = 5,\n FIELD_RESOLVER = 6,\n}\n\ninterface NormalizedExecuteArgs {\n schema?: GraphQLSchema;\n document?: DocumentNode;\n contextValue: ObjectWithGraphQLData;\n operationName?: Maybe<string>;\n fieldResolver?: Maybe<GraphQLFieldResolver>;\n /** Writes `contextValue`/`fieldResolver` mutations back to the live channel `arguments`. */\n writeBack: (contextValue: ObjectWithGraphQLData, fieldResolver: Maybe<GraphQLFieldResolver>) => void;\n}\n\n/**\n * `execute` accepts either a single `ExecutionArgs` object (modern callers, always in v16) or\n * positional args (v14/v15). Both are normalized here; `writeBack` puts mutations onto the correct\n * slot so they reach the real call.\n */\nfunction normalizeExecuteArgs(argsArray: unknown[]): NormalizedExecuteArgs {\n if (argsArray.length >= 2) {\n return {\n schema: argsArray[ExecuteArg.SCHEMA] as GraphQLSchema | undefined,\n document: argsArray[ExecuteArg.DOCUMENT] as DocumentNode | undefined,\n contextValue: argsArray[ExecuteArg.CONTEXT_VALUE] ?? {},\n operationName: argsArray[ExecuteArg.OPERATION_NAME] as Maybe<string>,\n fieldResolver: argsArray[ExecuteArg.FIELD_RESOLVER] as Maybe<GraphQLFieldResolver>,\n writeBack: (contextValue, fieldResolver) => {\n argsArray[ExecuteArg.CONTEXT_VALUE] = contextValue;\n argsArray[ExecuteArg.FIELD_RESOLVER] = fieldResolver;\n },\n };\n }\n\n const obj = (argsArray[0] ?? {}) as {\n schema?: GraphQLSchema;\n document?: DocumentNode;\n contextValue?: unknown;\n operationName?: Maybe<string>;\n fieldResolver?: Maybe<GraphQLFieldResolver>;\n };\n return {\n schema: obj.schema,\n document: obj.document,\n contextValue: obj.contextValue ?? {},\n operationName: obj.operationName,\n fieldResolver: obj.fieldResolver,\n writeBack: (contextValue, fieldResolver) => {\n obj.contextValue = contextValue;\n obj.fieldResolver = fieldResolver;\n },\n };\n}\n\n/**\n * Opens the execute span and, unless resolver spans are disabled, swaps the schema's field resolvers\n * (and the default field resolver) for span-creating proxies — mutating the live `arguments` in place\n * so the wrapped `execute` call runs with them. Always returns a span; the caller guards against\n * throws (see `safe` in `index.ts`).\n */\nexport function startExecuteSpan(\n argsArray: unknown[],\n self: unknown,\n config: GraphqlResolvedConfig,\n getConfig: () => GraphqlResolvedConfig,\n): Span {\n const args = normalizeExecuteArgs(argsArray);\n const { schema, document } = args;\n let { contextValue, fieldResolver } = args;\n\n // Skip resolver wrapping when disabled or when a parent execute already set up this context\n // (nested execute reusing the same contextValue).\n const alreadyInstrumented = !!contextValue[GRAPHQL_DATA_SYMBOL];\n if (!config.ignoreResolveSpans && !alreadyInstrumented) {\n const isUsingDefaultResolver = fieldResolver == null;\n const defaultFieldResolver = (self as { defaultFieldResolver?: GraphQLFieldResolver } | undefined)\n ?.defaultFieldResolver;\n const fieldResolverForExecute = fieldResolver ?? defaultFieldResolver;\n if (fieldResolverForExecute) {\n fieldResolver = wrapFieldResolver(getConfig, fieldResolverForExecute, isUsingDefaultResolver);\n }\n\n if (schema) {\n wrapFields(schema.getQueryType(), getConfig);\n wrapFields(schema.getMutationType(), getConfig);\n }\n }\n\n // v14–16 channels carry only the raw args, so derive the operation from the document (native v17\n // provides `operationType`/`operationName` on the event directly).\n const operation = getOperation(document as DocumentNode, args.operationName);\n const operationType = operation?.operation;\n const operationName = operation?.name?.value ?? args.operationName ?? undefined;\n\n const client = getClient();\n const streamedName = `GraphQL ${operationType || PROCESSING_TYPE_EXECUTE}`;\n\n const span = startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? streamedName\n : getOperationSpanName(operationType, operationName || undefined, SPAN_NAME_EXECUTE),\n attributes: {\n ...BASE_ATTRIBUTES,\n [GRAPHQL_PROCESSING_TYPE]: PROCESSING_TYPE_EXECUTE,\n [GRAPHQL_OPERATION_TYPE]: operationType,\n [GRAPHQL_OPERATION_NAME]: operationName || undefined,\n [GRAPHQL_DOCUMENT]: collectGraphqlDocument(document),\n },\n });\n\n if (config.useOperationNameForRootSpan && operationType) {\n renameRootSpanWithOperation(span, operationType, operationName || undefined);\n }\n\n // The resolver proxies read the execute span (and their own bookkeeping) off this symbol.\n contextValue[GRAPHQL_DATA_SYMBOL] = { source: document, span, fields: {} };\n args.writeBack(contextValue, fieldResolver);\n\n return span;\n}\n\n/** `result` is the settled `ExecutionResult`; GraphQL errors surface on `result.errors`, not a throw. */\nexport function finalizeExecuteSpan(span: Span, result: unknown): void {\n if (hasResultErrors(result)) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, waitForTracingChannelBinding } from '@sentry/core';\nimport { subscribeGraphqlDiagnosticChannels, type GraphQLOptions } from './graphql-dc-subscriber';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { graphqlModuleNames } from '../../orchestrion/config/graphql';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport {\n finalizeExecuteSpan,\n finalizeValidateSpan,\n startExecuteSpan,\n startParseSpan,\n startValidateSpan,\n} from './spans';\nimport type { GraphqlResolvedConfig } from './types';\n\n// Same name as the OTel/native integration by design, so enabling injection swaps this in for it.\nconst INTEGRATION_NAME = 'Graphql' as const;\n\n// The context orchestrion's transform attaches to each channel: `arguments` is the live args of the\n// wrapped call, `result` the settled return value.\nfunction getOptionsWithDefaults(options: GraphQLOptions): GraphqlResolvedConfig {\n return {\n ignoreResolveSpans: options.ignoreResolveSpans !== false,\n ignoreTrivialResolveSpans: options.ignoreTrivialResolveSpans !== false,\n useOperationNameForRootSpan: options.useOperationNameForRootSpan !== false,\n };\n}\n\nconst _graphqlIntegration = ((options: GraphQLOptions = {}) => {\n const config = getOptionsWithDefaults(options);\n const getConfig = (): GraphqlResolvedConfig => config;\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, graphqlModuleNames, instrumentGraphql, [config, getConfig]);\n },\n setupOnce() {\n setupNativeGraphQLInstrumentation(options);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGraphql(config: GraphqlResolvedConfig, getConfig: () => GraphqlResolvedConfig): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.GRAPHQL_PARSE), () =>\n safeChannelCallback(() => startParseSpan()),\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.GRAPHQL_VALIDATE),\n data => safeChannelCallback(() => startValidateSpan(data.arguments[1])),\n { beforeSpanEnd: (span, data) => safeChannelCallback(() => finalizeValidateSpan(span, data.result)) },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.GRAPHQL_EXECUTE),\n data => safeChannelCallback(() => startExecuteSpan(data.arguments, data.self, config, getConfig)),\n { beforeSpanEnd: (span, data) => safeChannelCallback(() => finalizeExecuteSpan(span, data.result)) },\n );\n}\n\nfunction setupNativeGraphQLInstrumentation(options: GraphQLOptions) {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Subscribe to graphql's native tracing channels (graphql >= 17).\n // This is a no-op on versions that don't publish to the channels, so it is always safe to call.\n waitForTracingChannelBinding(() => {\n subscribeGraphqlDiagnosticChannels(diagnosticsChannel.tracingChannel, options);\n });\n}\n\n/**\n * Instrument the graphql library.\n * This works for graphql v14-v17.\n */\nexport const graphqlIntegration = defineIntegration(_graphqlIntegration);\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { hapiModuleNames } from '../../orchestrion/config/hapi';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { attachHapiErrorHandler } from './hapi-error-handler';\nimport type { HapiServer, HapiShouldHandleError } from './hapi-types';\nimport { wrapExtArguments, wrapRouteArguments } from './hapi-utils';\n\n// NOTE: same name as the OTel integration by design — when enabled, the OTel\n// 'Hapi' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Hapi' as const;\n\ninterface HapiIntegrationOptions {\n /**\n * Callback deciding whether an error should be captured and sent to Sentry.\n *\n * By default, 5xx errors (and errors without a resolvable status) are sent,\n * while 3xx and 4xx errors are not. The hapi request's `response` carries the\n * resolved HTTP status.\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.hapiIntegration({\n * shouldHandleError(_error, request) {\n * return (request.response?.output?.statusCode ?? request.response?.statusCode ?? 500) >= 500;\n * },\n * }),\n * ],\n * });\n * ```\n */\n shouldHandleError: HapiShouldHandleError;\n}\n\n/**\n * The shape orchestrion's transform attaches to the `@hapi/hapi` route/ext\n * tracing-channel `context` objects.\n *\n * `arguments` is the *live* args array passed to `server.route` / `server.ext`;\n * we mutate it in place to swap handlers for span-creating proxies. `self` is\n * the hapi server instance: the root server has `self.realm.plugin === undefined`,\n * while a plugin's clone server exposes the registering plugin's name there.\n */\ninterface HapiChannelContext extends OrchestrionChannelContext {\n self?: { realm?: { plugin?: string } };\n}\n\n/**\n * The `start`/`initialize` channel `context` shape: `self` is the live server\n * we attach the auto-registered error listener to.\n */\ninterface HapiServerContext extends OrchestrionChannelContext {\n self?: HapiServer;\n}\n\nconst _hapiIntegration = (({ shouldHandleError }: Partial<HapiIntegrationOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, hapiModuleNames, instrumentHapi, [shouldHandleError], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentHapi(shouldHandleError?: HapiShouldHandleError): void {\n // `subscribe` requires all five lifecycle hooks. We only act on `start`,\n // which orchestrion fires synchronously with the live args array — that's\n // the moment we mutate the handlers in place.\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_ROUTE).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapRouteArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_EXT).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapExtArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler when the server boots\n // `attachHapiErrorHandler` is idempotent, so hooking both `start` and `initialize` is safe.\n const attachOnStart = {\n start(rawCtx: unknown) {\n const server = (rawCtx as HapiServerContext).self;\n if (server) {\n attachHapiErrorHandler(server, shouldHandleError);\n }\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n };\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_START).subscribe(attachOnStart);\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_INITIALIZE).subscribe(attachOnStart);\n}\n\n/**\n * Diagnostics-channel-based hapi integration. Subscribes to the\n * `orchestrion:@hapi/hapi:route` / `:ext` channels injected into `@hapi/hapi`'s\n * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport type { HonoRuntime } from './connInfo';\nimport type { Env, Hono, MatchedHandler, MiddlewareHandler } from './honoTypes';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { honoModuleNames } from '../../orchestrion/config/hono';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime';\nimport { applyPatches } from './applyPatches';\nimport { INTERNAL_REQUEST_ORIGIN } from './constants';\nimport { createHonoRequestMiddleware } from './createHonoMiddleware';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { isMatchedHandlerList, wrapRouteHandlers } from './matchResult';\nimport { extractPathname, isInternalRequestSpanActive } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport type { SentryHonoMiddlewareOptions } from './types';\n\n// Matches the `@sentry/hono` SDK's integration name, so the SDK filters its own out of the\n// forwarded defaults and the two never stack.\nconst INTEGRATION_NAME = 'Hono' as const;\n\nexport interface HonoIntegrationOptions extends SentryHonoMiddlewareOptions {}\n\nfunction getHonoRuntime(): HonoRuntime {\n return isBun() ? 'bun' : isDeno() ? 'deno' : isCloudflareWorkers() ? 'cloudflare' : 'node';\n}\n\n/**\n * Manually instruments a Hono app and returns the Sentry request/response middleware to register\n * first: `app.use(honoMiddleware(app))`.\n *\n * Only needed when neither the Sentry runtime hook nor the bundler plugin is active — otherwise\n * {@link honoIntegration} does this automatically. Safe to combine with the automatic instrumentation\n * (request handling is deduplicated per request, `applyPatches` is idempotent). `Sentry.init(...)`\n * must still be called separately.\n */\nexport function honoMiddleware<E extends Env>(app: Hono<E>, options: HonoIntegrationOptions = {}): MiddlewareHandler {\n applyPatches(app);\n\n return createHonoRequestMiddleware({\n runtime: getHonoRuntime(),\n shouldHandleError: options.shouldHandleError,\n });\n}\n\nfunction wrapMatchedMiddleware(handlers: MatchedHandler[], middlewareFlags: boolean[]): void {\n for (const [i, [pair]] of handlers.entries()) {\n if (middlewareFlags[i]) {\n pair[0] = wrapMiddlewareWithSpan(pair[0]);\n }\n }\n}\n\n/**\n * Per-request Context hook. `#dispatch` builds `new Context(req, { matchResult })` before its\n * single-handler fast-path check, so from the live `matchResult` we:\n * 1. wrap the matched middleware handlers for spans (route handlers are covered by the request span);\n * 2. wrap the matched route handlers if more than one matched, so the route name follows the handler\n * that responds;\n * 3. prepend the Sentry request/response middleware — it drives route naming, request data and error\n * capture from inside the chain, and forces the ≥2-handler `compose` path so the fast-path is\n * never taken.\n *\n * Running per request (no module-scope state) is what lets this work on Cloudflare.\n */\nfunction injectHonoInstrumentation(\n message: OrchestrionChannelContext,\n requestMiddleware: MiddlewareHandler,\n injectedHandlerLists: WeakSet<object>,\n): void {\n const ctorOptions = message.arguments?.[1] as { matchResult?: [unknown[], unknown] } | undefined;\n const handlers = ctorOptions?.matchResult?.[0];\n if (!Array.isArray(handlers) || injectedHandlerLists.has(handlers)) {\n return;\n }\n injectedHandlerLists.add(handlers);\n\n if (isMatchedHandlerList(handlers)) {\n const middlewareFlags = getMiddlewareFlags(handlers.map(([[, route]]) => route));\n wrapMatchedMiddleware(handlers, middlewareFlags);\n wrapRouteHandlers(handlers, middlewareFlags);\n }\n\n // Prepend the Sentry request/response middleware. Its arity marks it as a middleware, so its `/*`\n // never becomes the route name.\n const routeMeta = { basePath: '/', path: '/*', method: 'ALL', handler: requestMiddleware };\n handlers.unshift([[requestMiddleware, routeMeta], {}]);\n}\n\n/**\n * Traces Hono's internal `app.request(...)` dispatches (sub-app-to-sub-app fetches) as `http.server`\n * child spans, but only when there is a parent span (so a top-level `.request()` is not traced).\n */\nfunction instrumentInternalRequests(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.HONO_REQUEST),\n data => {\n // Alongside the manual middleware, the instance `app.request` Proxy has already opened this\n // span and is calling through — returning `undefined` (no span) avoids nesting a duplicate.\n if (isInternalRequestSpanActive()) {\n return undefined;\n }\n\n const [input, requestInit] = data.arguments;\n const method = (\n (requestInit as RequestInit | undefined)?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n return startInactiveSpan({\n name: `${method} ${extractPathname(input)}`,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: HTTP_SERVER,\n [SENTRY_ORIGIN]: INTERNAL_REQUEST_ORIGIN,\n },\n });\n },\n );\n}\n\n/**\n * Wires the per-request Hono hooks (Context constructor + internal `app.request`) to the diagnostics\n * channel.\n *\n * Note:\n * Because the Sentry request/response middleware is prepended into the matched-handler list (`matchResult[0]`),\n * it also shows up in `c.req.matchedRoutes` — apps that inspect `matchedRoutes`\n * will see an extra `ALL /*` entry (the Sentry middleware) that they did not register themselves.\n */\nfunction instrumentHono(options: HonoIntegrationOptions): void {\n // `router.match` may hand back a cached handler array for a route, so track the lists we've already\n // prepended into and never inject the Sentry middleware twice.\n const injectedHandlerLists = new WeakSet<object>();\n\n // The request/response middleware is stateless (per-request state lives on the request scope) and\n // `options` is fixed, so build it once and reuse it across every dispatched Context.\n const requestMiddleware = createHonoRequestMiddleware({\n runtime: getHonoRuntime(),\n shouldHandleError: options.shouldHandleError,\n });\n\n // The Context constructor's `end` fires synchronously inside `new Context()`, before `#dispatch`\n // reads `matchResult[0].length`, so the injected middleware is in place for the same request.\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.HONO_CONTEXT).end.subscribe(message => {\n safeChannelCallback(() =>\n injectHonoInstrumentation(message as OrchestrionChannelContext, requestMiddleware, injectedHandlerLists),\n );\n });\n\n instrumentInternalRequests();\n}\n\nconst _honoIntegration = ((options: HonoIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, honoModuleNames, instrumentHono, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Automatically instruments Hono applications for Sentry tracing.\n *\n * Hooks Hono's per-request internals (the `Context` constructor and `app.request`) via the\n * orchestrion diagnostics channel — so instrumentation happens per request, never at module scope,\n * which is what lets it work on Cloudflare Workers with no manual middleware. Enabled by default in\n * the Node, Bun, Deno and Cloudflare SDKs; requires the Sentry runtime hook or bundler plugin.\n *\n * Registering `@sentry/hono`'s `sentry()` middleware manually alongside it is safe — request handling\n * is deduplicated per request.\n */\nexport const honoIntegration = defineIntegration(_honoIntegration);\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n defineIntegration,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport { CODE_FUNCTION_NAME, HTTP_ROUTE, KOA_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { koaModuleNames } from '../../orchestrion/config/koa';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { attachKoaErrorHandler, KOA_CONTEXT_SPAN, type KoaApp } from './koa-error-handler';\n\n// Same name as the OTel integration. When enabled, the OTel 'Koa' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Koa' as const;\n\nconst ORIGIN = 'auto.http.koa';\n\nconst LAYER_TYPE = {\n ROUTER: 'router',\n MIDDLEWARE: 'middleware',\n} as const;\ntype KoaLayerType = (typeof LAYER_TYPE)[keyof typeof LAYER_TYPE];\n\n// Keeps wrapping idempotent — the same middleware instance can be registered on\n// multiple routes (mirrors the vendored OTel instrumentation's symbol).\nconst kLayerPatched: unique symbol = Symbol('sentry.koa.layer-patched');\n\ntype Next = () => Promise<unknown>;\n\ninterface KoaContext {\n [key: string]: unknown;\n _matchedRoute?: string | RegExp;\n _matchedRouteName?: string;\n request?: { method?: string };\n}\n\ninterface Layer {\n path: string | RegExp;\n stack: KoaMiddleware[];\n}\n\ninterface Router {\n stack: Layer[];\n}\n\ntype KoaMiddleware = ((context: KoaContext, next: Next) => unknown) & {\n router?: Router;\n [kLayerPatched]?: boolean;\n};\n\ntype KoaSpanAttributes = Record<string, string | undefined>;\n\ninterface KoaMiddlewareMetadata {\n attributes: KoaSpanAttributes;\n name: string;\n}\n\n/** The `callback` channel `context` shape: `self` is the live app to attach the error listener to. */\ninterface KoaCallbackContext extends OrchestrionChannelContext {\n self?: KoaApp;\n}\n\nexport interface KoaIntegrationOptions {\n /** Ignore layers of the specified types (`'middleware'` and/or `'router'`). */\n ignoreLayersType?: Array<'middleware' | 'router'>;\n}\n\nconst _koaIntegration = ((options: KoaIntegrationOptions = {}) => {\n const ignoreLayersType = options.ignoreLayersType ?? [];\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, koaModuleNames, instrumentKoa, [ignoreLayersType], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentKoa(ignoreLayersType: KoaLayerType[]): void {\n diagnosticsChannel.tracingChannel(CHANNELS.KOA_USE).subscribe({\n start(rawCtx) {\n handleUse(rawCtx as OrchestrionChannelContext, ignoreLayersType);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler once the app boots.\n // We act on `end` (after `callback()` ran) so\n // koa's default `error` listener is already in place; `attachKoaErrorHandler`\n // is idempotent, so repeated `callback()` calls add at most one listener.\n diagnosticsChannel.tracingChannel(CHANNELS.KOA_CALLBACK).subscribe({\n start() {},\n end(rawCtx) {\n const app = (rawCtx as KoaCallbackContext).self;\n if (app) {\n // oxlint-disable-next-line typescript/no-deprecated -- internal auto-registration entrypoint\n attachKoaErrorHandler(app);\n }\n },\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n}\n\nfunction handleUse(ctx: OrchestrionChannelContext, ignoreLayersType: KoaLayerType[]): void {\n const middleware = ctx.arguments[0];\n if (typeof middleware === 'function') {\n ctx.arguments[0] = patchUse(middleware as KoaMiddleware, ignoreLayersType);\n }\n}\n\n/**\n * Wrap a registered koa middleware. A `@koa/router` dispatch layer\n * (`router.routes()`) exposes a `.router`, in which case we patch each routed\n * middleware in its stack (in place) and leave the dispatch itself unwrapped;\n * everything else is a plain middleware.\n */\nfunction patchUse(middleware: KoaMiddleware, ignoreLayersType: KoaLayerType[]): KoaMiddleware {\n return middleware.router\n ? patchRouterDispatch(middleware, ignoreLayersType)\n : patchLayer(middleware, false, ignoreLayersType);\n}\n\n/**\n * Patches the dispatch function used by `@koa/router`, wrapping each routed\n * middleware in the router's stack so routed spans carry their matched path.\n */\nfunction patchRouterDispatch(dispatchLayer: KoaMiddleware, ignoreLayersType: KoaLayerType[]): KoaMiddleware {\n const router = dispatchLayer.router;\n const routesStack = router?.stack ?? [];\n for (const pathLayer of routesStack) {\n const path = pathLayer.path;\n const pathStack = pathLayer.stack;\n pathStack.forEach((routedMiddleware, j) => {\n pathStack[j] = patchLayer(routedMiddleware, true, ignoreLayersType, path);\n });\n }\n return dispatchLayer;\n}\n\n/**\n * Wraps an individual middleware layer so it opens a span when invoked. No span\n * is created when there is no active (parent) span, matching the vendored OTel\n * instrumentation's `api.trace.getSpan(api.context.active())` guard.\n */\nfunction patchLayer(\n middlewareLayer: KoaMiddleware,\n isRouter: boolean,\n ignoreLayersType: KoaLayerType[],\n layerPath?: string | RegExp,\n): KoaMiddleware {\n const layerType = isRouter ? LAYER_TYPE.ROUTER : LAYER_TYPE.MIDDLEWARE;\n // Skip patching the layer if it's ignored by config or already wrapped.\n if (middlewareLayer[kLayerPatched] === true || ignoreLayersType.includes(layerType)) {\n return middlewareLayer;\n }\n\n if (\n middlewareLayer.constructor.name === 'GeneratorFunction' ||\n middlewareLayer.constructor.name === 'AsyncGeneratorFunction'\n ) {\n return middlewareLayer;\n }\n\n middlewareLayer[kLayerPatched] = true;\n\n return (context: KoaContext, next: Next) => {\n if (!getActiveSpan()) {\n return middlewareLayer(context, next);\n }\n const metadata = getMiddlewareMetadata(context, middlewareLayer, isRouter, layerPath);\n\n if (context._matchedRoute) {\n setHttpServerSpanRouteAttribute(context._matchedRoute.toString());\n }\n\n // Router layers carry the route, middleware layers the handler name.\n const layerName = metadata.attributes[HTTP_ROUTE] ?? metadata.attributes[CODE_FUNCTION_NAME];\n // Somehow, name is sometimes `''` for middleware spans.\n // See: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2220\n const staticName = typeof layerName === 'string' ? layerName || '< unknown >' : metadata.name;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router spans are named after their route.\n const isStreamedRouterSpan = layerType === LAYER_TYPE.ROUTER && !!client && hasSpanStreamingEnabled(client);\n const name = isStreamedRouterSpan ? metadata.attributes[HTTP_ROUTE] || ROUTER_SPAN_NAME_FALLBACK : staticName;\n\n return startSpan(\n {\n name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: layerType === LAYER_TYPE.MIDDLEWARE ? MIDDLEWARE : ROUTER,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n },\n () => {\n // Stash the outermost koa span (first layer wins) on the koa `ctx`, so the\n // error listener can capture within it — koa emits its `error` event after\n // the middleware chain (and its spans) have unwound, when no span is active.\n if (!context[KOA_CONTEXT_SPAN]) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n addNonEnumerableProperty(context, KOA_CONTEXT_SPAN, activeSpan);\n }\n }\n\n const route = metadata.attributes[HTTP_ROUTE];\n if (getIsolationScope() === getDefaultIsolationScope()) {\n DEBUG_BUILD && debug.warn('Isolation scope is default isolation scope - skipping setting transactionName');\n } else if (route) {\n const method = context.request?.method?.toUpperCase() || 'GET';\n getIsolationScope().setTransactionName(`${method} ${route}`);\n }\n return middlewareLayer(context, next);\n },\n );\n };\n}\n\nfunction getMiddlewareMetadata(\n context: KoaContext,\n layer: KoaMiddleware,\n isRouter: boolean,\n layerPath?: string | RegExp,\n): KoaMiddlewareMetadata {\n if (isRouter) {\n return {\n attributes: {\n [KOA_TYPE]: LAYER_TYPE.ROUTER,\n [HTTP_ROUTE]: layerPath?.toString(),\n },\n name: context._matchedRouteName || `router - ${layerPath}`,\n };\n }\n return {\n attributes: {\n [KOA_TYPE]: LAYER_TYPE.MIDDLEWARE,\n [CODE_FUNCTION_NAME]: layer.name || 'middleware',\n },\n name: `middleware - ${layer.name}`,\n };\n}\n\n/**\n * Diagnostics-channel-based koa integration. Subscribes to the\n * `orchestrion:koa:use` channel injected into `Application.prototype.use` and\n * wraps each registered middleware/router layer in a span-creating proxy.\n * Requires the Sentry runtime hook or bundler plugin.\n */\nexport const koaIntegration = defineIntegration(_koaIntegration);\n","import { DB_STORED_PROCEDURE_NAME } from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst DB_SYSTEM_VALUE_REDIS = 'redis';\n\n// `FCALL`/`FCALL_RO` invoke a redis function by name as their first argument. Redis functions are\n// the one construct the conventions' db naming templates can model for redis — everything else a\n// command touches is a key, which is exactly the high cardinality the streamed name has to avoid.\nconst STORED_PROCEDURE_COMMANDS = ['fcall', 'fcall_ro'];\n\n// The connection a command was sent over. Untyped values because call sites read them off a client,\n// a diagnostics_channel payload or an already-built span attribute bag.\ninterface RedisConnection {\n host?: unknown;\n port?: unknown;\n}\n\nfunction getStoredProcedureName(command: string, args: ReadonlyArray<unknown>): string | undefined {\n if (!STORED_PROCEDURE_COMMANDS.includes(command.toLowerCase())) {\n return undefined;\n }\n const raw = args[0];\n const name = typeof raw === 'string' ? raw : Buffer.isBuffer(raw) ? raw.toString() : undefined;\n // node-redis and ioredis redact arguments before publishing them on their channels. A redacted\n // function name says nothing, so leave the attribute unset rather than emit `FCALL ?`.\n return name && name !== '?' ? name : undefined;\n}\n\n// The conventions have no address-only template, so both halves are required: a client\n// configured with only a port has no target, and neither does a unix socket, whose\n// `server.address` is a path with no port to pair it with.\nfunction getServerTarget({ host, port }: RedisConnection): string | undefined {\n const hasPort = typeof port === 'number' || (typeof port === 'string' && !!port);\n return typeof host === 'string' && host && hasPort ? `${host}:${port}` : undefined;\n}\n\n/**\n * The conventions attributes that name a redis command span, and the name itself when span\n * streaming is enabled (`undefined` otherwise, leaving the caller's existing name in place).\n *\n * `db.query.text` carries the key and its arguments, so it cannot name a streamed span. Redis has\n * no collection to pair the operation with, so the name is\n * `{db.operation.name} {server.address}:{server.port}`, falling back to `{db.system.name}` when the\n * client was configured without a host. `FCALL` names a redis function, which the conventions model\n * as a stored procedure and rank ahead of the connection.\n *\n * `db.namespace` is deliberately not a target: for redis it is the numeric database index, which\n * says nothing about what the command did.\n */\nexport function getRedisQueryNaming(\n command: string,\n args: ReadonlyArray<unknown>,\n connection: RedisConnection,\n): { streamedName: string | undefined; attributes: SpanAttributes } {\n const storedProcedure = getStoredProcedureName(command, args);\n const target = storedProcedure || getServerTarget(connection);\n const name = command && target ? `${command} ${target}` : target || DB_SYSTEM_VALUE_REDIS;\n const client = getClient();\n\n return {\n streamedName: client && hasSpanStreamingEnabled(client) ? name : undefined,\n attributes: storedProcedure ? { [DB_STORED_PROCEDURE_NAME]: storedProcedure } : {},\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/instrumentation-redis-v0.62.0/packages/redis-common\n * - Upstream version: @opentelemetry/redis-common@0.38.2\n *\n * Single canonical copy, shared by the orchestrion redis and ioredis channel subscribers here.\n */\n/* eslint-disable -- vendored @opentelemetry/redis-common */\n\n/**\n * List of regexes and the number of arguments that should be serialized for matching commands.\n * For example, HSET should serialize which key and field it's operating on, but not its value.\n * Setting the subset to -1 will serialize all arguments.\n * Commands without a match will have their first argument serialized.\n *\n * Refer to https://redis.io/commands/ for the full list.\n */\nconst serializationSubsets = [\n {\n regex: /^ECHO/i,\n args: 0,\n },\n {\n regex: /^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,\n args: 1,\n },\n {\n regex: /^(HSET|HMSET|LSET|LINSERT)/i,\n args: 2,\n },\n {\n regex:\n /^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,\n args: -1,\n },\n];\n\n/**\n * Given the redis command name and arguments, return a combination of the\n * command name + the allowed arguments according to `serializationSubsets`.\n */\nexport const defaultDbStatementSerializer = (\n cmdName: string,\n cmdArgs: Array<string | Buffer | number | unknown[]>,\n): string => {\n if (Array.isArray(cmdArgs) && cmdArgs.length) {\n const nArgsToSerialize = serializationSubsets.find(({ regex }) => regex.test(cmdName))?.args ?? 0;\n const argsToSerialize: Array<string | Buffer | number | unknown[]> =\n nArgsToSerialize >= 0 ? cmdArgs.slice(0, nArgsToSerialize) : cmdArgs.slice();\n if (cmdArgs.length > argsToSerialize.length) {\n argsToSerialize.push(`[${cmdArgs.length - nArgsToSerialize} other arguments]`);\n }\n return `${cmdName} ${argsToSerialize.join(' ')}`;\n }\n return cmdName;\n};\n","import {\n CACHE_HIT,\n CACHE_ITEM_SIZE,\n CACHE_KEY,\n CACHE_OPERATION,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_OP,\n} from '@sentry/conventions/attributes';\nimport { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { CACHE_OPERATION_NAMES, getClient, hasSpanStreamingEnabled, spanToJSON, truncate } from '@sentry/core';\n\n// Runtime-agnostic on purpose: imports nothing from `node:*` and touches `Buffer` only inside\n// function bodies (never at module load), so bundling this into an edge runtime is safe and the\n// redis channel integrations can share one cache implementation across every server runtime.\n\nexport type RedisCommandArgs = Array<string | Buffer | number | unknown[]>;\n\nconst SINGLE_ARG_COMMANDS = ['get', 'set', 'setex'];\n\nexport const GET_COMMANDS = ['get', 'mget'];\nexport const SET_COMMANDS = ['set', 'setex'];\nexport const REMOVE_COMMANDS = ['del', 'unlink'];\n// todo: expire (no matching cache convention op yet)\n\n/** Options controlling which redis commands are captured as cache spans. */\nexport interface RedisCacheOptions {\n /**\n * Define cache prefixes for cache keys that should be captured as a cache span.\n *\n * Setting this to, for example, `['user:']` will capture cache keys that start with `user:`.\n */\n cachePrefixes?: string[];\n /**\n * Maximum length of the cache key added to the span description. If the key exceeds this length, it will be truncated.\n *\n * Passing `0` will use the full cache key without truncation.\n *\n * By default, the full cache key is used.\n *\n * Only applies with `traceLifecycle: 'static'`. With span streaming (the default), span names are\n * low cardinality: cache spans are named after the cache operation (e.g. `cache.get`) and the\n * key is only added to the `cache.key` attribute, so there is nothing to truncate.\n */\n maxCacheKeyLength?: number;\n}\n\n/** Checks if a given command is in the list of redis commands.\n * Useful because commands can come in lowercase or uppercase (depending on the library). */\nexport function isInCommands(redisCommands: string[], command: string): boolean {\n return redisCommands.includes(command.toLowerCase());\n}\n\n/** Determine cache operation based on redis statement */\nexport function getCacheOperation(command: string): 'cache.get' | 'cache.put' | 'cache.remove' | undefined {\n if (isInCommands(GET_COMMANDS, command)) {\n return CACHE_GET;\n } else if (isInCommands(SET_COMMANDS, command)) {\n return CACHE_PUT;\n } else if (isInCommands(REMOVE_COMMANDS, command)) {\n return CACHE_REMOVE;\n } else {\n return undefined;\n }\n}\n\nfunction keyHasPrefix(key: string, prefixes: string[]): boolean {\n return prefixes.some(prefix => key.startsWith(prefix));\n}\n\n/** Safely converts a redis key to a string (comma-separated if there are multiple keys) */\nexport function getCacheKeySafely(redisCommand: string, cmdArgs: RedisCommandArgs): string[] | undefined {\n try {\n if (cmdArgs.length === 0) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const processArg = (arg: string | Buffer | number | any[]): string[] => {\n if (typeof arg === 'string' || typeof arg === 'number' || Buffer.isBuffer(arg)) {\n return [arg.toString()];\n } else if (Array.isArray(arg)) {\n return flatten(arg.map(arg => processArg(arg)));\n } else {\n return ['<unknown>'];\n }\n };\n\n const firstArg = cmdArgs[0];\n if (isInCommands(SINGLE_ARG_COMMANDS, redisCommand) && firstArg != null) {\n return processArg(firstArg);\n }\n\n return flatten(cmdArgs.map(arg => processArg(arg)));\n } catch {\n return undefined;\n }\n}\n\n/** Determines whether a redis operation should be considered as \"cache operation\" by checking if a key is prefixed.\n * We only support certain commands (such as 'set', 'get', 'mget'). */\nexport function shouldConsiderForCache(redisCommand: string, keys: string[], prefixes: string[]): boolean {\n if (!getCacheOperation(redisCommand)) {\n return false;\n }\n\n for (const key of keys) {\n if (keyHasPrefix(key, prefixes)) {\n return true;\n }\n }\n return false;\n}\n\n/** Calculates size based on the cache response value */\nexport function calculateCacheItemSize(response: unknown): number | undefined {\n const getSize = (value: unknown): number | undefined => {\n try {\n if (Buffer.isBuffer(value)) return value.byteLength;\n else if (typeof value === 'string') return value.length;\n else if (typeof value === 'number') return value.toString().length;\n else if (value === null || value === undefined) return 0;\n return JSON.stringify(value).length;\n } catch {\n return undefined;\n }\n };\n\n return Array.isArray(response)\n ? response.reduce((acc: number | undefined, curr) => {\n const size = getSize(curr);\n return typeof size === 'number' ? (acc !== undefined ? acc + size : size) : acc;\n }, 0)\n : getSize(response);\n}\n\n/**\n * Decides at span-start time whether a redis command is a cache operation (its key matches one of\n * the configured `cachePrefixes`) and returns the span name plus attribute overrides to merge into\n * the db span options, or `undefined` for a plain db span. Callers must spread the returned\n * attributes after their db attributes, so the cache op overrides the db op. Deciding at start time\n * — instead of renaming the db span at response time — makes `ignoreSpans` and span streaming see\n * the same op/name the user sees in the UI.\n *\n * `dbAttributes` are the attributes the caller starts the span with; the network peer is derived\n * from `server.address`/`server.port` in there.\n */\nexport function getRedisCacheAttributes(\n redisCommand: string,\n cmdArgs: RedisCommandArgs,\n dbAttributes: SpanAttributes,\n options: RedisCacheOptions,\n): { name: string; attributes: SpanAttributes } | undefined {\n const safeKey = getCacheKeySafely(redisCommand, cmdArgs);\n const cacheOperation = getCacheOperation(redisCommand);\n\n if (\n !safeKey ||\n !cacheOperation ||\n !options.cachePrefixes ||\n !shouldConsiderForCache(redisCommand, safeKey, options.cachePrefixes)\n ) {\n // not relevant for cache\n return undefined;\n }\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: cacheOperation,\n [CACHE_KEY]: safeKey,\n [CACHE_OPERATION]: CACHE_OPERATION_NAMES[cacheOperation],\n };\n\n const networkPeerAddress = dbAttributes[SERVER_ADDRESS] as string | undefined;\n const networkPeerPort = dbAttributes[SERVER_PORT] as number | undefined;\n if (networkPeerPort && networkPeerAddress) {\n attributes[NETWORK_PEER_ADDRESS] = networkPeerAddress;\n attributes[NETWORK_PEER_PORT] = networkPeerPort;\n }\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n // With span streaming, span names have to be low cardinality, so we can't fall back to the cache key.\n return { name: cacheOperation, attributes };\n }\n\n // todo: change to string[] once EAP supports it\n const spanDescription = safeKey.join(', ');\n\n return {\n name: options.maxCacheKeyLength ? truncate(spanDescription, options.maxCacheKeyLength) : spanDescription,\n attributes,\n };\n}\n\n/**\n * Sets the response-derived cache attributes (`cache.hit`, `cache.item_size`) on a span that was\n * started as a cache span via {@link getRedisCacheAttributes}. A no-op for plain db spans and for\n * `cache.remove` spans — a remove response is a delete-count, not a cached value, so its size is\n * meaningless.\n */\nexport function applyCacheResponseAttributes(span: Span, response: unknown): void {\n const op = spanToJSON(span).attributes[SENTRY_OP];\n if (op !== CACHE_GET && op !== CACHE_PUT) {\n return;\n }\n\n const cacheItemSize = calculateCacheItemSize(response);\n\n if (cacheItemSize) {\n span.setAttribute(CACHE_ITEM_SIZE, cacheItemSize);\n }\n\n if (op === CACHE_GET && cacheItemSize !== undefined) {\n span.setAttribute(CACHE_HIT, cacheItemSize > 0);\n }\n}\n\ntype NestedArray<T> = Array<NestedArray<T> | T>;\n\nfunction flatten<T>(input: NestedArray<T>): T[] {\n const result: T[] = [];\n\n const flattenHelper = (input: NestedArray<T>): void => {\n input.forEach((el: T | NestedArray<T>) => {\n if (Array.isArray(el)) {\n flattenHelper(el);\n } else {\n result.push(el);\n }\n });\n };\n\n flattenHelper(input);\n return result;\n}\n","import type { TracingChannel } from 'node:diagnostics_channel';\nimport {\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB_QUERY, DB } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport { startInactiveSpan } from '@sentry/core';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport type { RedisCacheOptions } from './redis-cache';\nimport { applyCacheResponseAttributes, getRedisCacheAttributes } from './redis-cache';\nimport { getRedisQueryNaming } from './redis-span-name';\n\n// Channel names published by node-redis >= 5.12.0 and ioredis >= 5.11.0.\n// Hardcoded so the subscriber does not have to import either library — the\n// channels just have to be subscribed to before the user's redis code\n// publishes.\nexport const REDIS_DC_CHANNEL_COMMAND = 'node-redis:command';\nexport const REDIS_DC_CHANNEL_BATCH = 'node-redis:batch';\nexport const REDIS_DC_CHANNEL_CONNECT = 'node-redis:connect';\nexport const IOREDIS_DC_CHANNEL_COMMAND = 'ioredis:command';\nexport const IOREDIS_DC_CHANNEL_CONNECT = 'ioredis:connect';\n\nconst ORIGIN = 'auto.db.redis.native_channel';\nconst DB_SYSTEM_NAME_VALUE_REDIS = 'redis';\n\n/**\n * Shape of the `node-redis:command` channel payload published by node-redis.\n *\n * Both `command` and `args` are already redacted by node-redis itself (see\n * `sanitizeArgs` in @redis/client) using the OTel `redis-common` rules. The\n * arg array is `[<command>, <safe arg>, ..., '?', ...]` — `?` replaces any\n * value the library considers sensitive. Subscribers can emit `args` directly\n * as `db.query.text` without further serialization.\n */\nexport interface RedisCommandData {\n command: string;\n /** First arg is the command name itself; consumers should slice it off. */\n args: string[];\n database?: number;\n serverAddress?: string;\n serverPort?: number;\n result?: unknown;\n error?: Error;\n}\n\n/**\n * Shape of the `ioredis:command` channel payload published by ioredis >= 5.11.0.\n *\n * As with node-redis, args are already sanitized by ioredis (`sanitizeArgs` in\n * `lib/tracing.ts`) before publishing. Unlike node-redis, the command name is\n * NOT prepended to `args`.\n */\nexport interface IORedisCommandData {\n command: string;\n args: string[];\n batchMode?: 'MULTI';\n batchSize?: number;\n database?: number;\n serverAddress?: string;\n serverPort?: number;\n result?: unknown;\n error?: Error;\n}\n\n/** Shape of the `node-redis:batch` channel payload published by node-redis. */\nexport interface RedisBatchData {\n batchMode?: 'MULTI' | 'PIPELINE';\n batchSize?: number;\n database?: number;\n clientId?: string | number;\n serverAddress?: string;\n serverPort?: number;\n result?: unknown[];\n error?: Error;\n}\n\n/** Shape of the `*:connect` channel payload published by node-redis and ioredis. */\nexport interface RedisConnectData {\n serverAddress?: string;\n serverPort?: number;\n url?: string;\n error?: Error;\n}\n\n/**\n * Platform-provided factory that creates a native tracing channel for the given name. The\n * subscriber binds the span and its lifecycle onto the channel via `bindTracingChannelToSpan`,\n * which propagates the active span through the runtime's async context.\n *\n * Both Node and Deno pass `node:diagnostics_channel`'s `tracingChannel` directly.\n */\nexport type RedisTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * Subscribe Sentry span handlers to node-redis and ioredis diagnostics-channel\n * events: `node-redis:command`/`:batch`/`:connect` (published by node-redis\n * >= 5.12.0) and `ioredis:command`/`:connect` (published by ioredis >= 5.11.0).\n *\n * On older client versions the channels are never published to, so subscribers\n * are inert — there is no double-instrumentation against any IITM-based\n * patcher gated to those older versions.\n */\nexport function subscribeRedisDiagnosticChannels(\n tracingChannel: RedisTracingChannelFactory,\n cacheOptions: RedisCacheOptions = {},\n): void {\n // node-redis: command name appears as args[0] in the channel payload, so\n // strip it before the statement and cache handling see it.\n setupCommandChannel<RedisCommandData>(\n tracingChannel,\n REDIS_DC_CHANNEL_COMMAND,\n data => data.args.slice(1),\n cacheOptions,\n );\n setupBatchChannel(tracingChannel, REDIS_DC_CHANNEL_BATCH, data =>\n data.batchMode === 'PIPELINE' ? 'PIPELINE' : 'MULTI',\n );\n setupConnectChannel(tracingChannel, REDIS_DC_CHANNEL_CONNECT);\n // ioredis: args already exclude the command name; no slicing needed. And\n // ioredis has no separate batch channel — pipeline/MULTI metadata rides\n // on the per-command payload via `batchMode`/`batchSize`.\n setupCommandChannel<IORedisCommandData>(tracingChannel, IOREDIS_DC_CHANNEL_COMMAND, data => data.args, cacheOptions);\n setupConnectChannel(tracingChannel, IOREDIS_DC_CHANNEL_CONNECT);\n}\n\nfunction setupCommandChannel<T extends RedisCommandData | IORedisCommandData>(\n tracingChannel: RedisTracingChannelFactory,\n channelName: string,\n getCommandArgs: (data: T) => string[],\n cacheOptions: RedisCacheOptions,\n): void {\n bindTracingChannelToSpan(\n tracingChannel<T>(channelName),\n data => {\n // `args` is already sanitized by the publishing library (node-redis /\n // ioredis call their own `sanitizeArgs` before publishing). Join with\n // spaces to mirror the format the libraries themselves intend.\n const args = getCommandArgs(data);\n const statement = args.length ? `${data.command} ${args.join(' ')}` : data.command;\n const { streamedName, attributes: namingAttributes } = getRedisQueryNaming(data.command, args, {\n host: data.serverAddress,\n port: data.serverPort,\n });\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB_QUERY,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_REDIS,\n [DB_OPERATION_NAME]: data.command,\n ...namingAttributes,\n [DB_QUERY_TEXT]: statement,\n ...(data.serverAddress != null ? { [SERVER_ADDRESS]: data.serverAddress } : {}),\n ...(data.serverPort != null ? { [SERVER_PORT]: data.serverPort } : {}),\n };\n const cacheProperties = getRedisCacheAttributes(data.command, args, attributes, cacheOptions);\n return startInactiveSpan({\n name: cacheProperties?.name ?? streamedName ?? `redis-${data.command}`,\n attributes: { ...attributes, ...cacheProperties?.attributes },\n });\n },\n {\n beforeSpanEnd(span, data) {\n if ('error' in data) return;\n applyCacheResponseAttributes(span, data.result);\n },\n },\n );\n}\n\nfunction setupBatchChannel(\n tracingChannel: RedisTracingChannelFactory,\n channelName: string,\n getOperationName: (data: RedisBatchData) => string,\n): void {\n bindTracingChannelToSpan(tracingChannel<RedisBatchData>(channelName), data => {\n const operation = getOperationName(data);\n return startInactiveSpan({\n name: operation,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB_QUERY,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_REDIS,\n [DB_OPERATION_NAME]: operation,\n // should only include batch size greater than 1,\n // or else it isn't properly considered a \"batch\"\n ...(Number(data.batchSize) > 1 ? { [DB_OPERATION_BATCH_SIZE]: data.batchSize } : {}),\n ...(data.serverAddress != null ? { [SERVER_ADDRESS]: data.serverAddress } : {}),\n ...(data.serverPort != null ? { [SERVER_PORT]: data.serverPort } : {}),\n },\n });\n });\n}\n\nfunction setupConnectChannel(tracingChannel: RedisTracingChannelFactory, channelName: string): void {\n bindTracingChannelToSpan(tracingChannel<RedisConnectData>(channelName), data => {\n return startInactiveSpan({\n name: 'redis-connect',\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_REDIS,\n ...(data.serverAddress != null ? { [SERVER_ADDRESS]: data.serverAddress } : {}),\n ...(data.serverPort != null ? { [SERVER_PORT]: data.serverPort } : {}),\n },\n });\n });\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB_QUERY, DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { startInactiveSpan } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport type { RedisCacheOptions } from './redis-cache';\nimport { applyCacheResponseAttributes, getRedisCacheAttributes } from './redis-cache';\nimport { getRedisQueryNaming } from './redis-span-name';\nimport { defaultDbStatementSerializer } from './redis-statement-serializer';\n\nconst ORIGIN = 'auto.db.redis';\n\nconst DB_SYSTEM_VALUE_REDIS = 'redis';\n\n/** Structural type for the command object ioredis passes to `sendCommand`. */\ninterface RedisCommand {\n name: string;\n args: Array<string | Buffer>;\n}\n\ninterface RedisClientLike {\n options?: { host?: string; port?: number };\n}\n\ninterface IORedisCommandContext extends OrchestrionChannelContext {\n self?: RedisClientLike;\n}\n\nfunction getConnectionOptions(self: RedisClientLike | undefined): { host?: string; port?: number } {\n return { host: self?.options?.host, port: self?.options?.port };\n}\n\nfunction connectionAttributes(host: string | undefined, port: number | undefined): Record<string, unknown> {\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_REDIS,\n ...(host != null ? { [SERVER_ADDRESS]: host } : {}),\n ...(port != null ? { [SERVER_PORT]: port } : {}),\n [SENTRY_ORIGIN]: ORIGIN,\n };\n}\n\n// ioredis re-enters `sendCommand` with the same command object when it drains\n// the offline queue on connect which leads to duplicate spans.\n// Track commands we've already traced so each logical command produces one span.\nconst tracedCommands = new WeakSet<object>();\n\n/**\n * Builds the db span for an `orchestrion:ioredis:command` payload, or returns `undefined` to skip\n * it: for a non-command payload, or the offline-queue re-send of an already-traced command.\n *\n * Exported for unit testing.\n */\nexport function startIORedisCommandSpan(\n data: IORedisCommandContext,\n cacheOptions: RedisCacheOptions,\n): Span | undefined {\n const command = data.arguments?.[0] as RedisCommand | undefined;\n if (!command || typeof command !== 'object') {\n return undefined;\n }\n // guard against duplicate spans\n if (tracedCommands.has(command)) {\n return undefined;\n }\n tracedCommands.add(command);\n const { host, port } = getConnectionOptions(data.self);\n const statement = defaultDbStatementSerializer(command.name, command.args ?? []);\n const { streamedName, attributes: namingAttributes } = getRedisQueryNaming(command.name, command.args ?? [], {\n host,\n port,\n });\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n ...connectionAttributes(host, port),\n [SENTRY_OP]: DB_QUERY,\n [DB_OPERATION_NAME]: command.name,\n ...namingAttributes,\n [DB_QUERY_TEXT]: statement,\n };\n const cacheProperties = getRedisCacheAttributes(command.name, command.args ?? [], attributes, cacheOptions);\n\n return startInactiveSpan({\n name: cacheProperties?.name ?? streamedName ?? statement,\n onlyIfParent: true,\n attributes: { ...attributes, ...cacheProperties?.attributes },\n });\n}\n\n/**\n * Subscribes to `orchestrion:ioredis:command` / `:connect` (injected into ioredis' `<5.11.0`\n * `sendCommand`/`connect`) and creates db spans matching `@opentelemetry/instrumentation-ioredis`.\n * ioredis `>=5.11.0` publishes its own `ioredis:*` diagnostics_channel, handled by the native\n * subscriber in `redis-dc-subscriber.ts` instead.\n */\nexport function instrumentIoredis(options: RedisCacheOptions): void {\n const commandChannel = diagnosticsChannel.tracingChannel<IORedisCommandContext, IORedisCommandContext>(\n CHANNELS.IOREDIS_COMMAND,\n );\n const connectChannel = diagnosticsChannel.tracingChannel<IORedisCommandContext, IORedisCommandContext>(\n CHANNELS.IOREDIS_CONNECT,\n );\n\n bindTracingChannelToSpan(commandChannel, data => startIORedisCommandSpan(data, options), {\n beforeSpanEnd(span, data) {\n if (!('error' in data)) {\n applyCacheResponseAttributes(span, data.result);\n }\n },\n });\n\n bindTracingChannelToSpan(connectChannel, data => {\n const { host, port } = getConnectionOptions(data.self);\n return startInactiveSpan({\n name: 'connect',\n onlyIfParent: true,\n attributes: {\n [SENTRY_KIND]: 'client',\n ...connectionAttributes(host, port),\n [SENTRY_OP]: DB,\n },\n });\n });\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB_QUERY, DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport {\n isObjectLike,\n defineIntegration,\n getActiveSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n withActiveSpan,\n waitForTracingChannelBinding,\n} from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { getRedisQueryNaming } from './redis-span-name';\nimport { defaultDbStatementSerializer } from './redis-statement-serializer';\nimport type { RedisCacheOptions } from './redis-cache';\nimport { applyCacheResponseAttributes, getRedisCacheAttributes } from './redis-cache';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { redisModuleNames } from '../../orchestrion/config/redis';\nimport { ioredisModuleNames } from '../../orchestrion/config/ioredis';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { subscribeRedisDiagnosticChannels } from './redis-dc-subscriber';\nimport { instrumentIoredis } from './ioredis-channel-subscriber';\n\nconst INTEGRATION_NAME = 'Redis' as const;\n\nconst ORIGIN = 'auto.db.redis';\n\nconst DB_SYSTEM_VALUE_REDIS = 'redis';\n\nexport interface RedisIntegrationOptions extends RedisCacheOptions {}\n\n/** Structural type for a node-redis (`@redis/client`) command definition. */\ninterface RedisCommandDefinition {\n transformArguments?: (...args: unknown[]) => Array<string | Buffer>;\n}\n\n/** Structural type for the `command_obj` `redis` v2-v3 passes to `internal_send_command`. */\ninterface LegacyRedisCommand {\n command: string;\n args: Array<string | Buffer>;\n callback?: (err: Error | null | undefined, reply: unknown) => unknown;\n}\n\ninterface LegacyRedisClient {\n connection_options?: { host?: string; port?: number };\n address?: string;\n}\n\ninterface NodeRedisClientOptions {\n socket?: { host?: string; port?: number; path?: string };\n url?: string;\n}\n\ninterface NodeRedisClient {\n options?: NodeRedisClientOptions;\n}\n\nfunction endSpan(span: Span, err: unknown): void {\n if (err) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: err instanceof Error ? err.message : String(err) });\n }\n span.end();\n}\n\n// Strip a leading `commandOptions(...)` object (tagged with a `Symbol`) before\n// deriving the wire arguments, mirroring `@redis/client`'s `transformCommandArguments`.\nfunction stripCommandOptions(args: unknown[]): unknown[] {\n const first = args[0];\n if (isObjectLike(first) && Object.getOwnPropertySymbols(first).length > 0) {\n return args.slice(1);\n }\n return args;\n}\n\n// Resolves the connection the way node-redis >= 5.12 reports it on its own diagnostics channel: a\n// unix socket reports its path and no port, a TCP client the `localhost:6379` it defaults to.\n// Only v4 writes those defaults back into `client.options`, so reading the options as-is would\n// report a connection for a v4 client and none for the identically configured v5 one.\nfunction nodeRedisAttributes(options: NodeRedisClientOptions | undefined): SpanAttributes {\n const socket = options?.socket;\n const host = socket?.path ?? socket?.host ?? 'localhost';\n const port = socket?.path != null ? undefined : (socket?.port ?? 6379);\n\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_REDIS,\n [SERVER_ADDRESS]: host,\n ...(port != null ? { [SERVER_PORT]: port } : {}),\n [SENTRY_ORIGIN]: ORIGIN,\n };\n}\n\nfunction startCommandSpan(\n commandName: string,\n commandArgs: Array<string | Buffer>,\n attributes: SpanAttributes,\n cacheOptions: RedisCacheOptions,\n): Span {\n const dbStatement = defaultDbStatementSerializer(commandName, commandArgs);\n const { streamedName, attributes: namingAttributes } = getRedisQueryNaming(commandName, commandArgs, {\n host: attributes[SERVER_ADDRESS],\n port: attributes[SERVER_PORT],\n });\n const cacheProperties = getRedisCacheAttributes(commandName, commandArgs, attributes, cacheOptions);\n\n return startInactiveSpan({\n name: cacheProperties?.name ?? streamedName ?? (dbStatement || `redis-${commandName}`),\n attributes: {\n [SENTRY_KIND]: 'client',\n ...attributes,\n [SENTRY_OP]: DB_QUERY,\n [DB_OPERATION_NAME]: commandName,\n ...namingAttributes,\n [DB_QUERY_TEXT]: dbStatement,\n ...cacheProperties?.attributes,\n },\n });\n}\n\n// --- redis v2-v3: `RedisClient.prototype.internal_send_command(command_obj)` ---\n\n// Settles via `command_obj.callback`, not the sync return — so instead of\n// `bindTracingChannelToSpan` we open the span in `start`, wrap the callback to end it, and end on `error` for sync throws.\nfunction subscribeLegacyRedisCommand(cacheOptions: RedisCacheOptions): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.REDIS_COMMAND);\n const noop = (): void => {};\n channel.subscribe({\n end: noop,\n asyncStart: noop,\n asyncEnd: noop,\n start(data) {\n const command = data.arguments?.[0] as LegacyRedisCommand | undefined;\n if (!command || typeof command !== 'object') {\n return;\n }\n // The span is ended via the wrapped callback (or the sync-throw `error` path). A\n // command with no callback has no completion signal to end it on, so don't open one.\n const originalCallback = command.callback;\n if (typeof originalCallback !== 'function') {\n return;\n }\n const client = data.self as LegacyRedisClient | undefined;\n const attributes: SpanAttributes = {\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_REDIS,\n [SENTRY_ORIGIN]: ORIGIN,\n };\n\n if (client?.connection_options?.host != null) {\n attributes[SERVER_ADDRESS] = client.connection_options.host;\n }\n if (client?.connection_options?.port != null) {\n attributes[SERVER_PORT] = client.connection_options.port;\n }\n const span = startCommandSpan(command.command, command.args ?? [], attributes, cacheOptions);\n (data as OrchestrionChannelContext & { _sentrySpan?: Span })._sentrySpan = span;\n\n const parentSpan = getActiveSpan();\n command.callback = function (this: unknown, err: Error | null | undefined, reply: unknown) {\n if (!err) {\n applyCacheResponseAttributes(span, reply);\n }\n endSpan(span, err);\n // eslint-disable-next-line prefer-rest-params\n const args = arguments as unknown as [Error | null | undefined, unknown];\n return withActiveSpan(parentSpan ?? null, () => originalCallback.apply(this, args));\n };\n },\n error(data) {\n // Synchronous throw: the wrapped callback never fires, so end here instead.\n const span = (data as OrchestrionChannelContext & { _sentrySpan?: Span })._sentrySpan;\n if (span) {\n endSpan(span, data.error);\n }\n },\n });\n}\n\n// --- node-redis v4/v5 (`@redis/client`) ---\n\nfunction bindNodeRedisCommandChannel(\n channelName: string,\n getWireArgs: (data: OrchestrionChannelContext) => Array<string | Buffer> | undefined,\n cacheOptions: RedisCacheOptions,\n): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext, OrchestrionChannelContext>(channelName);\n bindTracingChannelToSpan(\n channel,\n data => {\n const wireArgs = getWireArgs(data);\n if (!wireArgs?.length) {\n return undefined;\n }\n const commandName = String(wireArgs[0]);\n const options = (data.self as NodeRedisClient | undefined)?.options;\n return startCommandSpan(commandName, wireArgs.slice(1), nodeRedisAttributes(options), cacheOptions);\n },\n {\n beforeSpanEnd(span, data) {\n if (!('error' in data)) {\n applyCacheResponseAttributes(span, data.result);\n }\n },\n },\n );\n}\n\n// `sendCommand(args, options)` — `args` are already the wire arguments.\nfunction getSendCommandArgs(data: OrchestrionChannelContext): Array<string | Buffer> | undefined {\n const args = data.arguments?.[0];\n return Array.isArray(args) ? (args as Array<string | Buffer>) : undefined;\n}\n\n// `commandsExecutor(command, jsArgs)` — derive the wire arguments the same way\n// `@redis/client` does internally, via `command.transformArguments`.\nfunction getExecutorArgs(data: OrchestrionChannelContext): Array<string | Buffer> | undefined {\n const command = data.arguments?.[0] as RedisCommandDefinition | undefined;\n const jsArgs = data.arguments?.[1];\n if (typeof command?.transformArguments !== 'function' || !Array.isArray(jsArgs)) {\n return undefined;\n }\n try {\n return command.transformArguments(...stripCommandOptions(jsArgs));\n } catch {\n return undefined;\n }\n}\n\nfunction bindNodeRedisConnectChannel(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext, OrchestrionChannelContext>(\n CHANNELS.NODE_REDIS_CONNECT,\n );\n bindTracingChannelToSpan(channel, data => {\n const options = (data.self as NodeRedisClient | undefined)?.options;\n return startInactiveSpan({\n name: 'redis-connect',\n attributes: {\n [SENTRY_KIND]: 'client',\n ...nodeRedisAttributes(options),\n [SENTRY_OP]: DB,\n },\n });\n });\n}\n\n// Batch (multi/pipeline): one span per `exec`. Batched commands bypass `sendCommand`, so\n// the executor's `ctx.arguments[0]` (the queued commands) gives the batch size. Span shape\n// mirrors the native `node-redis:batch` span (see `redis-dc-subscriber.ts`).\nfunction bindNodeRedisBatchChannel(\n channelName: string,\n getOperation: (data: OrchestrionChannelContext) => string,\n): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext, OrchestrionChannelContext>(channelName);\n bindTracingChannelToSpan(channel, data => {\n const commands = data.arguments?.[0];\n const size = Array.isArray(commands) ? commands.length : undefined;\n const options = (data.self as NodeRedisClient | undefined)?.options;\n const operation = getOperation(data);\n return startInactiveSpan({\n name: operation,\n attributes: {\n [SENTRY_KIND]: 'client',\n ...nodeRedisAttributes(options),\n [SENTRY_OP]: DB_QUERY,\n [DB_OPERATION_NAME]: operation,\n ...(size && size > 1 ? { [DB_OPERATION_BATCH_SIZE]: size } : {}),\n },\n });\n });\n}\n\nconst _redisIntegration = ((options: RedisIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // redis v2-v3 uses a nested callback, not `bindStore`, so it subscribes\n // without the async-context binding. Kept separate so a missing binding\n // never defers it: on the bundler path the wait would push subscription\n // past `Sentry.init()` and early commands would emit with no subscriber\n invokeOrchestrionInstrumentation(client, redisModuleNames, instrumentLegacyRedis, [options], {\n requiresTracingChannelBinding: false,\n });\n // node-redis v4/v5 binds spans into async context via `bindTracingChannelToSpan`.\n invokeOrchestrionInstrumentation(client, redisModuleNames, instrumentNodeRedis, [options]);\n // ioredis `<5.11.0` (>=5.11.0 publishes its own `ioredis:*` channel, handled in `setupOnce`).\n invokeOrchestrionInstrumentation(client, ioredisModuleNames, instrumentIoredis, [options]);\n },\n setupOnce() {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n waitForTracingChannelBinding(() => {\n subscribeRedisDiagnosticChannels(diagnosticsChannel.tracingChannel, options);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentLegacyRedis(options: RedisIntegrationOptions): void {\n subscribeLegacyRedisCommand(options);\n}\n\nfunction instrumentNodeRedis(options: RedisIntegrationOptions): void {\n bindNodeRedisCommandChannel(CHANNELS.NODE_REDIS_COMMAND, getSendCommandArgs, options);\n bindNodeRedisCommandChannel(CHANNELS.NODE_REDIS_EXECUTOR, getExecutorArgs, options);\n bindNodeRedisConnectChannel();\n bindNodeRedisBatchChannel(CHANNELS.NODE_REDIS_MULTI, () => 'MULTI');\n bindNodeRedisBatchChannel(CHANNELS.NODE_REDIS_PIPELINE, () => 'PIPELINE');\n bindNodeRedisBatchChannel(CHANNELS.NODE_REDIS_BATCH, data =>\n data.arguments?.[2] !== undefined ? 'MULTI' : 'PIPELINE',\n );\n}\n\n/**\n * Adds Sentry tracing instrumentation for the [redis](https://www.npmjs.com/package/redis) and\n * [ioredis](https://www.npmjs.com/package/ioredis) libraries.\n *\n * A single integration covers every client version: `redis` v2-v3, node-redis v4/v5 (`@redis/client`)\n * and ioredis `<5.11.0` via injected channels, and node-redis `>=5.12.0` / ioredis `>=5.11.0` via\n * their native `diagnostics_channel`. Captures single commands, `connect`, and multi/pipeline batches,\n * plus cache spans for keys matching the configured `cachePrefixes`.\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.redisIntegration()],\n * });\n * ```\n */\nexport const redisIntegration = defineIntegration(_redisIntegration);\n","export {\n MESSAGING_DESTINATION_PARTITION_ID as ATTR_MESSAGING_DESTINATION_PARTITION_ID,\n MESSAGING_KAFKA_MESSAGE_KEY as ATTR_MESSAGING_KAFKA_MESSAGE_KEY,\n MESSAGING_KAFKA_MESSAGE_TOMBSTONE as ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE,\n MESSAGING_KAFKA_OFFSET as ATTR_MESSAGING_KAFKA_OFFSET,\n} from '@sentry/conventions/attributes';\n\nexport const MESSAGING_OPERATION_TYPE_VALUE_PROCESS = 'process' as const;\nexport const MESSAGING_OPERATION_TYPE_VALUE_RECEIVE = 'receive' as const;\nexport const MESSAGING_OPERATION_TYPE_VALUE_SEND = 'send' as const;\nexport const MESSAGING_SYSTEM_VALUE_KAFKA = 'kafka' as const;\n\n// `_OTHER` is OTel's fallback bucket when no more specific `error.type` is known.\nexport const ERROR_TYPE_VALUE_OTHER = '_OTHER' as const;\n","/*\n * Copyright The OpenTelemetry Authors, Aspecto\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-kafkajs\n * - Upstream version: @opentelemetry/instrumentation-kafkajs@0.27.0\n * - Span builders migrated to the `@sentry/core` span API. Kept byte-identical in span name/attributes\n * for parity with the OTel integration this replaces, except for the span name under span streaming,\n * which follows the Sentry messaging conventions.\n */\n\nimport {\n ERROR_TYPE,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PROCESS, QUEUE_PUBLISH, QUEUE_RECEIVE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes, SpanLink } from '@sentry/core';\nimport {\n getClient,\n getTraceData,\n hasSpanStreamingEnabled,\n isObjectLike,\n propagationContextFromHeaders,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { KafkaMessage, Message } from './types';\nimport {\n ATTR_MESSAGING_DESTINATION_PARTITION_ID,\n ATTR_MESSAGING_KAFKA_MESSAGE_KEY,\n ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE,\n ATTR_MESSAGING_KAFKA_OFFSET,\n ERROR_TYPE_VALUE_OTHER,\n MESSAGING_OPERATION_TYPE_VALUE_RECEIVE,\n MESSAGING_OPERATION_TYPE_VALUE_SEND,\n MESSAGING_SYSTEM_VALUE_KAFKA,\n} from './semconv';\n\nconst PRODUCER_ORIGIN = 'auto.queue.kafkajs.producer';\nconst CONSUMER_ORIGIN = 'auto.queue.kafkajs.consumer';\n\n// `@opentelemetry/api` `TraceFlags`, inlined to avoid an OTel dep: SAMPLED = 0x1, NONE = 0x0.\nconst TRACE_FLAG_SAMPLED = 1;\nconst TRACE_FLAG_NONE = 0;\n\ninterface ConsumerSpanOptions {\n topic: string;\n message: KafkaMessage | undefined;\n operationType: 'process' | 'receive';\n attributes: SpanAttributes;\n links?: SpanLink[];\n}\n\n/**\n * Reads a header value off a kafkajs message as a string. kafkajs delivers headers as `Buffer`s (or\n * arrays of them), so we normalize to a string before handing them to Sentry's trace helpers.\n */\nexport function getHeaderAsString(headers: KafkaMessage['headers'], key: string): string | undefined {\n const value = headers?.[key];\n if (value == null) {\n return undefined;\n }\n return Array.isArray(value) ? value[0]?.toString() : value.toString();\n}\n\n/**\n * Builds a span link to the producer span carried in the message headers, mirroring the upstream\n * behavior of linking each batch-processed message to its originating producer span.\n */\nexport function getLinksFromHeaders(headers: KafkaMessage['headers']): SpanLink[] | undefined {\n const sentryTrace = getHeaderAsString(headers, 'sentry-trace');\n if (!sentryTrace) {\n return undefined;\n }\n\n const { traceId, parentSpanId, sampled } = propagationContextFromHeaders(\n sentryTrace,\n getHeaderAsString(headers, 'baggage'),\n );\n if (!parentSpanId) {\n return undefined;\n }\n\n return [\n {\n context: {\n traceId,\n spanId: parentSpanId,\n isRemote: true,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n },\n },\n ];\n}\n\n/**\n * The Kafka message key is producer-supplied payload data, so `dataCollection.queues` gates it.\n * Everything else on the span (topic, partition, offset) is structural metadata and stays.\n */\nfunction collectMessageKey(key: unknown, client = getClient()): string | undefined {\n if (!key || client?.getDataCollectionOptions().queues === false) {\n return undefined;\n }\n return String(key);\n}\n\n/** Starts an inactive consumer (process/receive) span carrying the kafkajs messaging attributes. */\nexport function startConsumerSpan({ topic, message, operationType, links, attributes }: ConsumerSpanOptions): Span {\n // The batch \"receive\" span is named `poll`; per-message spans use the operation type verbatim.\n const operationName = operationType === MESSAGING_OPERATION_TYPE_VALUE_RECEIVE ? 'poll' : operationType;\n\n const isBatchReceive = operationType === MESSAGING_OPERATION_TYPE_VALUE_RECEIVE;\n\n const client = getClient();\n\n return startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? `${operationType} ${topic}` : `${operationName} ${topic}`,\n links,\n attributes: {\n [SENTRY_OP]: isBatchReceive ? QUEUE_RECEIVE : QUEUE_PROCESS,\n [SENTRY_KIND]: isBatchReceive ? 'client' : 'consumer',\n ...attributes,\n [MESSAGING_SYSTEM]: MESSAGING_SYSTEM_VALUE_KAFKA,\n [MESSAGING_DESTINATION_NAME]: topic,\n [MESSAGING_OPERATION_TYPE]: operationType,\n [MESSAGING_OPERATION_NAME]: operationName,\n [ATTR_MESSAGING_KAFKA_MESSAGE_KEY]: collectMessageKey(message?.key, client),\n [ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]: message?.key && message.value === null ? true : undefined,\n [ATTR_MESSAGING_KAFKA_OFFSET]: message?.offset as string | undefined,\n // Mirror the upstream behavior of only tagging per-message processing spans (not the batch\n // receiving span, which carries no message) with the auto origin.\n ...(message ? { [SENTRY_ORIGIN]: CONSUMER_ORIGIN } : {}),\n },\n });\n}\n\n/** Starts an inactive producer span and propagates its trace into the message headers. */\nexport function startProducerSpan(topic: string, message: Message): Span {\n const span = startInactiveSpan({\n name: `send ${topic}`,\n attributes: {\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_KIND]: 'producer',\n [MESSAGING_SYSTEM]: MESSAGING_SYSTEM_VALUE_KAFKA,\n [MESSAGING_DESTINATION_NAME]: topic,\n [ATTR_MESSAGING_KAFKA_MESSAGE_KEY]: collectMessageKey(message.key),\n [ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]: message.key && message.value === null ? true : undefined,\n [ATTR_MESSAGING_DESTINATION_PARTITION_ID]:\n message.partition !== undefined ? String(message.partition) : undefined,\n [MESSAGING_OPERATION_NAME]: 'send',\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_TYPE_VALUE_SEND,\n [SENTRY_ORIGIN]: PRODUCER_ORIGIN,\n },\n });\n\n // Propagate the producer span's trace to consumers via the message headers.\n message.headers = message.headers ?? {};\n const traceData = getTraceData({ span });\n if (traceData['sentry-trace']) {\n message.headers['sentry-trace'] = traceData['sentry-trace'];\n }\n if (traceData.baggage) {\n message.headers['baggage'] = traceData.baggage;\n }\n\n return span;\n}\n\n/**\n * Marks all `spans` with the error status and `error.type` derived from a settle-time `reason`,\n * WITHOUT ending them. Mirrors the vendored `endSpansOnPromise` catch block. The producer path (which\n * receives discrete `error`/`asyncEnd` channel events) applies the error on `error` and ends on\n * `asyncEnd`; the consumer path folds this into `endSpansOnPromise`.\n */\nexport function applyErrorToSpans(spans: Span[], reason: unknown): void {\n let errorMessage: string | undefined;\n let errorType: string = ERROR_TYPE_VALUE_OTHER;\n if (typeof reason === 'string' || reason === undefined) {\n errorMessage = reason;\n } else if (isObjectLike(reason) && Object.prototype.hasOwnProperty.call(reason, 'message')) {\n errorMessage = (reason as { message?: string }).message;\n errorType = (reason as { constructor: { name: string } }).constructor.name;\n }\n\n spans.forEach(span => {\n span.setAttribute(ERROR_TYPE, errorType);\n span.setStatus({ code: SPAN_STATUS_ERROR, message: errorMessage });\n });\n}\n\n/**\n * Resolves once `promise` settles, applying the error status to all `spans` on failure and ending\n * them regardless. Used by the consumer path, which invokes the user callback directly (and so holds a\n * real promise). Verbatim from the vendored `endSpansOnPromise`.\n */\nexport function endSpansOnPromise<T>(spans: Span[], promise: Promise<T>): Promise<T> {\n return Promise.resolve(promise)\n .catch(reason => {\n applyErrorToSpans(spans, reason);\n throw reason;\n })\n .finally(() => {\n spans.forEach(span => span.end());\n });\n}\n","/*\n * Copyright The OpenTelemetry Authors, Aspecto\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-kafkajs\n * - Upstream version: @opentelemetry/instrumentation-kafkajs@0.27.0\n * - Span-creating wrappers for the consumer callbacks (`_getConsumerEachMessagePatch`/\n * `_getConsumerEachBatchPatch`), migrated to the `@sentry/core` span API. The `run` channel's `start`\n * subscriber swaps the user's `eachMessage`/`eachBatch` for these before the original runs.\n */\n\nimport { MESSAGING_BATCH_MESSAGE_COUNT } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { continueTrace, startNewTrace, withActiveSpan } from '@sentry/core';\nimport {\n ATTR_MESSAGING_DESTINATION_PARTITION_ID,\n MESSAGING_OPERATION_TYPE_VALUE_PROCESS,\n MESSAGING_OPERATION_TYPE_VALUE_RECEIVE,\n} from './semconv';\nimport { endSpansOnPromise, getHeaderAsString, getLinksFromHeaders, startConsumerSpan } from './spans';\nimport type { EachBatchHandler, EachMessageHandler, KafkaMessage } from './types';\n\n// Marks a callback we've already wrapped. A user can reuse one config object across multiple\n// `consumer.run(config)` calls (e.g. a second consumer); without this guard the second `start` would\n// wrap the wrapper and emit duplicate spans per message.\nconst consumerCallbackWrapped: unique symbol = Symbol('sentry-kafkajs-consumer-callback-wrapped');\n\ntype MaybeWrapped = { [consumerCallbackWrapped]?: true };\n\n/** Whether `fn` is a callback this module already wrapped, so callers skip re-wrapping it. */\nexport function isWrappedConsumerCallback(fn: unknown): boolean {\n return typeof fn === 'function' && (fn as MaybeWrapped)[consumerCallbackWrapped] === true;\n}\n\n/** Wraps `eachMessage` so each processed message becomes a consumer span parented to the message's producer. */\nexport function wrapEachMessage(original: EachMessageHandler): EachMessageHandler {\n const wrapped: EachMessageHandler & MaybeWrapped = function eachMessage(this: unknown, payload) {\n const sentryTrace = getHeaderAsString(payload.message.headers, 'sentry-trace');\n const baggage = getHeaderAsString(payload.message.headers, 'baggage');\n\n // Continue the producer's trace so the consumer span is parented to the message's producer.\n return continueTrace({ sentryTrace, baggage }, () => {\n const span = startConsumerSpan({\n topic: payload.topic,\n message: payload.message,\n operationType: MESSAGING_OPERATION_TYPE_VALUE_PROCESS,\n attributes: {\n [ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.partition),\n },\n });\n\n const promise = withActiveSpan(span, () => original.call(this, payload));\n return endSpansOnPromise([span], promise);\n });\n };\n wrapped[consumerCallbackWrapped] = true;\n return wrapped;\n}\n\n/** Wraps `eachBatch` so the batch pull becomes a fresh-root receiving span with a process span per message. */\nexport function wrapEachBatch(original: EachBatchHandler): EachBatchHandler {\n const wrapped: EachBatchHandler & MaybeWrapped = function eachBatch(this: unknown, payload) {\n // A batch pull aggregates messages from many producers, so the receiving span is a fresh root\n // trace and each processed message links back to its own producer span. Mirrors the OTel messaging\n // semantic conventions for a topic with multiple consumers.\n const receivingSpan = startNewTrace(() =>\n startConsumerSpan({\n topic: payload.batch.topic,\n message: undefined,\n operationType: MESSAGING_OPERATION_TYPE_VALUE_RECEIVE,\n attributes: {\n [MESSAGING_BATCH_MESSAGE_COUNT]: payload.batch.messages.length,\n [ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition),\n },\n }),\n );\n\n return withActiveSpan(receivingSpan, () => {\n const spans: Span[] = [receivingSpan];\n payload.batch.messages.forEach((message: KafkaMessage) => {\n spans.push(\n startConsumerSpan({\n topic: payload.batch.topic,\n message,\n operationType: MESSAGING_OPERATION_TYPE_VALUE_PROCESS,\n links: getLinksFromHeaders(message.headers),\n attributes: {\n [ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition),\n },\n }),\n );\n });\n const promise = original.call(this, payload);\n return endSpansOnPromise(spans, promise);\n });\n };\n wrapped[consumerCallbackWrapped] = true;\n return wrapped;\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { kafkajsModuleNames } from '../../orchestrion/config/kafkajs';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { isWrappedConsumerCallback, wrapEachBatch, wrapEachMessage } from './consumer';\nimport { applyErrorToSpans, startProducerSpan } from './spans';\nimport type { ConsumerRunConfig, ProducerBatch } from './types';\n\n// NOTE: this uses the same name as the OTel `Kafka` integration by design, so the OTel integration\n// is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Kafka' as const;\n\n/** The tracing-channel context the transform attaches around `messageProducer.js`'s `sendBatch`. */\ninterface SendBatchChannelContext extends OrchestrionChannelContext {\n // `arguments[0]` is the `{ topicMessages }` batch (kafkajs normalizes `send` into `sendBatch`).\n arguments: [ProducerBatch?, ...unknown[]];\n // The producer spans opened at `start`, ended on `asyncEnd` (and marked errored on `error`).\n _sentrySpans?: Span[];\n}\n\n/** The tracing-channel context the transform attaches around `consumer/index.js`'s `run`. */\ninterface ConsumerRunChannelContext extends OrchestrionChannelContext {\n // `arguments[0]` is the `run(config)` config whose `eachMessage`/`eachBatch` we swap in place.\n arguments: [ConsumerRunConfig?, ...unknown[]];\n}\n\nfunction subscribeToProducer(): void {\n const channel = diagnosticsChannel.tracingChannel<SendBatchChannelContext>(CHANNELS.KAFKAJS_SEND_BATCH);\n // Node types `subscribe` as requiring every lifecycle handler; runtime accepts a partial set, so we\n // pass only the ones we use (matching `bindTracingChannelToSpan`'s handling in `tracing-channel.ts`).\n const subscribers: Partial<TracingChannelSubscribers<SendBatchChannelContext>> = {\n start(ctx) {\n const spans: Span[] = [];\n // `startProducerSpan` mutates each message's headers; doing it at `start` means the mutation\n // reaches the real call, propagating the producer's trace to consumers.\n (ctx.arguments[0]?.topicMessages ?? []).forEach(topicMessage => {\n topicMessage.messages.forEach(message => {\n spans.push(startProducerSpan(topicMessage.topic, message));\n });\n });\n ctx._sentrySpans = spans;\n },\n error(ctx) {\n if (ctx._sentrySpans) {\n applyErrorToSpans(ctx._sentrySpans, ctx.error);\n }\n },\n asyncEnd(ctx) {\n // `asyncEnd` fires on both success and failure; `error` (above) has already set the status.\n ctx._sentrySpans?.forEach(span => span.end());\n },\n };\n channel.subscribe(subscribers as TracingChannelSubscribers<SendBatchChannelContext>);\n}\n\nfunction subscribeToConsumer(): void {\n const channel = diagnosticsChannel.tracingChannel<ConsumerRunChannelContext>(CHANNELS.KAFKAJS_CONSUMER_RUN);\n const subscribers: Partial<TracingChannelSubscribers<ConsumerRunChannelContext>> = {\n start(ctx) {\n const config = ctx.arguments[0];\n if (!config || typeof config !== 'object') {\n return;\n }\n // Swap the user callbacks for span-creating wrappers before `run` destructures its config. The\n // `isWrappedConsumerCallback` guard keeps this idempotent: a config object reused across another\n // `run` (or a second consumer) must not have its wrapper wrapped again, which would double spans.\n if (typeof config.eachMessage === 'function' && !isWrappedConsumerCallback(config.eachMessage)) {\n config.eachMessage = wrapEachMessage(config.eachMessage);\n }\n if (typeof config.eachBatch === 'function' && !isWrappedConsumerCallback(config.eachBatch)) {\n config.eachBatch = wrapEachBatch(config.eachBatch);\n }\n },\n };\n channel.subscribe(subscribers as TracingChannelSubscribers<ConsumerRunChannelContext>);\n}\n\nconst _kafkaIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, kafkajsModuleNames, instrumentKafkajs, [], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentKafkajs(): void {\n subscribeToProducer();\n subscribeToConsumer();\n}\n\n/**\n * Diagnostics-channel-based kafkajs integration.\n *\n * Subscribes to the `orchestrion:kafkajs:*` diagnostics_channels that Sentry's code transform\n * injects into `kafkajs`'s `producer/messageProducer.js` (`sendBatch`) and `consumer/index.js` (`run`).\n * Requires the Sentry runtime hook or bundler plugin to be active.\n *\n * Known limitation vs. the OTel integration it replaces: the wrapping producer-`transaction` span is\n * not emitted (the transformer can't replace `transaction()`'s return value to patch commit/abort).\n * Transactional `send`/`sendBatch` calls still produce producer spans, since they route through the\n * same instrumented `sendBatch`.\n */\nexport const kafkaIntegration = defineIntegration(_kafkaIntegration);\n","// The `@sentry/conventions` db/net attribute keys are deprecated (superseded by newer semconv), but we\n// emit them deliberately to preserve parity with what `@opentelemetry/instrumentation-knex` produced.\n/* oxlint-disable typescript/no-deprecated */\n\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport {\n debug,\n defineIntegration,\n getActiveSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n truncate,\n waitForTracingChannelBinding,\n} from '@sentry/core';\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_SYSTEM_NAME,\n DB_USER,\n NETWORK_TRANSPORT,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { getSqlQueryAttributes, getSqlSpanName, toSqlDialect } from '../utils/sql';\n\n// NOTE: this uses the same name as the OTel integration by design. `@sentry/node`'s `knexIntegration`\n// picks this subscriber over the vendored OTel path when orchestrion injection is active.\nconst INTEGRATION_NAME = 'Knex' as const;\nconst ORIGIN = 'auto.db.knex';\n\n// Max length of the query text captured in `db.query.text`; \"...\" is appended when truncated, so the\n// truncated statement caps at 1024 chars (1 KiB), matching `@opentelemetry/instrumentation-knex`.\nconst MAX_QUERY_LENGTH = 1021;\n\n// `db.sql.table` is deprecated and not exported by `@sentry/conventions`, so keep it local. Matches\n// what `@opentelemetry/instrumentation-knex` emitted.\nconst ATTR_DB_SQL_TABLE = 'db.sql.table';\n\nconst DB_SYSTEM_SQLITE = 'sqlite';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\n\n// The span active when a builder is created, reused as the parent when the query runs later (the query\n// often executes in a different async context than the builder was created in).\nconst parentSpanSymbol = Symbol('sentry.orchestrion.knex.parent-span');\n\ninterface KnexQuery {\n sql?: string;\n method?: string;\n bindings?: unknown[];\n}\n\ninterface KnexConnectionConfig {\n filename?: string;\n database?: string;\n user?: string;\n host?: string;\n port?: number;\n connectionString?: string;\n}\n\ninterface KnexBuilder {\n _single?: { table?: unknown };\n toString?: () => string;\n [parentSpanSymbol]?: Span;\n}\n\ninterface KnexClient {\n driverName?: string;\n config?: { connection?: KnexConnectionConfig };\n _formatQuery?: (sql: string, bindings: unknown[]) => string;\n SqlString?: { format: (sql: string, bindings: unknown[]) => string };\n}\n\ninterface KnexRunner {\n client?: KnexClient;\n builder?: KnexBuilder;\n}\n\n/** Context orchestrion attaches to the `orchestrion:knex:query` channel (wrapping `Runner.query`). */\ninterface KnexQueryChannelContext extends OrchestrionChannelContext {\n // `arguments[0]` is the query object (`{ sql, method, bindings }`).\n arguments: [KnexQuery?];\n self?: KnexRunner;\n}\n\nconst _knexIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n DEBUG_BUILD && debug.log(`[instrumentation:knex] subscribing to channel \"${CHANNELS.KNEX_QUERY}\"`);\n\n waitForTracingChannelBinding(() => {\n subscribeBuilder(CHANNELS.KNEX_QUERY_BUILDER);\n subscribeBuilder(CHANNELS.KNEX_SCHEMA_BUILDER);\n subscribeBuilder(CHANNELS.KNEX_RAW);\n subscribeQuery();\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Bookkeeping only: stash the span active at builder-creation time onto the returned builder. It is\n * read back as the parent when the query runs (see `subscribeQuery`), because the query often executes\n * in a different async context. A `Client` builder method is synchronous, so its `result` (the builder)\n * is available on the channel's `end`.\n */\nfunction subscribeBuilder(channelName: string): void {\n diagnosticsChannel.tracingChannel(channelName).end.subscribe(message => {\n const builder = (message as OrchestrionChannelContext).result;\n if (!builder || typeof builder !== 'object' || parentSpanSymbol in builder) {\n return;\n }\n\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n Object.defineProperty(builder, parentSpanSymbol, { value: activeSpan });\n });\n}\n\nfunction subscribeQuery(): void {\n bindTracingChannelToSpan<KnexQueryChannelContext>(\n diagnosticsChannel.tracingChannel<KnexQueryChannelContext>(CHANNELS.KNEX_QUERY),\n // oxlint-disable-next-line complexity\n data => {\n const runner = data.self;\n const builder = runner?.builder;\n\n // The builder captures the span active when it was created (see `subscribeBuilder`).\n // `onlyIfParent`: only instrument queries that run as part of an existing trace, matching OTel.\n const parentSpan = builder?.[parentSpanSymbol] ?? getActiveSpan();\n if (!parentSpan) {\n return undefined;\n }\n\n const query = data.arguments[0];\n const client = runner?.client;\n const connection = client?.config?.connection;\n const connectionString = connection?.connectionString;\n const table = extractTableName(builder);\n const operation = query?.method;\n const dbNameSpace =\n connection?.filename || connection?.database || extractDatabaseFromConnectionString(connectionString);\n const dbSystem = mapSystem(client?.driverName);\n\n const dialect = toSqlDialect(client?.driverName);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n ...getSqlQueryAttributes(query?.sql ? truncate(query.sql, MAX_QUERY_LENGTH) : undefined, dialect),\n 'knex.version': data.moduleVersion,\n [DB_SYSTEM_NAME]: dbSystem,\n [ATTR_DB_SQL_TABLE]: table,\n [DB_OPERATION_NAME]: operation,\n [DB_USER]: connection?.user,\n [DB_NAMESPACE]: dbNameSpace,\n [SERVER_ADDRESS]: connection?.host ?? extractHostFromConnectionString(connectionString),\n [SERVER_PORT]: connection?.port ?? extractPortFromConnectionString(connectionString),\n [NETWORK_TRANSPORT]: connection?.filename === ':memory:' ? 'inproc' : undefined,\n };\n\n return startInactiveSpan({\n name: getSqlSpanName(attributes, 'knex.query'),\n parentSpan,\n attributes,\n });\n },\n {\n beforeSpanEnd(span, data) {\n // knex prefixes query errors with the full SQL (\"<query> - <error>\"). Strip it so the span\n // status message is just the driver error, matching the vendored OTel instrumentation.\n if ('error' in data) {\n const message = cleanErrorMessage(data);\n if (message !== undefined) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n }\n }\n },\n },\n );\n}\n\nfunction cleanErrorMessage(data: KnexQueryChannelContext): string | undefined {\n const error = data.error;\n if (!error || typeof error !== 'object' || typeof (error as { message?: unknown }).message !== 'string') {\n return undefined;\n }\n\n const rawMessage = (error as { message: string }).message;\n const query = data.arguments[0];\n if (!query?.sql) {\n return rawMessage;\n }\n\n try {\n const formatter = getFormatter(data.self);\n const fullQuery = formatter(query.sql, query.bindings || []);\n return rawMessage.replace(`${fullQuery} - `, '');\n } catch {\n return rawMessage;\n }\n}\n\nfunction getFormatter(runner: KnexRunner | undefined): (sql: string, bindings: unknown[]) => string {\n if (runner) {\n const client = runner.client;\n if (client) {\n if (client._formatQuery) {\n return client._formatQuery.bind(client);\n } else if (client.SqlString) {\n return client.SqlString.format.bind(client.SqlString);\n }\n }\n if (runner.builder?.toString) {\n return runner.builder.toString.bind(runner.builder);\n }\n }\n\n return () => '<noop formatter>';\n}\n\nfunction mapSystem(driverName: string | undefined): string | undefined {\n if (driverName === 'sqlite3') {\n return DB_SYSTEM_SQLITE;\n }\n if (driverName === 'pg') {\n return DB_SYSTEM_POSTGRESQL;\n }\n return driverName;\n}\n\nfunction extractTableName(builder: KnexBuilder | undefined): string | undefined {\n const table = builder?._single?.table;\n if (table && typeof table === 'object') {\n return extractTableName(table);\n }\n return typeof table === 'string' ? table : undefined;\n}\n\nfunction extractDatabaseFromConnectionString(connectionString: string | undefined): string | undefined {\n if (!connectionString) {\n return undefined;\n }\n try {\n const db = new URL(connectionString).pathname?.replace(/^\\//, '');\n return db || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction extractHostFromConnectionString(connectionString: string | undefined): string | undefined {\n if (!connectionString) {\n return undefined;\n }\n try {\n return new URL(connectionString).hostname || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction extractPortFromConnectionString(connectionString: string | undefined): number | undefined {\n if (!connectionString) {\n return undefined;\n }\n try {\n const port = new URL(connectionString).port;\n return port ? parseInt(port, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Diagnostics-channel-based knex integration.\n *\n * Subscribes to the `orchestrion:knex:*` diagnostics_channels that Sentry's code transform\n * injects into knex's `Runner.query` (span) and `Client.queryBuilder`/`schemaBuilder`/`raw` (parent-span\n * bookkeeping). Requires the Sentry runtime hook or bundler plugin to be active.\n */\nexport const knexIntegration = defineIntegration(_knexIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { Integration, IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport {\n _INTERNAL_shouldSkipAiProviderWrapping,\n getClient,\n hasSpanStreamingEnabled,\n startInactiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_PROVIDER_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/openai';\nimport { instrumentStream } from '../ai/openai/streaming';\nimport type { OpenAiOptions } from '../ai/openai/types';\nimport { addResponseAttributes } from '../ai/openai/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n/**\n * Describes an OpenAI-compatible provider whose SDK mirrors the openai wire format (Groq, Together, ...),\n * so the span building, streaming and response parsing can all be reused from `ai/openai`.\n */\nexport interface OpenAiCompatibleProvider {\n /** Integration name; also the key used to skip double-wrapping when another provider drives the SDK. */\n integrationName: string;\n /** Value reported on `gen_ai.provider.name`. */\n providerName: string;\n /** Span origin, `auto.ai.<provider>`. */\n origin: string;\n /** The instrumented `module.name`s (from the orchestrion config's `getModuleNames`). */\n moduleNames: string[];\n /** The fully-qualified orchestrion channels this provider publishes to. */\n channels: { chat: string; embeddings: string };\n}\n\n/**\n * Builds a diagnostics-channel integration for an OpenAI-compatible provider SDK. It subscribes to the\n * `orchestrion:<module>:{chat,embeddings}` channels injected into the SDK's `create` methods, so it\n * requires the Sentry runtime hook or bundler plugin. Everything below the channel — request/response\n * attributes and streaming — is shared with the openai integration; only the provider name and origin\n * differ.\n */\nexport function createOpenAiCompatibleIntegration<T extends OpenAiCompatibleProvider>(\n provider: T,\n): (options?: OpenAiOptions) => Integration & { name: T['integrationName'] } {\n const instrumentedChannels = [\n { channel: provider.channels.chat, operation: 'chat' },\n { channel: provider.channels.embeddings, operation: 'embeddings' },\n ] as const;\n\n function instrument(options: OpenAiOptions): void {\n for (const { channel, operation } of instrumentedChannels) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, provider, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, options)) {\n end();\n }\n },\n end,\n ) || wrapStreamResult(span, data, options),\n },\n );\n }\n }\n\n return ((options: OpenAiOptions = {}) => {\n return {\n name: provider.integrationName,\n setup(client) {\n invokeOrchestrionInstrumentation(client, provider.moduleNames, instrument, [options]);\n },\n };\n }) satisfies IntegrationFn;\n}\n\n/**\n * Build the span for an instrumented `create` call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n provider: OpenAiCompatibleProvider,\n options: OpenAiOptions,\n): Span | undefined {\n // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks this\n // provider as skipped; skip here to avoid double spans.\n if (_INTERNAL_shouldSkipAiProviderWrapping(provider.integrationName)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n // `extractRequestAttributes` defaults the provider to openai; override it for the concrete provider.\n const attributes = extractRequestAttributes(args, operation, recordInputs);\n attributes[GEN_AI_PROVIDER_NAME] = provider.providerName;\n attributes[SENTRY_ORIGIN] = provider.origin;\n const model = (params?.model as string) || 'unknown';\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * For a streaming `create({ stream: true })` the result is a `Stream` the caller consumes later. We can't\n * swap what `create` returns, but the `Stream` in `data.result` is the same instance the caller holds and\n * we observe it before the caller iterates — so we patch its async iterator in place to run through\n * `instrumentStream`, which accumulates the streamed attributes and ends the span when iteration finishes.\n * Only a streaming call resolves to an async-iterable, so that check alone distinguishes it. Returns `true`\n * to hand span-ending ownership to `instrumentStream`; `false` for non-streaming/errored results, which end\n * via the normal `beforeSpanEnd` path.\n */\nfunction wrapStreamResult(span: Span, data: OrchestrionChannelContext, options: OpenAiOptions): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs ?? false);\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n","import { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { groqModuleNames } from '../orchestrion/config/groq';\nimport { createOpenAiCompatibleIntegration } from './openai-compatible';\n\n// Exported so LangChain can add it to its provider-skip list: `@langchain/groq` drives `groq-sdk`, so\n// a `ChatGroq` call would otherwise open both a LangChain span and this integration's Groq span.\nexport const GROQ_INTEGRATION_NAME = 'Groq' as const;\n\n/**\n * Instruments the `groq-sdk` client (chat completions and embeddings). Groq speaks the OpenAI wire format,\n * so this reuses the openai span/streaming logic; see `createOpenAiCompatibleIntegration`. Requires the\n * Sentry runtime hook or bundler plugin so the diagnostics channels get injected into `groq-sdk`.\n */\nexport const groqIntegration = defineIntegration(\n createOpenAiCompatibleIntegration({\n integrationName: GROQ_INTEGRATION_NAME,\n providerName: 'groq',\n origin: 'auto.ai.groq',\n moduleNames: groqModuleNames,\n channels: { chat: CHANNELS.GROQ_CHAT, embeddings: CHANNELS.GROQ_EMBEDDINGS },\n }),\n);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { _INTERNAL_skipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { ANTHROPIC_AI_INTEGRATION_NAME } from '../ai/anthropic-ai/constants';\nimport { GOOGLE_GENAI_INTEGRATION_NAME } from '../ai/google-genai/constants';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { LANGCHAIN_INTEGRATION_NAME } from '../ai/langchain/constants';\nimport { _INTERNAL_getLangChainEmbeddingsSpanOptions } from '../ai/langchain/embeddings';\nimport { recordTypeSafeClassifierState } from '../ai/langchain/typesafe-classifier';\nimport type { LangChainOptions } from '../ai/langchain/types';\nimport {\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n _INTERNAL_mergeLangChainCallbackHandler,\n} from '../ai/langchain/utils';\nimport { MISTRAL_INTEGRATION_NAME } from '../ai/mistral/constants';\nimport { OPENAI_INTEGRATION_NAME } from '../ai/openai/constants';\nimport { GROQ_INTEGRATION_NAME } from './groq';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langchainEmbeddingsChannels } from '../orchestrion/config/langchain';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { langchainModuleNames } from '../orchestrion/config/langchain';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangChain' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGCHAIN_INTEGRATION_NAME;\n\n// LangChain drives the underlying AI provider SDKs itself, so while it's active those providers must\n// not also instrument, or every call would produce two spans (mirrors the OTel path's skip list).\nconst SKIPPED_PROVIDERS = [\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n MISTRAL_INTEGRATION_NAME,\n // `@langchain/groq` drives `groq-sdk`, so ChatGroq calls must not also open the Groq integration's span.\n GROQ_INTEGRATION_NAME,\n];\n\n// The chat-model channels carry the live args array of `invoke(input, options)` / `_streamIterator(input, options)`.\n// The embeddings channels carry the instance (`self`) and the `embedQuery(text)` / `embedDocuments(texts)` args.\n// Registered lazily on the first LangChain call (not at `setupOnce`) so a direct provider call made\n// before any LangChain call still gets its own span — matches the OTel patch-on-import timing. It\n// also stops the underlying SDK from double-instrumenting embeddings, whose `embedQuery`/\n// `embedDocuments` call the provider SDK (e.g. `openai`) internally.\nfunction markProvidersSkipped(): void {\n _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);\n}\n\nconst _langChainIntegration = ((options: LangChainOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Chat models only mutate the call args, so they subscribe without the\n // async-context binding. Kept separate so a missing binding never defers\n // them: on the bundler path the wait would push subscription past\n // `Sentry.init()` and early calls would run with no subscriber.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentChatModels, [options], {\n requiresTracingChannelBinding: false,\n });\n // Embeddings open their own spans via `bindTracingChannelToSpan`, which\n // needs the binding.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentEmbeddings, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentChatModels(options: LangChainOptions): void {\n // One stateful handler tracks spans across the whole run tree, just like the OTel path.\n const sentryHandler = createLangChainCallbackHandler(options);\n\n // Chat models: inject the Sentry callback handler into the call options (arg 1). LangChain's own\n // callback dispatch then creates the spans, exactly as in the OTel path, so no span is opened\n // here — a `start` subscriber (which also makes orchestrion wrap the function) is enough.\n const injectHandler = (message: unknown): void => {\n const args = (message as OrchestrionChannelContext).arguments;\n if (!Array.isArray(args)) {\n return;\n }\n\n let callOptions = args[1] as Record<string, unknown> | undefined;\n if (!callOptions || typeof callOptions !== 'object' || Array.isArray(callOptions)) {\n callOptions = {};\n args[1] = callOptions;\n }\n\n // Without callbacks of its own, the call would otherwise lose the parent run and its tracers (e.g. LangSmith).\n callOptions.callbacks = _INTERNAL_mergeLangChainCallbackHandler(\n callOptions.callbacks ?? getInheritedLangChainCallbacks(),\n sentryHandler,\n );\n\n const conversationIdMetadata = getConversationIdMetadataFromConfig(callOptions);\n if (Object.keys(conversationIdMetadata).length) {\n callOptions.metadata = { ...conversationIdMetadata, ...(callOptions.metadata as Record<string, unknown>) };\n }\n };\n\n for (const channelName of [CHANNELS.LANGCHAIN_CHAT_MODEL_INVOKE, CHANNELS.LANGCHAIN_CHAT_MODEL_STREAM]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName).start.subscribe(message => {\n markProvidersSkipped();\n injectHandler(message);\n });\n }\n\n // `TypeSafeClassifier` calls Jev with `fetch`, not through a provider SDK, so nothing needs skipping.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGCHAIN_TYPESAFE_CLASSIFIER_INVOKE)\n .start.subscribe(message => {\n injectHandler(message);\n const { self, arguments: args } = message as OrchestrionChannelContext;\n recordTypeSafeClassifierState(self, args?.[0]);\n });\n}\n\n// Embeddings don't use the callback system. Wrap the method in its own span.\n// Embedding errors reject to the caller, so we only open the span (which bindTracingChannelToSpan\n// still marks failed on error) and do not capture them.\nfunction instrumentEmbeddings(options: LangChainOptions): void {\n for (const channelName of langchainEmbeddingsChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName), data =>\n createEmbeddingsSpan(data, options),\n );\n }\n}\n\nfunction createEmbeddingsSpan(data: OrchestrionChannelContext, options: LangChainOptions): Span {\n // `embedQuery`/`embedDocuments` call the provider SDK internally, so skip that SDK's own\n // instrumentation before its channel fires (the producer runs at the embeddings channel's `start`).\n markProvidersSkipped();\n\n const input = (data.arguments ?? [])[0];\n\n return startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, input, options));\n}\n\n/**\n * Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/core`'s `BaseChatModel` (to inject the Sentry callback handler) and into\n * `@langchain/openai`'s embedding methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const langChainIntegration = defineIntegration(_langChainIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, isObjectLike } from '@sentry/core';\nimport { resolveAIRecordingOptions } from '../ai/core/utils';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { instrumentCompiledGraph, isInsideManualLangGraphInstrumentation } from '../ai/langgraph';\nimport { LANGGRAPH_INTEGRATION_NAME } from '../ai/langgraph/constants';\nimport type { LangGraphOptions } from '../ai/langgraph/types';\nimport { extractAgentNameFromParams, extractLLMFromParams, wrapToolsWithSpans } from '../ai/langgraph/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langgraphModuleNames } from '../orchestrion/config/langgraph';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangGraph' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGGRAPH_INTEGRATION_NAME;\n\n// `createReactAgent` compiles a `StateGraph` internally. When set, the compile subscriber skips that nested\n// graph, so the createReactAgent handler wraps it with the agent's name and model instead.\nlet insideCreateReactAgent = false;\n\nconst _langGraphIntegration = ((options: LangGraphOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Nothing here opens a span at subscribe time, so a missing async-context\n // binding must never defer the subscription.\n invokeOrchestrionInstrumentation(client, langgraphModuleNames, instrumentLanggraph, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentLanggraph(options: LangGraphOptions): void {\n const resolvedOptions = resolveAIRecordingOptions(options);\n const sentryHandler = createLangChainCallbackHandler(resolvedOptions);\n\n // StateGraph.compile returns synchronously; wrap the returned graph's `invoke` and `stream` at `end`.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE)\n .end.subscribe(message => {\n if (insideCreateReactAgent || isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n instrumentCompiledGraph(result, getFirstArgObject(args) ?? {}, resolvedOptions, null, sentryHandler);\n });\n\n // createReactAgent only wraps tools and the returned graph's `invoke` and `stream`. Tools are wrapped at\n // `start` (before the agent runs), the graph at `end`.\n const reactAgentChannel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(\n CHANNELS.LANGGRAPH_CREATE_REACT_AGENT,\n );\n reactAgentChannel.start.subscribe(message => {\n // `createReactAgent` runs synchronously and compiles a `StateGraph` internally, so the flag\n // must be on for the duration and off by `end`. It's set here (never in a branch that can\n // throw) and cleared in both `end` and `error`, so it can neither stick on across calls nor\n // stay off during this call's nested compile. Tool wrapping is guarded for the same reason.\n insideCreateReactAgent = true;\n try {\n const { arguments: args } = message as OrchestrionChannelContext;\n const params = getFirstArgObject(args);\n if (params && Array.isArray(params.tools) && params.tools.length > 0) {\n wrapToolsWithSpans(params.tools, resolvedOptions, extractAgentNameFromParams(args) ?? undefined);\n }\n } catch (error) {\n DEBUG_BUILD && debug.error('[instrumentation:langgraph] failed to wrap createReactAgent tools', error);\n }\n });\n reactAgentChannel.end.subscribe(message => {\n insideCreateReactAgent = false;\n if (isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n const agentName = extractAgentNameFromParams(args) ?? undefined;\n const compileOptions = agentName ? { name: agentName } : {};\n instrumentCompiledGraph(result, compileOptions, resolvedOptions, extractLLMFromParams(args), sentryHandler);\n });\n // Make sure a thrown `createReactAgent` doesn't leave the suppression flag stuck on.\n reactAgentChannel.error.subscribe(() => {\n insideCreateReactAgent = false;\n });\n}\n\nfunction getFirstArgObject(args: unknown[] | undefined): Record<string, unknown> | undefined {\n const first = (args ?? [])[0];\n\n return isObjectLike(first) ? first : undefined;\n}\n\n/**\n * Diagnostics-channel-based LangGraph integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/langgraph`'s `StateGraph.compile` and `createReactAgent`, so it requires\n * the Sentry runtime hook or bundler plugin.\n */\nexport const langGraphIntegration = defineIntegration(_langGraphIntegration);\n","import type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, GLOBAL_OBJ } from '@sentry/core';\nimport type { FlueOptions } from '../ai/flue';\nimport { createFlueInstrumentation } from '../ai/flue';\nimport { FLUE_INTEGRATION_NAME, FLUE_MODULE_NAME } from '../ai/flue/constants';\nimport { DEBUG_BUILD } from '../debug-build';\n\ntype FlueInstrumentFn = (instrumentation: ReturnType<typeof createFlueInstrumentation>) => unknown;\n\n/**\n * The `instrument` we last registered against, so a second `setup()` in the same isolate is a\n * no-op. Cloudflare runs `init()` per request, and with `cacheClient: false` that reaches here\n * every time: in production Flue throws on the repeat, and under `vite dev` it disposes our\n * previous registration instead — ending the turn and tool spans of every in-flight request.\n *\n * Keyed on the binding rather than a bare boolean so a fresh `@flue/runtime` instance (a new\n * isolate reusing this module, a test swapping the marker) still registers.\n */\nlet registeredBinding: FlueInstrumentFn | undefined;\n\n/**\n * Register the instrumentation with Flue on the user's behalf, when the runtime binding is available.\n *\n * Flue is registered rather than patched, so this needs `@flue/runtime`'s own `instrument()`. In a\n * bundled worker, `@sentry/cloudflare/vite` has the package publish it on the global marker.\n * Elsewhere this no-ops and users call `instrument(Sentry.createFlueInstrumentation())` themselves.\n */\nconst _flueIntegration = ((options: FlueOptions = {}) => {\n return {\n name: FLUE_INTEGRATION_NAME,\n setup() {\n const provided = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.providedModules?.[FLUE_MODULE_NAME];\n const instrument = provided?.instrument as FlueInstrumentFn | undefined;\n\n if (typeof instrument !== 'function') {\n DEBUG_BUILD && debug.log('[Flue] no provided `@flue/runtime` binding; skipping auto-registration');\n return;\n }\n\n if (instrument === registeredBinding) {\n DEBUG_BUILD && debug.log('[Flue] already registered in this isolate; skipping auto-registration');\n return;\n }\n\n try {\n instrument(createFlueInstrumentation(options));\n registeredBinding = instrument;\n } catch (error) {\n // Never rethrow: `setup()` runs inside `Sentry.init()`, which core calls unguarded and\n // Cloudflare calls per request, so throwing here would take down the request handler.\n if ((error as Error | undefined)?.name === 'InstrumentationAlreadyInstalledError') {\n // The app owns the key and we will never win it, so stop rebuilding the instrumentation\n // (two 1000-entry `LRUMap`s) on every later `init()`.\n registeredBinding = instrument;\n DEBUG_BUILD && debug.log('[Flue] already instrumented by the app; skipping auto-registration');\n } else {\n debug.warn('[Flue] auto-registration failed; Flue spans will not be recorded:', error);\n }\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const flueIntegration = defineIntegration(_flueIntegration);\n","import type { Span } from '@sentry/core';\nimport {\n GEN_AI_COST_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_COST_CACHE_READ_INPUT_TOKENS,\n GEN_AI_COST_INPUT_TOKENS,\n GEN_AI_COST_OUTPUT_TOKENS,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\n\n/**\n * Token counts and costs of a pi-ai response. `input` and `cost.input` leave the cache tokens out;\n * `reasoning` is part of `output`.\n */\nexport interface PiAiUsage {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n reasoning?: number;\n totalTokens?: number;\n cost?: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n total?: number;\n };\n}\n\n/**\n * Set the token and cost attributes of a pi-ai response. The conventions count cached tokens in\n * `gen_ai.usage.input_tokens` and their cost in `gen_ai.cost.input_tokens`, so both are summed here.\n *\n * `unbilled` is true for a response the provider may not have billed: a failed request, or one the\n * provider parked to answer later. Its counters are all 0, which would read as a real zero-cost\n * call, so nothing is set for it unless it reports tokens.\n */\nexport function setPiAiUsageAttributes(span: Span, usage: PiAiUsage | undefined, unbilled?: boolean): void {\n if (!usage || (unbilled && !usage.totalTokens)) {\n return;\n }\n\n const attributes: Record<string, number> = {};\n const set = (key: string, value: number | undefined): void => {\n if (typeof value === 'number') {\n attributes[key] = value;\n }\n };\n\n set(GEN_AI_USAGE_INPUT_TOKENS, sum(usage.input, usage.cacheRead, usage.cacheWrite));\n set(GEN_AI_USAGE_OUTPUT_TOKENS, usage.output);\n set(GEN_AI_USAGE_TOTAL_TOKENS, usage.totalTokens);\n set(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, usage.cacheRead);\n set(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, usage.cacheWrite);\n set(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.reasoning);\n\n set(GEN_AI_COST_INPUT_TOKENS, sum(usage.cost?.input, usage.cost?.cacheRead, usage.cost?.cacheWrite));\n set(GEN_AI_COST_OUTPUT_TOKENS, usage.cost?.output);\n set(GEN_AI_COST_TOTAL_TOKENS, usage.cost?.total);\n set(GEN_AI_COST_CACHE_READ_INPUT_TOKENS, usage.cost?.cacheRead);\n set(GEN_AI_COST_CACHE_CREATION_INPUT_TOKENS, usage.cost?.cacheWrite);\n\n span.setAttributes(attributes);\n}\n\nfunction sum(...values: (number | undefined)[]): number | undefined {\n const numbers = values.filter((value): value is number => typeof value === 'number');\n return numbers.length ? numbers.reduce((total, value) => total + value, 0) : undefined;\n}\n","import type { Span, StartSpanOptions } from '@sentry/core';\nimport {\n getCurrentScope,\n getIsolationScope,\n isURLObjectRelative,\n parseStringToURLObject,\n SPAN_STATUS_ERROR,\n stringify,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_REASONING_LEVEL,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT } from '@sentry/conventions/op';\nimport { PI_AI_ORIGIN } from './constants';\nimport type { PiAiContext } from './messages';\nimport {\n piAiAssistantMessageToGenAiMessage,\n piAiFinishReason,\n piAiMessagesToGenAiMessages,\n piAiSystemInstructions,\n piAiToolDefinitions,\n} from './messages';\nimport type { PiAssistantMessage, PiModel, PiStreamOptions } from './types';\nimport { setPiAiUsageAttributes } from './usage';\n\ninterface PiAiChatRequest {\n model: PiModel;\n /** Absent for the deferred calls, which pass a handle in place of the request context. */\n context?: PiAiContext;\n callOptions?: PiStreamOptions;\n streaming: boolean;\n recordInputs: boolean;\n}\n\n/** The span options of the `gen_ai.chat` span of a pi-ai request. */\nexport function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptions {\n const { model, context, callOptions, streaming, recordInputs } = request;\n const conversationId =\n getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId;\n\n return {\n name: model.id ? `chat ${model.id}` : 'chat',\n op: GEN_AI_CHAT,\n attributes: {\n [SENTRY_ORIGIN]: PI_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_PROVIDER_NAME]: model.provider,\n [GEN_AI_REQUEST_MODEL]: model.id,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n [GEN_AI_RESPONSE_STREAMING]: streaming || undefined,\n [GEN_AI_REQUEST_TEMPERATURE]: callOptions?.temperature,\n [GEN_AI_REQUEST_MAX_TOKENS]: callOptions?.maxTokens,\n [GEN_AI_REQUEST_REASONING_LEVEL]: callOptions?.reasoning,\n ...getServerAttributes(model),\n ...(recordInputs && context ? getRequestContentAttributes(context) : {}),\n },\n };\n}\n\n/**\n * Record the settled message of a pi-ai request on its span. pi-ai never rejects a request: a\n * provider failure or an abort settles as a message with `stopReason` `error` or `aborted`.\n */\nexport function setPiAiResponseAttributes(span: Span, message: PiAssistantMessage, recordOutputs: boolean): void {\n const { responseModel, model, responseId, stopReason, usage } = message;\n\n const finishReason = piAiFinishReason(stopReason);\n const output = recordOutputs ? piAiAssistantMessageToGenAiMessage(message, finishReason) : undefined;\n\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL]: responseModel ?? model,\n [GEN_AI_RESPONSE_ID]: responseId,\n [GEN_AI_RESPONSE_FINISH_REASONS]: finishReason ? stringify([finishReason]) : undefined,\n [GEN_AI_OUTPUT_MESSAGES]: output ? stringify([output], String) : undefined,\n });\n\n const failed = stopReason === 'error';\n setPiAiUsageAttributes(span, usage, failed || stopReason === 'deferred');\n\n if (failed) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n } else if (stopReason === 'aborted') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n}\n\nfunction getServerAttributes(model: PiModel): Record<string, string | number | undefined> {\n const url = model.baseUrl ? parseStringToURLObject(model.baseUrl) : undefined;\n if (!url || isURLObjectRelative(url) || !url.hostname) {\n return {};\n }\n return { [SERVER_ADDRESS]: url.hostname, [SERVER_PORT]: url.port ? Number(url.port) : undefined };\n}\n\nfunction getRequestContentAttributes(context: PiAiContext): Record<string, string | undefined> {\n const messages = piAiMessagesToGenAiMessages(context.messages);\n const tools = piAiToolDefinitions(context);\n return {\n [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context),\n [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined,\n [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined,\n };\n}\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, isThenable, startInactiveSpan } from '@sentry/core';\nimport type { GenAiOptions } from '../ai/core/utils';\nimport { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../ai/pi-ai/chat';\nimport { PI_AI_INTEGRATION_NAME } from '../ai/pi-ai/constants';\nimport type { PiAiContext } from '../ai/pi-ai/messages';\nimport { isInsidePiAiSpan } from '../ai/pi-ai/providers';\nimport { resolvePiAiRecordingOptions } from '../ai/pi-ai/recording';\nimport type { PiEventStream, PiStreamOptions } from '../ai/pi-ai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { piAiModuleNames } from '../orchestrion/config/pi-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\nexport type PiAiOptions = GenAiOptions;\n\ntype PiAiChannelContext = OrchestrionChannelContext & { _sentryRecordOutputs?: boolean };\n\nconst _piAiIntegration = ((options: PiAiOptions = {}) => {\n return {\n name: PI_AI_INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, piAiModuleNames, instrumentPiAi, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPiAi(options: PiAiOptions): void {\n const streamChannel = diagnosticsChannel.tracingChannel<PiAiChannelContext>(CHANNELS.PI_AI_STREAM);\n const completeChannel = diagnosticsChannel.tracingChannel<PiAiChannelContext>(CHANNELS.PI_AI_COMPLETE);\n\n const startSpan = (data: PiAiChannelContext, streaming: boolean): Span | undefined => {\n // `complete` awaits `stream`, and the `compat` functions hand some models to a `Models` of their\n // own, so a traced call can make another one. Only the outermost gets a span.\n if (isInsidePiAiSpan()) {\n return undefined;\n }\n const [model, context, callOptions] = data.arguments ?? [];\n const { recordInputs, recordOutputs } = resolvePiAiRecordingOptions(options);\n data._sentryRecordOutputs = recordOutputs;\n return startInactiveSpan(\n getPiAiChatSpanOptions({\n model: model ?? {},\n // The deferred calls pass a handle here, which carries no request content.\n context: context as PiAiContext | undefined,\n callOptions: callOptions as PiStreamOptions | undefined,\n streaming,\n recordInputs,\n }),\n );\n };\n\n const setResponse = (span: Span, data: PiAiChannelContext, message: unknown): void => {\n if (message && typeof message === 'object') {\n setPiAiResponseAttributes(span, message, !!data._sentryRecordOutputs);\n }\n };\n\n bindTracingChannelToSpan(streamChannel, data => startSpan(data, true), {\n // The stream is returned before the request settles; its `result()` settles with the message.\n deferSpanEnd: ({ span, data, end }) => {\n const events = data.result as Partial<PiEventStream> | undefined;\n const settled = 'error' in data || typeof events?.result !== 'function' ? undefined : events.result();\n if (!isThenable(settled)) {\n return false;\n }\n settled.then(message => {\n setResponse(span, data, message);\n end();\n }, end);\n return true;\n },\n });\n\n bindTracingChannelToSpan(completeChannel, data => startSpan(data, false), {\n beforeSpanEnd: (span, data) => {\n if (!('error' in data)) {\n setResponse(span, data, data.result);\n }\n },\n });\n}\n\n/**\n * Traces the requests sent with pi-ai (`@earendil-works/pi-ai` >= 0.80.0 < 2) as `gen_ai.chat` spans,\n * through `createModels()` or the standalone `stream` and `complete` functions. Needs the Sentry\n * runtime hook (`--import`) or bundler plugin. This includes the model calls of Flue and pi-durable\n * agents, which send them through pi-ai.\n *\n * @example\n * ```javascript\n * Sentry.init({\n * integrations: [Sentry.piAiIntegration({ recordInputs: true, recordOutputs: true })],\n * });\n * ```\n */\nexport const piAiIntegration = defineIntegration(_piAiIntegration);\n","export const PI_DURABLE_INTEGRATION_NAME = 'PiDurable' as const;\n\nexport const PI_DURABLE_ORIGIN = 'auto.ai.pi_durable';\n\n/** Task kinds of the pi-durable built-in tasks. */\nexport const PI_TASK = {\n GENERATION: 'pi.generation',\n TOOL: 'pi.tool',\n COMPACTION: 'pi.compaction',\n} as const;\n\n/** Kind of the built-in document that holds a conversation's run control. */\nexport const PI_LIVE_DOC_KIND = 'pi.live';\n\n/** Kind of the built-in document that holds a conversation's provider session id. */\nexport const PI_PROVIDER_DOC_KIND = 'pi.provider';\n\n/** Kind of the transcript entry that holds the tool result the model receives. */\nexport const PI_TOOL_RESULT_ENTRY_KIND = 'pi.tool-result';\n\n/**\n * Cap on open run spans. A run span is removed when the run settles, but a run the process never\n * sees settle (a crash, or a settlement the scheduler writes outside a task phase) would otherwise\n * stay in the map for the lifetime of the process.\n */\nexport const MAX_TRACKED_PI_RUNS = 1000;\n","/** Read a member with `this` bound to the original, so getters and methods that use `this` keep working. */\nexport function bound(target: object, property: PropertyKey): unknown {\n const value: unknown = Reflect.get(target, property, target);\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n}\n","import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n","import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiOptions } from '../core/utils';\nimport { resolveAIRecordingOptions } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(tool: PiTool, runs: PiRuns, options: GenAiOptions): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n","import type { Scope } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n getCurrentScope,\n getDefaultIsolationScope,\n SPAN_STATUS_ERROR,\n startNewTrace,\n withActiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes';\nimport type { GenAiOptions } from '../core/utils';\nimport { setPiAiRecordingOptions } from '../pi-ai/recording';\nimport { PI_DURABLE_ORIGIN, PI_TASK } from './constants';\nimport type { PiRuns } from './runs';\nimport { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs';\nimport { instrumentTool, instrumentToolPhase } from './tools';\nimport type {\n PiHarness,\n PiHarnessOptions,\n PiPhaseHandler,\n PiRegistryReader,\n PiRegistrySnapshot,\n PiTask,\n PiTaskRuntime,\n PiTool,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\nexport type PiDurableOptions = GenAiOptions;\n\nconst INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented');\nconst RUNS = Symbol.for('sentry.pi-durable.runs');\n\n/**\n * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's\n * `registry` object is wrapped, never modified. The result has the caller's options as prototype:\n * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live,\n * getters included.\n *\n * Spans:\n * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that\n * created the conversation for a subagent;\n * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`;\n * - `gen_ai.execute_tool` for each tool call, under its run.\n *\n * The scheduler starts task phases from whichever async context last woke it, often an unrelated\n * request. Every phase therefore runs in its run's own scopes and trace, never in the ones it\n * inherits.\n */\nexport function instrumentPiDurableHarnessOptions<T extends PiHarnessOptions>(\n harnessOptions: T,\n options: PiDurableOptions = {},\n): T {\n if (!harnessOptions || (harnessOptions as Record<symbol, unknown>)[INSTRUMENTED]) {\n return harnessOptions;\n }\n\n const runs = createRuns();\n const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true });\n const instrumented: T = Object.create(harnessOptions, {\n ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}),\n // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going.\n // Only an app that passed its own `onReport` gets a chance to handle them.\n onReport: own((error: unknown) => {\n captureException(error, { mechanism: { handled: !!harnessOptions.onReport, type: PI_DURABLE_ORIGIN } });\n harnessOptions.onReport?.(error);\n }),\n });\n addNonEnumerableProperty(instrumented, INSTRUMENTED, true);\n addNonEnumerableProperty(instrumented, RUNS, runs);\n return instrumented;\n}\n\n/**\n * End the open runs and tool calls of `harness` when it closes. Closing stops the scheduler without\n * settling the inputs in flight, so nothing else would end their spans, and the maps that track\n * them would keep the spans for the lifetime of the process. A run whose ending commit is still in\n * flight ends with that commit's status.\n */\nexport function endRunsOnClose(harnessOptions: PiHarnessOptions, harness: unknown): void {\n const runs = (harnessOptions as Record<symbol, unknown>)[RUNS] as PiRuns | undefined;\n const closable = harness as PiHarness | undefined;\n if (!runs || typeof closable?.subscribeClose !== 'function') {\n return;\n }\n closable.subscribeClose(() => {\n for (const run of runs.active.values()) {\n endRun(run, runs, run.pendingEnd ? run.pendingEnd.status : { code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n for (const calls of runs.toolCalls.values()) {\n for (const call of calls) {\n if (call.endTimestamp === undefined) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n call.span.end(call.endTimestamp);\n }\n }\n runs.toolCalls.clear();\n runs.owners.clear();\n });\n}\n\nfunction instrumentRegistry(registry: PiRegistryReader, options: PiDurableOptions, runs: PiRuns): PiRegistryReader {\n // Cached so identity stays stable: the scheduler hands a task over to a new definition whenever\n // `snapshot().task(kind)` returns a different object than the one it runs.\n const snapshots = new WeakMap<PiRegistrySnapshot, PiRegistrySnapshot>();\n const tasks = new WeakMap<PiTask, PiTask>();\n const tools = new WeakMap<PiTool, PiTool>();\n\n const wrapTool = (tool: PiTool): PiTool => {\n let wrapped = tools.get(tool);\n if (!wrapped) {\n wrapped = instrumentTool(tool, runs, options);\n tools.set(tool, wrapped);\n }\n return wrapped;\n };\n\n const wrapTask = (task: PiTask | undefined): PiTask | undefined => {\n if (!task?.definition?.phases) {\n return task;\n }\n let wrapped = tasks.get(task);\n if (!wrapped) {\n const { definition } = task;\n // pi-durable calls a phase on the `phases` object and `abort` on the definition; keep that\n // receiver, so handlers that use `this` work.\n const wrapPhase =\n (phase: PiPhaseHandler, receiver: unknown, isAbort = false): PiPhaseHandler =>\n (taskRecord, runtime, context) =>\n runPhase(\n definition.name,\n observed => phase.call(receiver, taskRecord, observed, context),\n runtime,\n context,\n runs,\n wrapTool,\n isAbort,\n options,\n );\n const phases: Record<string, PiPhaseHandler> = {};\n for (const [name, phase] of Object.entries(definition.phases)) {\n phases[name] = typeof phase === 'function' ? wrapPhase(phase, definition.phases) : phase;\n }\n wrapped = {\n ...task,\n definition: {\n ...definition,\n phases,\n ...(typeof definition.abort === 'function' ? { abort: wrapPhase(definition.abort, definition, true) } : {}),\n },\n };\n tasks.set(task, wrapped);\n }\n return wrapped;\n };\n\n const wrapSnapshot = (snapshot: PiRegistrySnapshot): PiRegistrySnapshot => {\n let wrapped = snapshots.get(snapshot);\n if (!wrapped) {\n wrapped = new Proxy(snapshot, {\n get(target, property) {\n if (property === 'task') {\n return (name: string) => wrapTask(target.task(name));\n }\n if (property === 'tasks') {\n return () => target.tasks().map(task => wrapTask(task));\n }\n return bound(target, property);\n },\n });\n snapshots.set(snapshot, wrapped);\n }\n return wrapped;\n };\n\n return new Proxy(registry, {\n get(target, property) {\n if (property === 'snapshot') {\n return () => wrapSnapshot(target.snapshot());\n }\n return bound(target, property);\n },\n });\n}\n\nfunction runPhase(\n kind: string,\n phase: (runtime: PiTaskRuntime) => Promise<unknown>,\n runtime: PiTaskRuntime,\n context: unknown,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isAbort: boolean,\n options: PiDurableOptions,\n): Promise<unknown> {\n const { conversationId } = runtime;\n const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;\n // A compaction joins the run it was started for. One started while idle has no run, and its\n // `chat` span becomes the root of a trace of its own. An abort handler ends the run of its task,\n // so it joins that run but never starts one. Tasks of extensions never join a run.\n const run =\n isRunWork || kind === PI_TASK.COMPACTION\n ? (runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : undefined))\n : undefined;\n\n let observed = runtime;\n let finishToolPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n observed = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);\n observed = toolPhase.runtime;\n finishToolPhase = toolPhase.finish;\n }\n\n const runInScope = async (scope: Scope): Promise<unknown> => {\n // Read at the first phase of a run, which is a `pi.tool` phase when a restarted Harness reruns a\n // tool call, and at each phase outside a run, such as an idle compaction or a task of an extension.\n let sessionId = run?.sessionId;\n if (!sessionId) {\n sessionId = await readProviderSessionId(runtime, context);\n if (run && sessionId) {\n run.sessionId = sessionId;\n run.span.setAttribute(GEN_AI_CONVERSATION_ID, sessionId);\n }\n }\n scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));\n setPiAiRecordingOptions(scope, options);\n try {\n return await phase(observed);\n } catch (error) {\n // The scheduler faults a task whose phase throws, and a faulted generation ends its run. A\n // throw after an abort mark, or once the Harness closes, is not a fault.\n if (!runtime.signal?.aborted) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n if (run && kind === PI_TASK.GENERATION) {\n endRun(run, runs, { code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n throw error;\n } finally {\n finishToolPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));\n}\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, isObjectLike } from '@sentry/core';\nimport type { PiDurableOptions } from '../ai/pi-durable';\nimport { endRunsOnClose, instrumentPiDurableHarnessOptions } from '../ai/pi-durable';\nimport { PI_DURABLE_INTEGRATION_NAME } from '../ai/pi-durable/constants';\nimport { markBuiltInTool } from '../ai/pi-durable/tools';\nimport type { PiHarnessOptions } from '../ai/pi-durable/types';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { piDurableModuleNames } from '../orchestrion/config/pi-durable';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\nconst _piDurableIntegration = ((options: PiDurableOptions = {}) => {\n return {\n name: PI_DURABLE_INTEGRATION_NAME,\n setup(client) {\n // Subscribing opens no span; spans open later, inside task phases.\n invokeOrchestrionInstrumentation(client, piDurableModuleNames, instrumentPiDurable, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPiDurable(options: PiDurableOptions): void {\n const harnessOpen = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.PI_DURABLE_HARNESS_OPEN);\n\n harnessOpen.start.subscribe(message => {\n const args = (message as OrchestrionChannelContext).arguments;\n try {\n if (args && isObjectLike(args[1])) {\n args[1] = instrumentPiDurableHarnessOptions(args[1] as PiHarnessOptions, options);\n }\n } catch (error) {\n DEBUG_BUILD && debug.error('[instrumentation:pi-durable] failed to instrument Harness options', error);\n }\n });\n\n harnessOpen.asyncEnd.subscribe(message => {\n const { arguments: args, result } = message as OrchestrionChannelContext;\n try {\n if (args && isObjectLike(args[1])) {\n endRunsOnClose(args[1], result);\n }\n } catch (error) {\n DEBUG_BUILD && debug.error('[instrumentation:pi-durable] failed to observe Harness close', error);\n }\n });\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.PI_DURABLE_CODING_TOOL)\n .end.subscribe(message => markBuiltInTool((message as OrchestrionChannelContext).result));\n}\n\n/**\n * Diagnostics-channel-based integration for pi-durable (`@earendil-works/pi-durable` >= 1.0.0 < 2,\n * whose API is experimental). Subscribes to the `orchestrion:@earendil-works/pi-durable:harnessOpen`\n * channel injected into `Harness.open()` and to the `codingTool` channel injected into the built-in\n * tool factories, so it requires the Sentry runtime hook or bundler plugin.\n *\n * Traces one `gen_ai.invoke_agent` span per run, with its tool calls as `gen_ai.execute_tool`\n * children. Its model requests become `gen_ai.chat` children through `piAiIntegration`, since\n * pi-durable sends them through pi-ai.\n */\nexport const piDurableIntegration = defineIntegration(_piDurableIntegration);\n","import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport { isObjectLike } from '@sentry/core';\nimport type { ClassifierEvaluationCall } from '../ai/mastra/classifier-evaluation';\nimport { processClassifierEvaluationData, setStartingClassifierEvaluation } from '../ai/mastra/classifier-evaluation';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages } from '../ai/core/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { safeChannelCallback } from '../tracing-channel';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\n\n/**\n * Add the evaluated state, questions and answers of a `Classifier.evaluate()` call to the exporter's\n * `classifier_evaluation` span, which Mastra leaves without input or output.\n */\nexport function recordClassifierEvaluations(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_CLASSIFIER_EVALUATE);\n const calls = new WeakMap<object, ClassifierEvaluationCall>();\n\n channel.start.subscribe(message => {\n safeChannelCallback(() => {\n const call: ClassifierEvaluationCall = {};\n calls.set(message as object, call);\n setStartingClassifierEvaluation(call);\n });\n });\n // `evaluate()` has reached its first `await`, so Mastra has already started its span.\n channel.end.subscribe(() => {\n safeChannelCallback(() => setStartingClassifierEvaluation(undefined));\n });\n channel.asyncEnd.subscribe(message => {\n safeChannelCallback(() => {\n const call = calls.get(message as object);\n if (call) {\n finishClassifierEvaluation(call, message as OrchestrionChannelContext);\n }\n });\n });\n}\n\nfunction finishClassifierEvaluation(call: ClassifierEvaluationCall, message: OrchestrionChannelContext): void {\n call.settled = true;\n const { span, recordInputs, recordOutputs } = call;\n if (!span) {\n return;\n }\n\n const params = isObjectLike(message.arguments[0]) ? message.arguments[0] : {};\n // Questions given to the constructor take precedence over the ones passed to `evaluate()`, as in Mastra.\n const questions = (isObjectLike(message.self) ? message.self.questions : undefined) ?? params.questions;\n const data = processClassifierEvaluationData(call, {\n input: recordInputs ? { state: params.state, questions } : undefined,\n output: recordOutputs && isObjectLike(message.result) ? message.result.answers : undefined,\n });\n\n if (isObjectLike(data?.input)) {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(data.input));\n }\n if (data?.output !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(data.output));\n }\n\n if (call.endTime) {\n span.end(call.endTime);\n }\n}\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { IntegrationFn } from '@sentry/core';\nimport {\n captureException,\n consoleSandbox,\n debug,\n defineIntegration,\n GLOBAL_OBJ,\n isObjectLike,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n COMMUNITY_MASTRA_SENTRY_EXPORTER_NAME,\n MASTRA_EXPORTER_BRAND,\n MASTRA_INTEGRATION_NAME,\n} from '../ai/mastra/constants';\nimport { SentryMastraExporter } from '../ai/mastra';\nimport type { MastraExporterOptions } from '../ai/mastra';\nimport { getSentrySpanForMastraId } from '../ai/mastra/span-registry';\nimport type { MastraObservabilityExporter } from '../ai/mastra/types';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { mastraModuleNames } from '../orchestrion/config/mastra';\nimport { recordClassifierEvaluations } from './mastra-classifier';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindSpanToChannelStore, safeChannelCallback } from '../tracing-channel';\n\nexport interface MastraOptions extends MastraExporterOptions {\n /**\n * Construct a Mastra observability pipeline when the app has not configured one. Defaults to\n * `true`. Uses an `@mastra/observability` the app already has; the SDK never installs it.\n */\n bootstrapObservability?: boolean;\n}\n\ninterface MastraObservabilityInstance {\n getExporters?: () => readonly { name?: string; [MASTRA_EXPORTER_BRAND]?: boolean }[];\n}\n\ninterface MastraInstance {\n registerExporter?: (exporter: unknown, instance: unknown, entrypoint: unknown) => void;\n observability?: { getDefaultInstance?: () => MastraObservabilityInstance | undefined };\n}\n\n/** Mastra AISpan → the id the exporter keys its Sentry span on. */\nfunction mastraSpanId(span: unknown): string | undefined {\n if (!isObjectLike(span)) {\n return undefined;\n }\n const exported = span.getExportedSpanId;\n const id = typeof exported === 'function' ? exported.call(span) : span.id;\n return typeof id === 'string' ? id : undefined;\n}\n\n// `registerExporter` does not dedupe; WeakSet so short-lived instances stay collectable.\nconst registered = new WeakSet<object>();\n\n// Process-wide: several Mastra instances should not reprint this.\nlet warnedAboutCommunityExporter = false;\nlet warnedAboutMissingObservability = false;\n\nconst _mastraIntegration = ((options: MastraOptions = {}) => {\n return {\n name: MASTRA_INTEGRATION_NAME,\n setup(client) {\n // Attaching the exporter and capturing errors open no spans, so a missing async-context binding\n // must not defer them.\n invokeOrchestrionInstrumentation(client, mastraModuleNames, instrumentExporter, [options], {\n requiresTracingChannelBinding: false,\n });\n // The `executeWithContext` bridge binds spans into the async context, so it must wait for the\n // async-context binding (e.g. a custom OpenTelemetry setup wires it up late).\n invokeOrchestrionInstrumentation(client, mastraModuleNames, instrumentExecuteWithContext, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentExporter(options: MastraOptions): void {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_CONSTRUCTOR).end.subscribe(message => {\n safeChannelCallback(() => {\n const { self } = message as OrchestrionChannelContext;\n attachExporter(self, options);\n });\n });\n\n captureExecuteWithContextErrors();\n recordClassifierEvaluations();\n}\n\n/**\n * Capture errors thrown by Mastra operations as Sentry issues. Mastra runs each operation's work\n * inside `executeWithContext({ span, fn })`; when `fn` rejects, the channel's `error` carries the real\n * `Error` (with a stack), so we capture that rather than the exporter's stack-less `errorInfo`.\n * Associated with the exporter's span for that operation so it lands on the right trace. Capturing needs\n * no async context binding, so it rides the attach-only path.\n */\nfunction captureExecuteWithContextErrors(): void {\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_EXECUTE_WITH_CONTEXT)\n .error.subscribe(message => {\n safeChannelCallback(() => {\n const data = message as OrchestrionChannelContext;\n captureMastraError(data.error, (data.arguments as unknown[] | undefined)?.[0]);\n });\n });\n}\n\n/** Bound on the `cause` walk; a self- or cyclic `cause` from a wrapped error would otherwise hang. */\nconst MAX_CAUSE_CHAIN_DEPTH = 10;\n\n// Errors we've already captured, plus everything they wrap. Mastra re-throws failures wrapped in a\n// `new MastraError({ cause })`, so the same failure surfaces at outer operations as a *different*\n// object — `captureException`'s identity dedup can't see that, but the shared `cause` can.\nconst capturedErrors = new WeakSet<object>();\n\nfunction errorCauseChain(error: unknown): object[] {\n const chain: object[] = [];\n let current = error;\n for (let depth = 0; depth < MAX_CAUSE_CHAIN_DEPTH && isObjectLike(current); depth++) {\n chain.push(current);\n const cause = (current as { cause?: unknown }).cause;\n if (cause === current) {\n break;\n }\n current = cause;\n }\n return chain;\n}\n\nfunction captureMastraError(error: unknown, params: unknown): void {\n const chain = errorCauseChain(error);\n // Skip if this error — or anything it wraps, or anything wrapping it — was already captured.\n if (chain.some(link => capturedErrors.has(link))) {\n return;\n }\n chain.forEach(link => capturedErrors.add(link));\n\n const id = isObjectLike(params) ? mastraSpanId(params.span) : undefined;\n const span = id ? getSentrySpanForMastraId(id) : undefined;\n const capture = (): string => captureException(error, { mechanism: { type: 'auto.ai.mastra', handled: true } });\n\n // Attach to the operation's span so the issue lands on the right trace, when the span is still open.\n if (span) {\n withActiveSpan(span, capture);\n } else {\n capture();\n }\n}\n\n/**\n * Mastra runs each operation's work inside `executeWithContext({ span, fn })`. Bind the exporter's\n * Sentry span for that Mastra span into the async context for the call, so nested auto-instrumented\n * work (the model `fetch`, a `dataloader.load` in a tool) parents under it. This activates an existing\n * exporter span — it never opens or ends one; the exporter owns the span lifecycle.\n */\nfunction instrumentExecuteWithContext(): void {\n bindSpanToChannelStore(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_EXECUTE_WITH_CONTEXT),\n data => {\n const params = (data.arguments as unknown[] | undefined)?.[0];\n const id = isObjectLike(params) ? mastraSpanId(params.span) : undefined;\n return id ? getSentrySpanForMastraId(id) : undefined;\n },\n );\n}\n\nfunction attachExporter(instance: unknown, options: MastraOptions): void {\n if (!isObjectLike(instance) || registered.has(instance)) {\n return;\n }\n\n const mastra = instance as MastraInstance;\n if (typeof mastra.registerExporter !== 'function') {\n DEBUG_BUILD &&\n debug.log('[instrumentation:mastra] `Mastra.registerExporter` is missing; needs @mastra/core >= 1.63.2');\n return;\n }\n\n const { bootstrapObservability: _bootstrapObservability, ...exporterOptions } = options;\n const exporter = new SentryMastraExporter(exporterOptions);\n\n const defaultInstance = mastra.observability?.getDefaultInstance?.();\n if (defaultInstance) {\n const exporters = defaultInstance.getExporters?.() ?? [];\n\n if (exporters.some(registeredExporter => registeredExporter?.[MASTRA_EXPORTER_BRAND])) {\n markAttached(instance);\n DEBUG_BUILD && debug.log('[instrumentation:mastra] a Sentry exporter is already registered, skipping');\n return;\n }\n\n // Community exporter already called `Sentry.init()` and cannot be removed (add-only API).\n if (exporters.some(registeredExporter => registeredExporter?.name === COMMUNITY_MASTRA_SENTRY_EXPORTER_NAME)) {\n warnAboutCommunityExporter();\n }\n\n mastra.registerExporter(exporter, undefined, undefined);\n markAttached(instance);\n return;\n }\n\n if (options.bootstrapObservability === false) {\n DEBUG_BUILD &&\n debug.log('[instrumentation:mastra] no observability configured and bootstrapping is disabled, skipping');\n return;\n }\n\n const bootstrap = createObservabilityBootstrap(exporter);\n if (!bootstrap) {\n return;\n }\n\n mastra.registerExporter(exporter, bootstrap.instance, bootstrap.entrypoint);\n markAttached(instance);\n}\n\nfunction markAttached(instance: object): void {\n registered.add(instance);\n}\n\nfunction warnAboutMissingObservability(): void {\n if (warnedAboutMissingObservability) {\n return;\n }\n warnedAboutMissingObservability = true;\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Mastra has no observability pipeline and `@mastra/observability` could not be loaded, ' +\n 'so the Mastra integration will not create spans. Install `@mastra/observability`, or pass an ' +\n '`Observability` to the `Mastra` constructor. Disable this with ' +\n '`mastraIntegration({ bootstrapObservability: false })`.',\n );\n });\n}\n\n/** `console.warn` rather than `debug`: the app's Sentry client has been replaced. */\nfunction warnAboutCommunityExporter(): void {\n if (warnedAboutCommunityExporter) {\n return;\n }\n warnedAboutCommunityExporter = true;\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] The `@mastra/sentry` package is registered alongside the built-in Mastra integration, ' +\n 'and both are now exporting spans. Its exporter also calls `Sentry.init()` itself: depending on which ' +\n '`@sentry/node` version it resolves to, that either replaces the client configured in your ' +\n '`instrument.ts` — losing your release, environment, integrations and sampling — or starts a second, ' +\n 'independent SDK whose events never reach yours. Remove `@mastra/sentry` from your Mastra `exporters`; ' +\n 'the Sentry SDK instruments Mastra on its own.',\n );\n });\n}\n\n// `createRequire` treats its argument as a filename and resolves from `dirname(that)`.\n// Passing cwd itself would look in cwd's parent, so this dummy file (never loaded) keeps\n// resolution rooted at the app directory.\nfunction cwdRequireParent(): string {\n return join(process.cwd(), 'noop.js');\n}\n\nfunction appRequire(): ReturnType<typeof createRequire> {\n return createRequire(cwdRequireParent());\n}\n\n/**\n * The runtime injection hook records the resolved file of each instrumented module as it loads.\n * Unlike the CJS `require.cache`, this is populated for ESM-loaded modules too, so it is the\n * reliable anchor for finding the app's `@mastra/observability` next to its `@mastra/core`.\n */\nfunction findInjectedMastraCoreFilename(): string | undefined {\n const url = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.runtimeFiles?.['@mastra/core'];\n if (!url) {\n return undefined;\n }\n\n try {\n return url.startsWith('file:') ? fileURLToPath(url) : url;\n } catch {\n return undefined;\n }\n}\n\n/**\n * `@mastra/core` is already evaluated (we are in its constructor). Prefer that file so a\n * serverless/test cwd that is not the app still finds the app's `@mastra/observability`.\n * Only sees CJS-loaded modules; ESM apps rely on {@link findInjectedMastraCoreFilename}.\n */\nfunction findLoadedMastraCoreFilename(): string | undefined {\n const cache = appRequire().cache;\n if (!cache) {\n return undefined;\n }\n\n for (const filename of Object.keys(cache)) {\n if (filename.replace(/\\\\/g, '/').includes('/@mastra/core/')) {\n return filename;\n }\n }\n\n return undefined;\n}\n\nfunction tryRequireObservability(parent: string): Record<string, unknown> | undefined {\n try {\n return createRequire(parent)('@mastra/observability') as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Prefer the runtime-injected `@mastra/core` file (works under ESM and CJS), then the CJS-cached\n * copy, then cwd-resolved core, then cwd itself. A hit can still fail under pnpm if that copy\n * cannot see `@mastra/observability`, hence the fallbacks.\n */\nfunction loadMastraObservability(): Record<string, unknown> {\n // A bundled runtime (e.g. Cloudflare Workers) has no on-disk `node_modules` to\n // `createRequire` against. `@sentry/cloudflare/vite` splices a static provider import\n // into this module that stashes the `@mastra/observability` namespace on the global\n // marker, so prefer that when present.\n const injected = GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.providedModules?.['@mastra/observability'];\n if (injected) {\n return injected;\n }\n\n const parents = new Set<string>();\n const injectedCore = findInjectedMastraCoreFilename();\n if (injectedCore) {\n parents.add(injectedCore);\n }\n const loadedCore = findLoadedMastraCoreFilename();\n if (loadedCore) {\n parents.add(loadedCore);\n }\n try {\n parents.add(appRequire().resolve('@mastra/core'));\n } catch {\n // cwd is not the app, or `@mastra/core` is ESM-only and not in the CJS resolver.\n }\n parents.add(cwdRequireParent());\n\n for (const parent of parents) {\n const observability = tryRequireObservability(parent);\n if (observability) {\n return observability;\n }\n }\n\n throw new Error('Cannot resolve @mastra/observability');\n}\n\n/**\n * Mastra's default is a no-op with no pipeline. `@mastra/observability` is not a dependency of\n * `@mastra/core`, so this no-ops if the app has not installed it.\n */\nfunction createObservabilityBootstrap(\n exporter: MastraObservabilityExporter,\n): { instance: unknown; entrypoint: unknown } | undefined {\n let observabilityModule: Record<string, unknown>;\n try {\n observabilityModule = loadMastraObservability();\n } catch {\n warnAboutMissingObservability();\n return undefined;\n }\n\n const Observability = observabilityModule.Observability as\n | (new (config: unknown) => Record<string, unknown>)\n | undefined;\n const DefaultObservabilityInstance = observabilityModule.DefaultObservabilityInstance as\n | (new (config: unknown) => unknown)\n | undefined;\n\n if (!Observability || !DefaultObservabilityInstance) {\n DEBUG_BUILD && debug.log('[instrumentation:mastra] `@mastra/observability` is missing expected exports');\n return undefined;\n }\n\n return {\n instance: new DefaultObservabilityInstance({ serviceName: 'mastra', exporters: [exporter] }),\n // Empty registry: `new Observability({ configs: { default } })` already registers\n // `\"default\"`, and `Mastra.registerExporter` then throws `Tracing instance 'default' already registered`.\n entrypoint: new Observability({}),\n };\n}\n\n/**\n * Hooks the `Mastra` constructor and registers a Sentry exporter via `registerExporter()`.\n * Enabled by default. Disable with\n * `defaultIntegrations: integrations => integrations.filter(i => i.name !== 'Mastra')`.\n * Requires the runtime hook or bundler plugin, and `@mastra/core >= 1.63.2`.\n */\nexport const mastraIntegration = defineIntegration(_mastraIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { wrapMcpServerWithSentry } from '@sentry/core/server';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { mcpServerModuleNames } from '../orchestrion/config/mcp-server';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { safeChannelCallback } from '../tracing-channel';\n\nconst INTEGRATION_NAME = 'McpServer';\n\nconst _mcpServerIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // `wrapMcpServerWithSentry` only patches methods on the freshly-built instance; it opens no\n // spans itself (those come later from the wrapped transport), so a missing async-context\n // binding must not defer the subscription.\n invokeOrchestrionInstrumentation(client, mcpServerModuleNames, subscribe, [], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction subscribe(): void {\n // Wrap each newly-constructed `McpServer` the moment its constructor returns. This is the\n // automatic equivalent of a user calling `wrapMcpServerWithSentry(new McpServer(...))`; the\n // wrap's own `WeakSet` guard makes a later manual call on the same instance a no-op, so the two\n // paths coexist safely.\n for (const channel of [CHANNELS.MCP_SERVER_V2_CONSTRUCTOR, CHANNELS.MCP_SERVER_V1_CONSTRUCTOR]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel).end.subscribe(message => {\n safeChannelCallback(() => {\n const { self } = message as OrchestrionChannelContext;\n if (self) {\n wrapMcpServerWithSentry(self);\n }\n });\n });\n }\n}\n\n/**\n * Auto-instruments `@modelcontextprotocol/server` (v2) and `@modelcontextprotocol/sdk` (v1)\n * `McpServer` instances, so users no longer have to wrap them with `wrapMcpServerWithSentry`\n * by hand. Enabled by default. Requires the runtime hook or a bundler plugin (orchestrion) to\n * inject the constructor channel.\n */\nexport const mcpServerIntegration = defineIntegration(_mcpServerIntegration);\n","import { debug } from '@sentry/core';\nimport {\n _INTERNAL_handleServedNodeTunnelRequest as handleServedNodeTunnelRequest,\n _INTERNAL_httpServerHandlesTunnel as httpServerHandlesTunnel,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\n\ntype TunnelServer = { emit(event: string, ...data: unknown[]): boolean };\n\nconst tunnelServers = new WeakSet<TunnelServer>();\n\n/**\n * Wraps a Node server's `emit` once, so requests to the tunnel `serveTunnelIntegration` serves are answered before\n * any of the app's `request` listeners run. A listener for the `http.server.request.start` diagnostics channel, which\n * Node publishes right before it emits each request, so even the first request is answered. Only without core's HTTP\n * server instrumentation, whose own `emit` wrapper answers them otherwise.\n *\n * It never throws, since Node rethrows a channel listener's error as an uncaught exception.\n */\nexport function instrumentTunnelServer(message: unknown): void {\n try {\n const server = (message as { server?: TunnelServer } | undefined)?.server;\n if (!server || tunnelServers.has(server) || httpServerHandlesTunnel()) {\n return;\n }\n\n tunnelServers.add(server);\n // oxlint-disable-next-line typescript/unbound-method -- called with the server as `this` below\n const originalEmit = server.emit;\n server.emit = function (this: TunnelServer, event: string, ...data: unknown[]) {\n const [request, response] = data as Parameters<typeof handleServedNodeTunnelRequest>;\n if (event === 'request' && handleServedNodeTunnelRequest(request, response)) {\n return true;\n }\n\n return originalEmit.call(this, event, ...data);\n };\n } catch (error) {\n DEBUG_BUILD && debug.error('Sentry tunnel: failed to instrument a server', error);\n }\n}\n","import type { ServerTunnelOptions } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport {\n _INTERNAL_handleServedNodeTunnelRequest as handleServedNodeTunnelRequest,\n _INTERNAL_setNodeTunnelHandler as setNodeTunnelHandler,\n HTTP_ON_SERVER_REQUEST,\n serveTunnelIntegration as coreServeTunnelIntegration,\n} from '@sentry/core/server';\nimport { subscribe } from '../utils/diagnosticsChannel';\nimport { instrumentTunnelServer } from '../utils/tunnelServer';\n\nlet isSubscribed = false;\n\n/**\n * Lets every `node:http` server answer managed tunnel requests before the app sees them, whatever framework runs on\n * it. Nothing is answered unless the tunnel is on, through `serveTunnelIntegration` or a framework SDK.\n */\nexport function instrumentTunnelServers(): void {\n if (isSubscribed) {\n return;\n }\n\n isSubscribed = true;\n // Core's HTTP server instrumentation answers tunnel requests through it, without bundling it for apps that have no\n // tunnel.\n setNodeTunnelHandler(handleServedNodeTunnelRequest);\n subscribe(HTTP_ON_SERVER_REQUEST, instrumentTunnelServer);\n}\n\n/**\n * Makes a `serveTunnelIntegration` that, unless `intercept` is off, also runs `instrumentRuntimeServers` to answer\n * tunnel requests on the runtime's own servers, like `Bun.serve` or `Deno.serve`.\n */\nexport function makeServeTunnelIntegration(instrumentRuntimeServers?: () => void) {\n return defineIntegration((options: ServerTunnelOptions = {}) => {\n return {\n ...coreServeTunnelIntegration(options),\n setupOnce() {\n if (options.intercept !== false) {\n instrumentTunnelServers();\n instrumentRuntimeServers?.();\n }\n },\n };\n });\n}\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { lruMemoizerModuleNames } from '../orchestrion/config/lru-memoizer';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design — when enabled, the OTel\n// 'LruMemoizer' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'LruMemoizer' as const;\n\nconst _lruMemoizerIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, lruMemoizerModuleNames, instrumentLruMemoizer, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentLruMemoizer(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.LRU_MEMOIZER_LOAD),\n // We only want the helper's caller-context restore for the callback lru-memoizer fires from a detached `setImmediate`.\n () => undefined,\n );\n}\n\n/**\n * Diagnostics-channel-based lru-memoizer integration. Subscribes to\n * `orchestrion:lru-memoizer:load` (injected into `lru-memoizer/lib/async.js`'s\n * `memoizedFunction`). Creates no spans; only re-runs the memoized callback with the\n * caller's scope. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const lruMemoizerIntegration = defineIntegration(_lruMemoizerIntegration);\n","import {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core';\n\nconst DB_SYSTEM_VALUE_MONGODB = 'mongodb';\n\n/**\n * The db/collection namespace mongodb (v4+) passes to `Connection.command`\n */\nexport interface MongodbNamespace {\n db: string;\n collection?: string;\n}\n\ninterface V4Command {\n documents?: unknown[];\n cursors?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * Replaces every leaf value in the command object with '?', keeping keys\n * and Mongo operators. hides PII and improves grouping. Reproduced from\n * the OTel instrumentation.\n */\nexport function serializeDbStatement(commandObj: Record<string, unknown>): string {\n return JSON.stringify(scrubStatement(commandObj));\n}\n\nfunction scrubStatement(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(element => scrubStatement(element));\n }\n\n if (isCommandObj(value)) {\n const initial: Record<string, unknown> = {};\n return Object.entries(value)\n .map(([key, element]) => [key, scrubStatement(element)])\n .reduce((prev, current) => {\n if (isCommandEntry(current)) {\n prev[current[0]] = current[1];\n }\n return prev;\n }, initial);\n }\n\n // A value like string or number, possibly contains PII, scrub it.\n return '?';\n}\n\nfunction isCommandObj(value: unknown): value is Record<string, unknown> {\n return isObjectLike(value) && !isBuffer(value);\n}\n\nfunction isBuffer(value: unknown): boolean {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);\n}\n\nfunction isCommandEntry(value: unknown): value is [string, unknown] {\n return Array.isArray(value);\n}\n\n/**\n * Build span attributes for a mongodb v4+ command from the connection\n * context, namespace and command.\n */\nexport function getV4SpanAttributes(\n connectionCtx: { address?: string } | undefined,\n ns: MongodbNamespace,\n command: V4Command | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n let host: string | undefined;\n let port: string | undefined;\n if (connectionCtx) {\n const hostParts = typeof connectionCtx.address === 'string' ? connectionCtx.address.split(':') : '';\n if (hostParts.length === 2) {\n host = hostParts[0];\n port = hostParts[1];\n }\n }\n\n let commandObj: Record<string, unknown> | undefined;\n if (command?.documents?.[0]) {\n commandObj = command.documents[0] as Record<string, unknown>;\n } else if (command?.cursors) {\n commandObj = command.cursors as Record<string, unknown>;\n } else {\n commandObj = command;\n }\n\n return getSpanAttributes(ns.db, ns.collection, host, port, commandObj, operation, origin);\n}\n\n/**\n * Shared attribute builder used by both the v3 topology path and the v4+\n * connection path.\n */\nexport function getSpanAttributes(\n dbName: string | undefined,\n dbCollection: string | undefined,\n host: string | undefined,\n port: string | undefined,\n commandObj: Record<string, unknown> | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: origin,\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_MONGODB,\n [DB_NAMESPACE]: dbName,\n [DB_COLLECTION_NAME]: dbCollection,\n [DB_OPERATION_NAME]: operation,\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: `mongodb://${host}:${port}/${dbName}`,\n };\n\n if (host && port) {\n attributes[SERVER_ADDRESS] = host;\n const portNumber = parseInt(port, 10);\n if (!isNaN(portNumber)) {\n attributes[SERVER_PORT] = portNumber;\n }\n }\n\n if (commandObj) {\n try {\n attributes[DB_QUERY_TEXT] = serializeDbStatement(commandObj);\n } catch {\n // ignore serialization errors — the statement is best-effort metadata\n }\n }\n\n return attributes;\n}\n\n/** The v3 driver topology, from which host/port are read (mongodb 3.x). */\nexport interface MongoV3Topology {\n s?: {\n options?: { host?: string; port?: number };\n host?: string;\n port?: number;\n };\n description?: { address?: string };\n}\n\n/**\n * Determine the operation name for a mongodb v3 `command` from the command\n * document, mirroring the vendored instrumentation. Returns `undefined` for\n * commands it doesn't classify (e.g. `endSessions`).\n */\nexport function getV3CommandOperation(command: Record<string, unknown>): string | undefined {\n if (command.createIndexes !== undefined) {\n return 'createIndexes';\n } else if (command.findandmodify !== undefined) {\n return 'findAndModify';\n } else if (command.ismaster !== undefined) {\n return 'isMaster';\n } else if (command.count !== undefined) {\n return 'count';\n } else if (command.aggregate !== undefined) {\n return 'aggregate';\n }\n return undefined;\n}\n\n/**\n * Build span attributes for a mongodb v3 operation from the topology,\n * namespace string and command.\n */\nexport function getV3SpanAttributes(\n ns: string,\n topology: MongoV3Topology | undefined,\n command: Record<string, unknown> | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n let host: string | undefined;\n let port: string | undefined;\n if (topology?.s) {\n host = topology.s.options?.host ?? topology.s.host;\n port = (topology.s.options?.port ?? topology.s.port)?.toString();\n if (host == null || port == null) {\n const address = topology.description?.address;\n if (address) {\n const segments = address.split(':');\n host = segments[0];\n port = segments[1];\n }\n }\n }\n\n // The namespace is `[db].[collection-or-index]`; coerce to string\n // (might be a MongoDBNamespace)\n const [dbName, dbCollection] = ns.toString().split('.');\n const commandObj =\n (command?.query as Record<string, unknown> | undefined) ??\n (command?.q as Record<string, unknown> | undefined) ??\n command;\n\n return getSpanAttributes(dbName, dbCollection, host, port, commandObj, operation, origin);\n}\n\n/**\n * Start a mongodb client span on the stable conventions.\n *\n * The `db` op is set explicitly rather than relying on `inferDbSpanData`,\n * to support platforms that lack it (ie, Deno).\n */\nexport function startMongoSpan(attributes: SpanAttributes): Span {\n const operation = attributes[DB_OPERATION_NAME] as string | undefined;\n const target = (attributes[DB_COLLECTION_NAME] || attributes[DB_NAMESPACE]) as string | undefined;\n\n const client = getClient();\n const name =\n client && hasSpanStreamingEnabled(client)\n ? operation && target\n ? `${operation} ${target}`\n : target || DB_SYSTEM_VALUE_MONGODB\n : (attributes[DB_QUERY_TEXT] as string) || `mongodb.${attributes[DB_OPERATION_NAME] || 'command'}`;\n\n return startInactiveSpan({\n name,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n ...attributes,\n },\n });\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { MongodbNamespace, MongoV3Topology } from './mongodb-span';\nimport { getV3CommandOperation, getV3SpanAttributes, getV4SpanAttributes, startMongoSpan } from './mongodb-span';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { mongodbModuleNames } from '../../orchestrion/config/mongodb';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\n\nconst INTEGRATION_NAME = 'Mongo' as const;\n\nconst ORIGIN = 'auto.db.mongo';\n\n/**\n * what orchestrion's transform attaches to a channel context:\n * `self` is the `this`, plus args.\n */\ninterface MongoChannelContext extends OrchestrionChannelContext {\n self?: { address?: string };\n}\n\n// Details extracted from a v3 wireprotocol call's arguments to build its span.\ninterface V3CallInfo {\n topology: MongoV3Topology | undefined;\n ns: string;\n command: Record<string, unknown> | undefined;\n operation: string | undefined;\n}\n\n// Command doc first-keys whose span the `v3_command` channel must suppress.\n// The `insert`/`update`/`remove`/`query`/`getMore` functions call the shared\n// `command` function internally. Orchestrion transforms the `command` *source*\n// (unlike the vendored OTel patch, which wraps the module's exported reference\n// and misses internal calls), so `v3_command` would double-span the ones that\n// already have their own dedicated channel (`v3_insert`/`update`/`remove`/\n// `query`/`get_more`) without this guard.\n//\n// `killCursors` has no dedicated channel, but is suppressed too for OTel\n// parity: OTel wraps `wireprotocol/index.js`'s `command` property, which never\n// intercepts `kill_cursors.js`'s direct `require('./command')` call — so OTel\n// emits no killCursors span, and neither should we.\nconst V3_DEDICATED_COMMANDS = new Set(['insert', 'update', 'delete', 'find', 'getMore', 'killCursors']);\n\nconst _mongoIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, mongodbModuleNames, instrumentMongodb, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentMongodb(): void {\n subscribeV4Command();\n subscribeV4Checkout();\n subscribeV3Wireprotocol();\n}\n\n/**\n * `Connection.prototype.command` (mongodb >=4.0) one span per command.\n * Handles both the >=6.4 promise form and the >=4.0 <6.4 callback form\n * (both publish to this channel).\n */\nfunction subscribeV4Command(): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<MongoChannelContext>(CHANNELS.MONGODB_COMMAND), data => {\n const args = data.arguments ?? [];\n const ns = args[0] as MongodbNamespace | undefined;\n const cmd = args[1] as Record<string, unknown> | undefined;\n // Skip handshake/heartbeat commands (matches otel).\n if (!ns || !cmd || typeof cmd !== 'object' || cmd.ismaster || cmd.hello) {\n return undefined;\n }\n const operation = Object.keys(cmd)[0];\n return startMongoSpan(getV4SpanAttributes(data.self, ns, cmd, operation, ORIGIN));\n });\n}\n\n/**\n * `ConnectionPool.prototype.checkOut` (mongodb 4.0 - 6.3, callback form).\n * Creates no span (`getSpan` returns `undefined`) but the binding re-runs\n * the checkout callback under the caller's captured context, so the pooled\n * `command()` invoked inside it re-inherits the active span.\n */\nfunction subscribeV4Checkout(): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel(CHANNELS.MONGODB_CHECKOUT), () => undefined);\n}\n\n/**\n * mongodb >=3.3 <4 had no unified `command`; each operation is a separate\n * `lib/core/wireprotocol` function with its own argument layout, so each\n * channel extracts topology/namespace/command/op differently before building\n * the span.\n */\nfunction subscribeV3Wireprotocol(): void {\n for (const operation of ['insert', 'update', 'remove'] as const) {\n const channel =\n operation === 'insert'\n ? CHANNELS.MONGODB_V3_INSERT\n : operation === 'update'\n ? CHANNELS.MONGODB_V3_UPDATE\n : CHANNELS.MONGODB_V3_REMOVE;\n bindV3(channel, args => ({\n topology: args[0] as MongoV3Topology | undefined,\n ns: args[1] as string,\n command: (args[2] as Record<string, unknown>[] | undefined)?.[0],\n operation,\n }));\n }\n\n // `command`(server, ns, cmd, options, callback) operation derived from the\n // command doc. Skips commands that have a dedicated channel. See set above.\n bindV3(CHANNELS.MONGODB_V3_COMMAND, args => {\n const command = args[2] as Record<string, unknown> | undefined;\n const type = command ? Object.keys(command)[0] : undefined;\n if (type && V3_DEDICATED_COMMANDS.has(type)) {\n return undefined;\n }\n return {\n topology: args[0] as MongoV3Topology | undefined,\n ns: args[1] as string,\n command,\n operation: command ? getV3CommandOperation(command) : undefined,\n };\n });\n\n // `query`(server, ns, cmd, cursorState, options, callback). a find.\n bindV3(CHANNELS.MONGODB_V3_QUERY, args => ({\n topology: args[0] as MongoV3Topology | undefined,\n ns: args[1] as string,\n command: args[2] as Record<string, unknown> | undefined,\n operation: 'find',\n }));\n\n // `getMore`(server, ns, cursorState, batchSize, options, callback)\n // command doc is `cursorState.cmd`.\n bindV3(CHANNELS.MONGODB_V3_GET_MORE, args => ({\n topology: args[0] as MongoV3Topology | undefined,\n ns: args[1] as string,\n command: (args[2] as { cmd?: Record<string, unknown> } | undefined)?.cmd,\n operation: 'getMore',\n }));\n}\n\nfunction bindV3(channelName: string, extract: (args: unknown[]) => V3CallInfo | undefined): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<MongoChannelContext>(channelName), data => {\n const args = data.arguments;\n if (!args) {\n return undefined;\n }\n const info = extract(args);\n if (!info || typeof info.ns !== 'string') {\n return undefined;\n }\n return startMongoSpan(getV3SpanAttributes(info.ns, info.topology, info.command, info.operation, ORIGIN));\n });\n}\n\n/**\n * Diagnostics-channel-based mongodb integration.\n *\n * Reproduces the vendored `@opentelemetry/instrumentation-mongodb` span shape\n * (legacy db/net semantic conventions, `mongodb.<op>` names, scrubbed\n * `db.statement`) via the `orchestrion:mongodb:*` diagnostics_channels\n * injected by Sentry's code transform.\n */\nexport const mongoIntegration = defineIntegration(_mongoIntegration);\n","import type { TracingChannel } from 'node:diagnostics_channel';\nimport {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport { debug, getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\n\n// Channel names published by mongoose >= 9.7.0 (see mongoose `lib/tracing.js`,\n// `lib/query.js`, `lib/aggregate.js`, `lib/model.js` and `lib/cursor/*`).\n// Hardcoded so the subscriber does not have to import mongoose — the channels\n// just have to be subscribed to before the user's mongoose code publishes.\nexport const MONGOOSE_DC_CHANNEL_QUERY = 'mongoose:query';\nexport const MONGOOSE_DC_CHANNEL_AGGREGATE = 'mongoose:aggregate';\nexport const MONGOOSE_DC_CHANNEL_MODEL_SAVE = 'mongoose:model:save';\nexport const MONGOOSE_DC_CHANNEL_MODEL_INSERT_MANY = 'mongoose:model:insertMany';\nexport const MONGOOSE_DC_CHANNEL_MODEL_BULK_WRITE = 'mongoose:model:bulkWrite';\nexport const MONGOOSE_DC_CHANNEL_CURSOR_NEXT = 'mongoose:cursor:next';\n\nconst ORIGIN = 'auto.db.mongoose.native_channel';\nconst DB_SYSTEM_NAME_VALUE_MONGODB = 'mongodb';\n\n// Cap recursion so a self-referential or pathologically deep query can never\n// stall (or blow the stack in) instrumentation.\nconst MAX_REDACTION_DEPTH = 10;\n\n/**\n * Shape of the context object mongoose >= 9.7.0 publishes on its tracing\n * channels (mongoose's `TracingContext`, see `types/tracing.d.ts`).\n *\n * Node's `tracePromise` mutates this same object with `result`/`error` once the\n * operation settles, which `bindTracingChannelToSpan` reads in its lifecycle\n * handlers — hence both are declared optional here.\n *\n * Unlike redis/ioredis, mongoose does NOT pre-sanitize the payload, so `args`\n * carries the raw user query. We redact it before emitting `db.query.text`.\n */\nexport interface MongooseTracingData {\n operation: string;\n /** Absent for connection-level `aggregate()` calls, which have no model/collection. */\n collection?: string;\n database?: string;\n serverAddress?: string;\n serverPort?: number;\n /** Cursor channels only: the cursor's fetch batch size and tailable flag. */\n batchSize?: number;\n tailable?: boolean;\n /**\n * Operation-specific arguments. `filter` (queries/cursors) and `pipeline`\n * (aggregations) carry the query shape; `docs`/`ops` carry batch payloads.\n */\n args?: {\n filter?: unknown;\n pipeline?: unknown;\n docs?: unknown;\n ops?: unknown;\n [key: string]: unknown;\n };\n result?: unknown;\n error?: Error;\n}\n\n/**\n * Platform-provided factory that creates a native tracing channel for the given name. The\n * subscriber binds the span and its lifecycle onto the channel via `bindTracingChannelToSpan`,\n * which propagates the active span through the runtime's async context.\n *\n * Node passes `node:diagnostics_channel`'s `tracingChannel` directly.\n */\nexport type MongooseTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\nlet subscribed = false;\n\n/**\n * Subscribe Sentry span handlers to mongoose's diagnostics-channel events\n * (`mongoose:query`, `:aggregate`, `:model:save`, `:model:insertMany`,\n * `:model:bulkWrite`, `:cursor:next`), published by mongoose >= 9.7.0.\n *\n * On older mongoose versions the channels are never published to, so the\n * subscribers are inert — there is no double-instrumentation against the\n * IITM-based vendored patcher, which is gated to `< 9.7.0`.\n *\n * Idempotent: subsequent calls are a no-op.\n */\nexport function subscribeMongooseDiagnosticChannels(tracingChannel: MongooseTracingChannelFactory): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_QUERY);\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_AGGREGATE);\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_MODEL_SAVE);\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_MODEL_INSERT_MANY);\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_MODEL_BULK_WRITE);\n setupChannel(tracingChannel, MONGOOSE_DC_CHANNEL_CURSOR_NEXT);\n } catch {\n // The factory relies on `node:diagnostics_channel`, which isn't always\n // available. Fail closed; the SDK simply won't emit mongoose spans here.\n DEBUG_BUILD && debug.log('Mongoose node:diagnostics_channel subscription failed.');\n }\n}\n\nfunction setupChannel(tracingChannel: MongooseTracingChannelFactory, channelName: string): void {\n bindTracingChannelToSpan(tracingChannel<MongooseTracingData>(channelName), data => {\n const collection = data.collection;\n const queryText = redactMongoQuery(data.args?.pipeline ?? data.args?.filter);\n const batchSize = getBatchSize(data);\n\n const client = getClient();\n const target = collection || data.database;\n const name =\n client && hasSpanStreamingEnabled(client)\n ? target\n ? `${data.operation} ${target}`\n : DB_SYSTEM_NAME_VALUE_MONGODB\n : collection\n ? `mongoose.${collection}.${data.operation}`\n : `mongoose.${data.operation}`;\n\n return startInactiveSpan({\n name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_MONGODB,\n [DB_OPERATION_NAME]: data.operation,\n [DB_COLLECTION_NAME]: collection ?? undefined,\n [DB_NAMESPACE]: data.database ?? undefined,\n [DB_QUERY_TEXT]: queryText ?? undefined,\n [DB_OPERATION_BATCH_SIZE]: batchSize ?? undefined,\n [SERVER_ADDRESS]: data.serverAddress ?? undefined,\n [SERVER_PORT]: data.serverPort ?? undefined,\n },\n });\n });\n}\n\n/**\n * `db.operation.batch.size` is only meaningful for genuine batch operations.\n * Mongoose's cursor `batchSize` is a fetch-tuning option, not a batch operation\n * size, so it is intentionally excluded here.\n */\nfunction getBatchSize(data: MongooseTracingData): number | undefined {\n const args = data.args;\n const batch = data.operation === 'insertMany' ? args?.docs : data.operation === 'bulkWrite' ? args?.ops : undefined;\n\n return Array.isArray(batch) && batch.length > 1 ? batch.length : undefined;\n}\n\n/**\n * Serialize a mongoose filter/pipeline into `db.query.text` while stripping every\n * value: keys and Mongo operators (`$gt`, `$in`, …) are preserved, leaf values\n * become `'?'`. Mongoose does not sanitize its channel payload, so this prevents\n * raw user data (potential PII) from leaving the process. Returns `undefined`\n * (rather than throwing) on anything it cannot serialize.\n */\nfunction redactMongoQuery(value: unknown): string | undefined {\n if (value == null) {\n return undefined;\n }\n\n try {\n const redacted = redactValue(value, 0);\n const text = JSON.stringify(redacted);\n\n // Skip empty/uninformative shapes (e.g. a `findOne()` with no filter).\n return text == null || text === '{}' || text === '[]' ? undefined : text;\n } catch {\n return undefined;\n }\n}\n\nfunction redactValue(value: unknown, depth: number): unknown {\n if (depth > MAX_REDACTION_DEPTH) {\n return '?';\n }\n\n if (Array.isArray(value)) {\n return value.map(item => redactValue(item, depth + 1));\n }\n\n if (isObjectLike(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n out[key] = redactValue((value as Record<string, unknown>)[key], depth + 1);\n }\n\n return out;\n }\n\n return '?';\n}\n","import {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\n\nconst DB_SYSTEM_NAME_VALUE_MONGODB = 'mongodb';\n\n/** The subset of mongoose's `Collection` that the legacy span shape reads. */\nexport interface MongooseLegacyCollection {\n name?: string;\n conn?: { name?: string; user?: string; host?: string; port?: number };\n}\n\nexport interface StartMongooseLegacySpanOptions {\n collection: MongooseLegacyCollection | undefined;\n modelName: string | undefined;\n operation: string;\n origin: string;\n parentSpan?: Span;\n}\n\n/**\n * Start a mongoose client span reproducing the vendored\n * `@opentelemetry/instrumentation-mongoose` span shape, on the stable\n * conventions. `db.system.name` deliberately deviates from what the OTel\n * instrumentation emitted: mongoose is an ODM, the database system is mongodb.\n *\n * Shared by the vendored OTel/IITM instrumentation (`@sentry/node`) and the\n * orchestrion channel subscriber so the two emit an identical span shape,\n * differing only by `origin`.\n */\nexport function startMongooseLegacySpan({\n collection,\n modelName,\n operation,\n origin,\n parentSpan,\n}: StartMongooseLegacySpanOptions): Span {\n const collectionName = collection?.name;\n const namespace = collection?.conn?.name;\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [DB_COLLECTION_NAME]: collectionName,\n [DB_NAMESPACE]: namespace,\n [DB_USER]: collection?.conn?.user,\n [SERVER_ADDRESS]: collection?.conn?.host,\n [SERVER_PORT]: collection?.conn?.port,\n [DB_OPERATION_NAME]: operation,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_MONGODB,\n [SENTRY_ORIGIN]: origin,\n };\n\n const client = getClient();\n const target = collectionName || namespace;\n const name =\n client && hasSpanStreamingEnabled(client)\n ? target\n ? `${operation} ${target}`\n : DB_SYSTEM_NAME_VALUE_MONGODB\n : `mongoose.${modelName}.${operation}`;\n\n return startInactiveSpan({\n name,\n // Set this explicitly, for platforms lacking `inferDbSpanData`\n attributes,\n parentSpan,\n });\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, waitForTracingChannelBinding } from '@sentry/core';\nimport { subscribeMongooseDiagnosticChannels } from './mongoose-dc-subscriber';\nimport type { MongooseLegacyCollection } from './mongoose-legacy-span';\nimport { startMongooseLegacySpan } from './mongoose-legacy-span';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { MONGOOSE_CONTEXT_CAPTURE_CHANNELS } from '../../orchestrion/config/mongoose';\nimport type { SentryTracingChannel } from '../../tracing-channel';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { mongooseModuleNames } from '../../orchestrion/config/mongoose';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\n\nconst INTEGRATION_NAME = 'Mongoose' as const;\n\nconst ORIGIN = 'auto.db.mongoose';\n\ninterface MongooseQuery {\n mongooseCollection?: MongooseLegacyCollection;\n model?: { modelName?: string };\n op?: string;\n}\n\ninterface MongooseAggregate {\n _model?: { collection?: MongooseLegacyCollection; modelName?: string };\n}\n\ninterface MongooseModelStatic {\n collection?: MongooseLegacyCollection;\n modelName?: string;\n}\n\ninterface MongooseDocument {\n constructor: { collection?: MongooseLegacyCollection; modelName?: string };\n}\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel context\n * object. `self` is the `this` of the traced method\n */\ninterface MongooseChannelContext extends OrchestrionChannelContext {\n self?: object;\n}\n\n// The active span captured when a query/aggregate was *built*, keyed by the\n// query/aggregate object.\n//\n// Used as the parent for the span created at `exec()` so a query parents to\n// where it was built, not where it happens to be awaited. A WeakMap avoids\n// mutating mongoose's own objects.\nconst STORED_PARENT_SPAN = new WeakMap<object, Span>();\n\nlet orchestrionSubscribed = false;\n\nconst _mongooseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // mongoose >= 9.7 publishes via its own diagnostics_channel; reuse the\n // shared native subscriber eagerly\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n waitForTracingChannelBinding(() => {\n subscribeMongooseDiagnosticChannels(diagnosticsChannel.tracingChannel);\n });\n },\n setup(client) {\n // mongoose < 9.7 is covered by the orchestrion-injected channels, so this\n // half subscribes lazily, once mongoose is actually instrumented\n invokeOrchestrionInstrumentation(client, mongooseModuleNames, subscribeOrchestrionMongooseChannels, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction subscribeOrchestrionMongooseChannels(): void {\n if (orchestrionSubscribed) {\n return;\n }\n orchestrionSubscribed = true;\n\n // Context-capture builders: stash the active span at build time so `exec()`\n // can parent to it.\n for (const channelName of MONGOOSE_CONTEXT_CAPTURE_CHANNELS) {\n channel(channelName).subscribe({\n start(message) {\n stashParentSpan(message.self);\n },\n });\n }\n\n // `Model.aggregate()` returns the aggregate it builds; stash the parent on\n // the returned object.\n channel(CHANNELS.MONGOOSE_MODEL_AGGREGATE).subscribe({\n end(message) {\n const result = message.result;\n if (result && typeof result === 'object') {\n stashParentSpan(result);\n }\n },\n });\n\n // Query execution.\n bindExecSpan(CHANNELS.MONGOOSE_QUERY_EXEC, self => {\n const query = self as MongooseQuery;\n return startSpan(\n query.mongooseCollection,\n query.model?.modelName,\n query.op ?? 'exec',\n STORED_PARENT_SPAN.get(self),\n );\n });\n\n // Aggregation execution.\n bindExecSpan(CHANNELS.MONGOOSE_AGGREGATE_EXEC, self => {\n const model = (self as MongooseAggregate)._model;\n return startSpan(model?.collection, model?.modelName, 'aggregate', STORED_PARENT_SPAN.get(self));\n });\n\n // `doc.save()` (and the `$save` alias).\n bindExecSpan(CHANNELS.MONGOOSE_MODEL_SAVE, self => {\n const ctor = (self as MongooseDocument).constructor;\n return startSpan(ctor.collection, ctor.modelName, 'save');\n });\n\n // `doc.remove()` (mongoose 5/6).\n bindExecSpan(CHANNELS.MONGOOSE_MODEL_REMOVE, self => {\n const ctor = (self as MongooseDocument).constructor;\n return startSpan(ctor.collection, ctor.modelName, 'remove');\n });\n\n // Static batch operations. `self` is the Model.\n bindExecSpan(CHANNELS.MONGOOSE_MODEL_INSERT_MANY, self => {\n const model = self as MongooseModelStatic;\n return startSpan(model.collection, model.modelName, 'insertMany');\n });\n bindExecSpan(CHANNELS.MONGOOSE_MODEL_BULK_WRITE, self => {\n const model = self as MongooseModelStatic;\n return startSpan(model.collection, model.modelName, 'bulkWrite');\n });\n}\n\nfunction startSpan(\n collection: MongooseLegacyCollection | undefined,\n modelName: string | undefined,\n operation: string,\n parentSpan?: Span,\n): Span {\n return startMongooseLegacySpan({ collection, modelName, operation, origin: ORIGIN, parentSpan });\n}\n\n// `SentryTracingChannel` relaxes Node's subscriber type to a `Partial`, so a\n// `start`-only (or `end`-only) subscriber for the context-capture channels\n// is accepted.\nfunction channel(channelName: string): SentryTracingChannel<MongooseChannelContext> {\n return diagnosticsChannel.tracingChannel<MongooseChannelContext>(channelName);\n}\n\nfunction bindExecSpan(channelName: string, getSpan: (self: object) => Span): void {\n bindTracingChannelToSpan<MongooseChannelContext>(\n diagnosticsChannel.tracingChannel<MongooseChannelContext>(channelName),\n data => {\n const self = data.self;\n if (!self) {\n return undefined;\n }\n return getSpan(self);\n },\n );\n}\n\nfunction stashParentSpan(self: object | undefined): void {\n const active = getActiveSpan();\n if (self && active) {\n STORED_PARENT_SPAN.set(self, active);\n }\n}\n\n/**\n * Diagnostics-channel-based mongoose integration.\n *\n * Reproduces the vendored `@opentelemetry/instrumentation-mongoose` span\n * shape (legacy db/net semantic conventions, `mongoose.<Model>.<op>` names,\n * build-time span parenting) via the `orchestrion:mongoose:*`\n * diagnostics_channels injected into mongoose `< 9.7` by Sentry's\n * code transform. For mongoose `>= 9.7` it also drives the native\n * diagnostics_channel subscription, so this single integration covers every\n * supported version once it replaces the OTel one.\n */\nexport const mongooseIntegration = defineIntegration(_mongooseIntegration);\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/mistral';\nimport { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from '../ai/mistral/constants';\nimport { instrumentEventStream } from '../ai/mistral/streaming';\nimport type { MistralOptions } from '../ai/mistral/types';\nimport { addResponseAttributes, getMistralRequestSignal, getSpanName } from '../ai/mistral/utils';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { mistralModuleNames } from '../orchestrion/config/mistral';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\nconst INTEGRATION_NAME = MISTRAL_INTEGRATION_NAME;\n\n// Each instrumented channel maps to the gen_ai operation its span reports. Streaming methods publish\n// on their own channel, so the span knows it is a stream before the result exists.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.MISTRAL_CHAT, operation: 'chat', streaming: false },\n { channel: CHANNELS.MISTRAL_CHAT_STREAM, operation: 'chat', streaming: true },\n { channel: CHANNELS.MISTRAL_EMBEDDINGS, operation: 'embeddings', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS, operation: 'invoke_agent', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS_STREAM, operation: 'invoke_agent', streaming: true },\n] as const;\n\nconst _mistralAIIntegration = ((options: MistralOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, mistralModuleNames, instrumentMistral, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentMistral(options: MistralOptions): void {\n for (const { channel, operation, streaming } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, streaming, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getMistralRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);\n },\n // Streaming: the result is an `EventStream` consumed later, so instrument it and let it end the span.\n deferSpanEnd: ({ span, data }) =>\n streaming &&\n instrumentEventStream(\n data.result,\n span,\n resolveAIRecordingOptions(options).recordOutputs,\n getMistralRequestSignal(data.arguments?.[1]),\n ),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented Mistral call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n streaming: boolean,\n options: MistralOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, streaming);\n attributes[SENTRY_ORIGIN] = MISTRAL_ORIGIN;\n\n const span = startInactiveSpan({\n name: getSpanName(operation, attributes),\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\n/**\n * An integration to instrument @mistralai/mistrailai.\n */\nexport const mistralAIIntegration = defineIntegration(_mistralAIIntegration);\n","import { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { togetherAiModuleNames } from '../orchestrion/config/together-ai';\nimport { createOpenAiCompatibleIntegration } from './openai-compatible';\n\n/**\n * Instruments the `together-ai` client (chat completions and embeddings). Together speaks the OpenAI wire\n * format, so this reuses the openai span/streaming logic; see `createOpenAiCompatibleIntegration`. Requires\n * the Sentry runtime hook or bundler plugin so the diagnostics channels get injected into `together-ai`.\n */\nexport const togetherAIIntegration = defineIntegration(\n createOpenAiCompatibleIntegration({\n integrationName: 'TogetherAI',\n providerName: 'together_ai',\n origin: 'auto.ai.together_ai',\n moduleNames: togetherAiModuleNames,\n channels: { chat: CHANNELS.TOGETHER_CHAT, embeddings: CHANNELS.TOGETHER_EMBEDDINGS },\n }),\n);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { GenAiOptions } from '../ai/core/utils';\nimport { resolveAIRecordingOptions } from '../ai/core/utils';\nimport { addResponseAttributes, onSystemOneResponse, startDecideSpan } from '../ai/typesafe';\nimport { TYPESAFE_INTEGRATION_NAME } from '../ai/typesafe/constants';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { typesafeModuleNames } from '../orchestrion/config/typesafe';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\nconst _typesafeIntegration = ((options: GenAiOptions = {}) => {\n return {\n name: TYPESAFE_INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, typesafeModuleNames, instrumentTypeSafe, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentTypeSafe(options: GenAiOptions): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.TYPESAFE_SYSTEM_ONE),\n data => startDecideSpan(data.arguments?.[0], data.self, resolveAIRecordingOptions(options).recordInputs),\n {\n beforeSpanEnd: (span, data) => {\n if (!('error' in data)) {\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);\n }\n },\n deferSpanEnd: ({ data, end }) =>\n onSystemOneResponse(\n data.result,\n body => {\n data.result = body;\n end();\n },\n error => end(error),\n ),\n },\n );\n}\n\n/**\n * Diagnostics-channel-based integration for the TypeSafe SDK (`@typesafe-ai/sdk` >= 0.5.0 < 1).\n * Subscribes to the `orchestrion:@typesafe-ai/sdk:system-one` channel injected into\n * `TypeSafeClient.systemOne`, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const typesafeIntegration = defineIntegration(_typesafeIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_NAMESPACE,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Scope, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, bindScopeToEmitter, defineIntegration, getCurrentScope, startInactiveSpan } from '@sentry/core';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { mysqlModuleNames } from '../orchestrion/config/mysql';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, OTel 'Mysql' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Mysql' as const;\n\nconst DB_SYSTEM_NAME_VALUE_MYSQL = 'mysql' as const;\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context` object. Documented here\n * rather than imported because orchestrion's runtime doesn't export it.\n */\ninterface MysqlQueryChannelContext extends OrchestrionChannelContext {\n self?: MysqlConnection;\n // The caller's scope, captured at `start` and replayed onto the streamed `Query` emitter (see below).\n _sentryCallerScope?: Scope;\n}\n\ninterface MysqlConnectionConfig {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n // Pool connections nest the real config one level deeper.\n connectionConfig?: MysqlConnectionConfig;\n}\n\ninterface MysqlConnection {\n config?: MysqlConnectionConfig;\n}\n\nconst _mysqlIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, mysqlModuleNames, instrumentMysql, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentMysql(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<MysqlQueryChannelContext>(CHANNELS.MYSQL_QUERY),\n data => {\n const sql = extractSql(data.arguments[0]);\n const { host, port, database, user } = getConnectionConfig(data.self);\n const portNumber = typeof port === 'string' ? parseInt(port, 10) : port;\n const portIsNumber = typeof portNumber === 'number' && !isNaN(portNumber);\n\n // For the streamed path: mysql emits the `Query` emitter's events from its socket data\n // handler with the caller's context lost. `deferSpanEnd` replays this scope onto the emitter.\n data._sentryCallerScope = getCurrentScope();\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_MYSQL,\n [SENTRY_ORIGIN]: 'auto.db.mysql',\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: getJDBCString(host, portIsNumber ? portNumber : undefined, database),\n [DB_NAMESPACE]: database,\n [DB_USER]: user,\n ...getSqlQueryAttributes(sql, 'mysql'),\n [SERVER_ADDRESS]: host,\n [SERVER_PORT]: portIsNumber ? portNumber : undefined,\n };\n\n return startInactiveSpan({ name: getSqlSpanName(attributes, 'mysql.query'), attributes });\n },\n {\n // No-callback `query(sql)` returns a streamable `Query` emitter as `result`; it settles on the\n // emitter's `'end'`/`'error'`, not the channel, so defer ending to those.\n deferSpanEnd({ data, end }) {\n const result = data.result;\n if (!result || typeof result !== 'object' || !hasOnMethod(result)) {\n return false;\n }\n\n // Replay the caller's scope so user listeners on the emitter nest under it, not a new trace.\n const callerScope = data._sentryCallerScope;\n if (callerScope) {\n bindScopeToEmitter(result, callerScope);\n }\n\n result.on('error', err => end(err));\n result.on('end', () => end());\n\n return true;\n },\n },\n );\n}\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\nfunction extractSql(firstArg: unknown): string | undefined {\n if (typeof firstArg === 'string') {\n return firstArg;\n }\n if (isObjectLike(firstArg) && 'sql' in firstArg) {\n const sql = (firstArg as { sql?: unknown }).sql;\n return typeof sql === 'string' ? sql : undefined;\n }\n return undefined;\n}\n\nfunction getConnectionConfig(connection: MysqlConnection | undefined): {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n} {\n // Pool connections nest the real config under `.connectionConfig`; single\n // connections expose it directly. Matches `@opentelemetry/instrumentation-mysql`.\n const config = connection?.config?.connectionConfig ?? connection?.config ?? {};\n return {\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.user,\n };\n}\n\nfunction getJDBCString(host: string | undefined, port: number | undefined, database: string | undefined): string {\n let s = `jdbc:mysql://${host || 'localhost'}`;\n if (typeof port === 'number') {\n s += `:${port}`;\n }\n if (database) {\n s += `/${database}`;\n }\n return s;\n}\n\n/**\n * Diagnostics-channel-based mysql integration.\n *\n * Subscribes to the `orchestrion:mysql:query` diagnostics_channel that\n * Sentry's code transform injects into `mysql/lib/Connection.js`'s\n * `Connection.prototype.query`. Requires the Sentry runtime hook or\n * bundler plugin to be active.\n */\nexport const mysqlIntegration = defineIntegration(_mysqlIntegration);\n","import type { TracingChannel } from 'node:diagnostics_channel';\nimport {\n DB_NAMESPACE,\n DB_SYSTEM_NAME,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport { startInactiveSpan } from '@sentry/core';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../../utils/sql';\n\n// Channel names published by mysql2 >= 3.20.0 (see mysql2 `lib/tracing.js`).\n// Hardcoded so the subscriber does not have to import mysql2 — the channels\n// just have to be subscribed to before the user's mysql2 code publishes.\nexport const MYSQL2_DC_CHANNEL_QUERY = 'mysql2:query';\nexport const MYSQL2_DC_CHANNEL_EXECUTE = 'mysql2:execute';\nexport const MYSQL2_DC_CHANNEL_CONNECT = 'mysql2:connect';\nexport const MYSQL2_DC_CHANNEL_POOL_CONNECT = 'mysql2:pool:connect';\n\nconst ORIGIN = 'auto.db.mysql2.native_channel';\nconst DB_SYSTEM_NAME_VALUE_MYSQL = 'mysql';\n\n/**\n * Shape of the context object mysql2 >= 3.20.0 publishes on its query/execute\n * tracing channels (see mysql2 `lib/base/connection.js`).\n *\n * Node's `traceCallback`/`tracePromise` mutate this same object with\n * `result`/`error` once the operation settles, which `bindTracingChannelToSpan`\n * reads in its lifecycle handlers — hence both are declared optional here.\n *\n * `query` is the SQL statement. On the `query` channel mysql2 has already\n * inlined `values` into it (`Connection.format`), so it carries raw user data;\n * on the `execute` channel it keeps `?` placeholders. Either way we sanitize it\n * before emitting `db.query.text` and never attach `values`.\n */\nexport interface MySQL2QueryData {\n query?: string;\n values?: unknown;\n database?: string;\n serverAddress?: string;\n /** Absent for unix-socket connections, where `serverAddress` is the socket path. */\n serverPort?: number;\n result?: unknown;\n error?: Error;\n}\n\n/**\n * Shape of the context object mysql2 >= 3.20.0 publishes on its\n * `connect`/`pool:connect` channels.\n */\nexport interface MySQL2ConnectData {\n database?: string;\n serverAddress?: string;\n serverPort?: number;\n user?: string;\n result?: unknown;\n error?: Error;\n}\n\n/**\n * Platform-provided factory that creates a native tracing channel for the given name. The\n * subscriber binds the span and its lifecycle onto the channel via `bindTracingChannelToSpan`,\n * which propagates the active span through the runtime's async context.\n *\n * Node passes `node:diagnostics_channel`'s `tracingChannel` directly.\n */\nexport type MySQL2TracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * Subscribe Sentry span handlers to mysql2's diagnostics-channel events\n * (`mysql2:query`, `:execute`, `:connect`, `:pool:connect`), published by\n * mysql2 >= 3.20.0.\n *\n * On older mysql2 versions the channels are never published to, so the\n * subscribers are inert — there is no double-instrumentation against the\n * vendored OTel patcher, which is gated to `< 3.20.0`.\n */\nexport function subscribeMysql2DiagnosticChannels(tracingChannel: MySQL2TracingChannelFactory): void {\n setupQueryChannel(tracingChannel, MYSQL2_DC_CHANNEL_QUERY);\n setupQueryChannel(tracingChannel, MYSQL2_DC_CHANNEL_EXECUTE);\n setupConnectChannel(tracingChannel, MYSQL2_DC_CHANNEL_CONNECT, 'mysql2.connect');\n setupConnectChannel(tracingChannel, MYSQL2_DC_CHANNEL_POOL_CONNECT, 'mysql2.pool.connect');\n}\n\nfunction setupQueryChannel(tracingChannel: MySQL2TracingChannelFactory, channelName: string): void {\n bindTracingChannelToSpan(tracingChannel<MySQL2QueryData>(channelName), data => {\n // mysql2 does not sanitize its channel payload, so the statement may carry\n // raw user values (on the `query` channel they are inlined). Strip every\n // literal before it leaves the process; `values` is never attached.\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_MYSQL,\n ...getSqlQueryAttributes(data.query, 'mysql'),\n [DB_NAMESPACE]: data.database || undefined,\n [SERVER_ADDRESS]: data.serverAddress,\n [SERVER_PORT]: data.serverPort,\n };\n\n return startInactiveSpan({ name: getSqlSpanName(attributes, 'mysql2.query'), attributes, onlyIfParent: true });\n });\n}\n\nfunction setupConnectChannel(tracingChannel: MySQL2TracingChannelFactory, channelName: string, spanName: string): void {\n bindTracingChannelToSpan(tracingChannel<MySQL2ConnectData>(channelName), data => {\n return startInactiveSpan({\n name: spanName,\n onlyIfParent: true,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_VALUE_MYSQL,\n [DB_NAMESPACE]: data.database || undefined,\n [SERVER_ADDRESS]: data.serverAddress,\n [SERVER_PORT]: data.serverPort,\n },\n });\n });\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, isObjectLike, startInactiveSpan, waitForTracingChannelBinding } from '@sentry/core';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../../utils/sql';\nimport { subscribeMysql2DiagnosticChannels } from './mysql2-dc-subscriber';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport type { ChannelName } from '../../orchestrion/channels';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { mysql2ModuleNames } from '../../orchestrion/config/mysql2';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport {\n DB_NAMESPACE,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\n\nconst INTEGRATION_NAME = 'Mysql2' as const;\nconst ORIGIN = 'auto.db.mysql2';\nconst DB_SYSTEM_VALUE_MYSQL = 'mysql';\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context`\n * object. Documented here rather than imported because orchestrion's runtime\n * doesn't export it.\n */\ninterface Mysql2QueryChannelContext extends OrchestrionChannelContext {\n self?: Mysql2Connection;\n}\n\ninterface Mysql2ConnectionConfig {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n // Pool connections nest the real config one level deeper.\n connectionConfig?: Mysql2ConnectionConfig;\n}\n\ninterface Mysql2Connection {\n config?: Mysql2ConnectionConfig;\n}\n\n/**\n * Diagnostics-channel-based mysql2 integration.\n *\n * Subscribes to:\n * - the `orchestrion:mysql2:query`/`:execute` channels the code transform\n * injects into mysql2's `query`/`execute` (mysql2 `< 3.20.0`), and\n * - mysql2's native `node:diagnostics_channel` tracing channels\n * (mysql2 `>= 3.20.0`), which the transform intentionally leaves alone.\n *\n * The two version ranges never overlap, so no query is double-counted. Requires the Sentry\n * runtime hook or bundler plugin to be active.\n */\nfunction instrumentMysql2Orchestrion(): void {\n subscribeQueryChannel(CHANNELS.MYSQL2_QUERY);\n subscribeQueryChannel(CHANNELS.MYSQL2_EXECUTE);\n}\n\nfunction subscribeQueryChannel(channelName: ChannelName): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<Mysql2QueryChannelContext>(channelName), data => {\n const statement = getQueryText(data.arguments);\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: DB,\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_MYSQL,\n ...getSqlQueryAttributes(statement, 'mysql'),\n ...getConnectionAttributes(data.self?.config),\n };\n\n return startInactiveSpan({ name: getSqlSpanName(attributes, 'mysql2.query'), attributes, onlyIfParent: true });\n });\n}\n\n/**\n * Render the `db.query.text` from the wrapped call's first argument.\n */\nfunction getQueryText(args: unknown[]): string | undefined {\n return extractSql(args[0]);\n}\n\nfunction extractSql(firstArg: unknown): string | undefined {\n if (typeof firstArg === 'string') {\n return firstArg;\n }\n if (isObjectLike(firstArg) && 'sql' in firstArg) {\n const sql = (firstArg as { sql?: unknown }).sql;\n return typeof sql === 'string' ? sql : undefined;\n }\n return undefined;\n}\n\nfunction getConnectionAttributes(config: Mysql2ConnectionConfig | undefined): SpanAttributes {\n // Pool connections nest the real config under `.connectionConfig`; single\n // connections expose it directly.\n const { host, port, database, user } = config?.connectionConfig ?? config ?? {};\n const portNumber = typeof port === 'string' ? parseInt(port, 10) : port;\n const portIsNumber = typeof portNumber === 'number' && !isNaN(portNumber);\n\n return {\n [DB_NAMESPACE]: database || undefined,\n [DB_USER]: user || undefined,\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_ADDRESS]: host || undefined,\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_PORT]: portIsNumber ? portNumber : undefined,\n };\n}\n\nconst _mysql2Integration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // mysql2 >= 3.20.0 native diagnostics_channel path: subscribe eagerly,\n // because they do not get an orchestrion event to indicate readiness\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n waitForTracingChannelBinding(() => {\n subscribeMysql2DiagnosticChannels(diagnosticsChannel.tracingChannel);\n });\n },\n setup(client) {\n // mysql2 < 3.20.0 orchestrion channels, subscribe lazily\n invokeOrchestrionInstrumentation(client, mysql2ModuleNames, instrumentMysql2Orchestrion, []);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Diagnostics-channel-based mysql2 integration.\n *\n * Adds Sentry tracing instrumentation for the\n * [mysql2](https://www.npmjs.com/package/mysql2) library via diagnostics-channel\n * injection. See {@link instrumentMysql2} for how the two mysql2 version ranges\n * are covered.\n *\n * Known limitation vs. older OTel integration it replaced: the callback-less\n * streaming form (`connection.query(sql).on('result', ...)`) is not traced.\n * See the `mysql2` transform config for why. The callback and promise forms\n * (the common case) are fully instrumented.\n */\nexport const mysql2Integration = defineIntegration(_mysql2Integration);\n","import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/openai';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { instrumentStream } from '../ai/openai/streaming';\nimport type { OpenAiOptions } from '../ai/openai/types';\nimport { addResponseAttributes } from '../ai/openai/utils';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { openaiModuleNames } from '../orchestrion/config/openai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'OpenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'OpenAI' as const;\n\nconst ORIGIN = 'auto.ai.openai';\n\n// Each instrumented `create` method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.OPENAI_CHAT, operation: 'chat' },\n { channel: CHANNELS.OPENAI_EMBEDDINGS, operation: 'embeddings' },\n { channel: CHANNELS.OPENAI_DECIDE, operation: 'decide' },\n] as const;\n\nconst _openAIIntegration = ((options: OpenAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, openaiModuleNames, instrumentOpenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentOpenai(options: OpenAiOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs, operation);\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n // stream responses should end only after iteration is completed\n if (!wrapStreamResult(span, data, options)) {\n end();\n }\n },\n end,\n ) || wrapStreamResult(span, data, options),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented `create` call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(data: OrchestrionChannelContext, operation: string, options: OpenAiOptions): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs);\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const model = (params?.model as string) || 'unknown';\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * For a streaming `create({ stream: true })` the result is a `Stream` the caller consumes later. We can't\n * swap what `create` returns, but the `Stream` in `data.result` is the same instance the caller holds and\n * we observe it before the caller iterates — so we patch its async iterator in place to run through\n * `instrumentStream`, which accumulates the streamed attributes and ends the span when iteration finishes.\n * Only a streaming call resolves to an async-iterable, so that check alone distinguishes it. Returns `true`\n * to hand span-ending ownership to `instrumentStream`; `false` for non-streaming/errored results, which end\n * via the normal `beforeSpanEnd` path.\n */\nfunction wrapStreamResult(span: Span, data: OrchestrionChannelContext, options: OpenAiOptions): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs ?? false);\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based OpenAI integration. Subscribes to the `orchestrion:openai:*`\n * diagnostics_channels injected into `openai`'s `create` methods (chat completions, responses, embeddings,\n * conversations, decisions), so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const openAIIntegration = defineIntegration(_openAIIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_NAMESPACE,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Scope, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, bindScopeToEmitter, defineIntegration, getCurrentScope, startInactiveSpan } from '@sentry/core';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { pgModuleNames } from '../orchestrion/config/pg';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Postgres' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Postgres' as const;\n\n// Only the query span carries an origin (the connect/pool-connect spans don't,\n// so they default to 'manual').\nconst ORIGIN = 'auto.db.postgres';\n\nconst ATTR_PG_PLAN = 'db.postgresql.plan';\nconst ATTR_PG_IDLE_TIMEOUT = 'db.postgresql.idle.timeout.millis';\nconst ATTR_PG_MAX_CLIENT = 'db.postgresql.max.client';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\n\n// We set the `db` op and the SQL description directly here (same as mysql\n// orchestrion) rather than relying on the OTel pipeline's `inferDbSpanData`\n// processor, which only runs in the node SDK, so setting them here is what\n// makes the spans correct on the other runtimes\n//\n// The user-visible span is identical to OTel: query spans are named after the\n// SQL statement; connect/pool-connect spans keep these names.\nconst SPAN_QUERY_FALLBACK = 'pg.query';\nconst SPAN_CONNECT = 'pg.connect';\nconst SPAN_POOL_CONNECT = 'pg-pool.connect';\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context`. Documented here rather\n * than imported because orchestrion's runtime doesn't export it.\n */\ninterface PgChannelContext extends OrchestrionChannelContext {\n // The caller's scope, captured at `start` and replayed onto a streamed `Submittable` emitter (see below).\n _sentryCallerScope?: Scope;\n}\n\nexport interface PgConnectionParams {\n database?: string;\n host?: string;\n port?: number;\n user?: string;\n connectionString?: string;\n}\n\ninterface PgPoolOptions extends PgConnectionParams {\n idleTimeoutMillis?: number;\n // pg-pool stores the max pool size as `max` (defaulting it to 10 in its\n // constructor). The OTel pg instrumentation reads a `maxClient` field that\n // pg-pool never sets, so its `db.postgresql.max.client` attribute is always\n // dropped; we read the real `max` so the attribute is actually populated.\n max?: number;\n}\n\nconst _postgresIntegration = ((options: { ignoreConnectSpans?: boolean } = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, pgModuleNames, instrumentPostgres, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPostgres(options: { ignoreConnectSpans?: boolean }): void {\n bindPgQueryChannel(CHANNELS.PG_QUERY, { origin: ORIGIN, connectionString: true });\n\n // Connect spans, gated by `ignoreConnectSpans` (same as OTel pg).\n // `Client.prototype.connect` (pg + native)\n // and `Pool.prototype.connect` (pg-pool).\n if (!options.ignoreConnectSpans) {\n subscribeQueryLikeChannel(CHANNELS.PG_CONNECT, connectSpanOptions);\n subscribeQueryLikeChannel(CHANNELS.PGPOOL_CONNECT, poolConnectSpanOptions);\n }\n}\n\nexport interface PgQuerySpanOptions {\n origin: string;\n // `db.connection_string` is deprecated in favor of `server.address`/`server.port`. Only the pg\n // integration keeps emitting it, for parity with its OTel predecessor.\n connectionString?: boolean;\n}\n\n/**\n * Query spans for a channel carrying `pg` `Client.prototype.query` calls, from `pg` itself or from\n * a copy bundled into another driver (`@neondatabase/serverless`). Only this call can return a\n * streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.\n */\nexport function bindPgQueryChannel(channelName: string, options: PgQuerySpanOptions): void {\n subscribeQueryLikeChannel(channelName, ctx => querySpanOptions(ctx, options), { deferStreamedResult: true });\n}\n\n/**\n * Subscribe to a pg tracing-channel and manage a span across its lifecycle.\n * Shared by the query/connect/pool-connect channels. They differ only in how\n * the span's name + attributes are built (`getSpanOptions`), and whether the\n * result can be a streamable emitter (`deferStreamedResult`, query-only).\n */\nfunction subscribeQueryLikeChannel(\n channelName: string,\n getSpanOptions: (ctx: PgChannelContext) => { name: string; attributes: SpanAttributes },\n { deferStreamedResult = false }: { deferStreamedResult?: boolean } = {},\n): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<PgChannelContext>(channelName),\n data => {\n // Capture the caller's scope while still synchronously inside the call, for the streamed path:\n // pg dispatches a `Submittable` emitter's events outside the original async scope, so `deferSpanEnd`\n // replays this scope onto that emitter.\n data._sentryCallerScope = getCurrentScope();\n\n // `sentry.kind: 'client'` mirrors the OTel pg instrumentation, so the emitted\n // `sentry.kind` matches across the OTel and diagnostics-channel paths.\n const spanOptions = getSpanOptions(data);\n return startInactiveSpan({\n ...spanOptions,\n onlyIfParent: true,\n attributes: { ...spanOptions.attributes, [SENTRY_KIND]: 'client' },\n });\n },\n // `connect`/`pool-connect` resolve with a persistent `Client` (itself an\n // `EventEmitter`), which is NOT a streamed result. Deferring their span\n // to that emitter's `'end'`/`'error'` would keep it open for the whole\n // connection lifetime, so it never ends in time and is dropped. Only\n // `query` can return a streamable `Submittable`, so only it defers.\n deferStreamedResult\n ? {\n // Streamable `Submittable` (e.g. `client.query(new Query())`)\n // returns an emitter that orchestrion stores on `ctx.result` while\n // firing no async events; the query isn't done until the emitter\n // emits `'end'`/`'error'`. Defer ending to those events for that\n // path; the callback, promise, and sync-throw paths carry no\n // emitter, so the helper ends the span as usual.\n deferSpanEnd({ data, end }) {\n const result = data.result;\n if (!result || typeof result !== 'object' || !hasOnMethod(result)) {\n return false;\n }\n\n // Replay the caller's scope onto the emitter so listeners theu\n // user attaches after the call returns (and any spans they start)\n // nest under the caller, not a fresh root trace.\n const callerScope = data._sentryCallerScope;\n if (callerScope) {\n bindScopeToEmitter(result, callerScope);\n }\n\n result.on('error', err => end(err));\n result.on('end', () => end());\n\n return true;\n },\n }\n : undefined,\n );\n}\n\nfunction querySpanOptions(\n ctx: PgChannelContext,\n { origin, connectionString }: PgQuerySpanOptions,\n): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n const queryConfig = extractQueryConfig(ctx.arguments);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n ...(connectionString ? getPgConnectionAttributes(params) : getConnectionAttributes(params)),\n [SENTRY_ORIGIN]: origin,\n ...getSqlQueryAttributes(queryConfig?.text),\n [ATTR_PG_PLAN]: typeof queryConfig?.name === 'string' ? queryConfig.name : undefined,\n };\n\n return { name: getSqlSpanName(attributes, SPAN_QUERY_FALLBACK), attributes };\n}\n\nfunction connectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n // No origin set -> defaults to 'manual'\n return { name: SPAN_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPgConnectionAttributes(params) } };\n}\n\nfunction poolConnectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const opts = (ctx.self as { options?: PgPoolOptions } | undefined)?.options ?? {};\n return { name: SPAN_POOL_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPoolConnectionAttributes(opts) } };\n}\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\n// `client.query(text, cb?)`, `client.query(text, values, cb?)`, and\n// `client.query(configObj, cb?)` are all valid; normalize to `{ text, name }`\n// (the only fields the span needs). Returns undefined for invalid args.\nfunction extractQueryConfig(args: unknown[]): { text: string; name?: unknown } | undefined {\n const arg0 = args[0];\n if (typeof arg0 === 'string') {\n return { text: arg0 };\n }\n if (isObjectLike(arg0) && typeof (arg0 as { text?: unknown }).text === 'string') {\n const obj = arg0 as { text: string; name?: unknown };\n return { text: obj.text, name: obj.name };\n }\n return undefined;\n}\n\n/** The `db.*`/`server.*` attributes for a pg-style set of connection parameters. */\nexport function getConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n [DB_NAMESPACE]: params.database,\n [DB_USER]: params.user,\n [SERVER_ADDRESS]: params.host,\n [SERVER_PORT]: Number.isInteger(params.port) ? params.port : undefined,\n };\n}\n\nfunction getPgConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n return { ...getConnectionAttributes(params), [DB_CONNECTION_STRING]: getConnectionString(params) };\n}\n\nfunction getPoolConnectionAttributes(opts: PgPoolOptions): SpanAttributes {\n let url: URL | undefined;\n try {\n url = opts.connectionString ? new URL(opts.connectionString) : undefined;\n } catch {\n url = undefined;\n }\n const database = url?.pathname.slice(1) || opts.database;\n const host = url?.hostname || opts.host;\n // Mirror OTel's `getSemanticAttributesFromPoolConnection`: prefer the URL's\n // port, but fall back to an explicit `opts.port` when the connection string\n // omits it (`Number('')` / `Number(undefined)` -> falsy).\n const port = Number(url?.port) || (Number.isInteger(opts.port) ? opts.port : undefined);\n const user = url?.username || opts.user;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: getConnectionString(opts),\n [ATTR_PG_IDLE_TIMEOUT]: opts.idleTimeoutMillis,\n [ATTR_PG_MAX_CLIENT]: opts.max,\n [DB_NAMESPACE]: database,\n [SERVER_PORT]: port,\n // these two come from a url parse and slice, can be ''\n [SERVER_ADDRESS]: host || undefined,\n [DB_USER]: user || undefined,\n };\n}\n\n// Builds `postgresql://host:port/database`, masking credentials when a raw\n// connection string was provided.\nfunction getConnectionString(params: PgConnectionParams): string {\n if (params.connectionString) {\n try {\n const url = new URL(params.connectionString);\n url.username = '';\n url.password = '';\n return url.toString();\n } catch {\n return 'postgresql://localhost:5432/';\n }\n }\n const host = params.host || 'localhost';\n const port = params.port || 5432;\n const database = params.database || '';\n return `postgresql://${host}:${port}/${database}`;\n}\n\n/**\n * Diagnostics-channel-based `pg` (node-postgres) integration.\n *\n * Subscribes to the `orchestrion:pg:query`/`:connect` and\n * `orchestrion:pg-pool:connect` diagnostics_channels that Sentry's code\n * transform injects into `pg`'s `Client.prototype.query`/`connect`\n * and `pg-pool`'s `Pool.prototype.connect`. Requires the Sentry runtime\n * hook or bundler plugin to be active.\n */\nexport const postgresIntegration = defineIntegration(_postgresIntegration);\n","import type { TracingChannel } from 'node:diagnostics_channel';\nimport {\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_RESPONSE_STATUS_CODE,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { debug, getActiveSpan, isObjectLike, startInactiveSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../../utils/sql';\nimport {\n _getConnectionAttributes,\n _isPostgresJsWrapperSpan,\n type PostgresConnectionContext,\n type PostgresJsSqlInstrumentationOptions,\n} from '../postgresjs-wrapper';\n\n/**\n * Tracing channel published by `postgres` >= 4.0.0 for every query (see postgres `src/diagnostics.js`).\n */\nexport const POSTGRESJS_DC_CHANNEL_QUERY = 'postgres:query';\n\nconst ORIGIN = 'auto.db.postgresjs';\nconst DB_SYSTEM_NAME_POSTGRES = 'postgres';\n\n/**\n * The context `postgres` >= 4.0.0 publishes on `postgres:query`. `host`, `port` and `connection`\n * stay `null` until the query is written to a connection, and `command`/`count` until it completes,\n * so they can only be read once the span ends.\n */\nexport interface PostgresJsQueryData {\n query?: string | null;\n database?: string;\n user?: string | null;\n host?: string | null;\n port?: number | null;\n command?: string | null;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory for a native tracing channel. Node passes `node:diagnostics_channel`'s\n * `tracingChannel` directly.\n */\nexport type PostgresJsTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * Subscribe Sentry span handlers to the `postgres:query` tracing channel published natively by\n * `postgres` >= 4.0.0. Older versions never publish it, and the orchestrion transform is gated to\n * `< 4`, so no query gets two spans.\n */\nexport function subscribePostgresJsDiagnosticChannels(\n tracingChannel: PostgresJsTracingChannelFactory,\n options: PostgresJsSqlInstrumentationOptions = {},\n): void {\n const { requireParentSpan, requestHook } = options;\n\n bindTracingChannelToSpan(\n tracingChannel<PostgresJsQueryData>(POSTGRESJS_DC_CHANNEL_QUERY),\n data => {\n // `instrumentPostgresJsSql` already spans this query, and its span is active when postgres runs it.\n if (_isPostgresJsWrapperSpan(getActiveSpan())) {\n return undefined;\n }\n\n const queryAttributes = getSqlQueryAttributes(data.query ?? undefined);\n const sanitizedSqlQuery = queryAttributes[DB_QUERY_TEXT] ?? '';\n const connectionContext = getPostgresJsConnectionContext(data);\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_POSTGRES,\n ...queryAttributes,\n ..._getConnectionAttributes(connectionContext),\n };\n const span = startInactiveSpan({\n name: getSqlSpanName(attributes, 'postgresjs.query'),\n onlyIfParent: requireParentSpan !== false,\n attributes,\n });\n\n if (requestHook) {\n callRequestHook(requestHook, span, sanitizedSqlQuery, connectionContext);\n }\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n span.setAttributes(getPostgresJsQueryEndAttributes(data));\n },\n },\n );\n}\n\n/**\n * Maps a `postgres:query` context to a {@link PostgresConnectionContext}. At `start` only the\n * database is known; `host`/`port` are filled in once the query is sent.\n *\n * @internal Exported for testing only\n */\nexport function getPostgresJsConnectionContext(data: PostgresJsQueryData): PostgresConnectionContext {\n return {\n ATTR_DB_NAMESPACE: data.database || undefined,\n ATTR_SERVER_ADDRESS: data.host || undefined,\n ATTR_SERVER_PORT: typeof data.port === 'number' ? String(data.port) : undefined,\n };\n}\n\n/**\n * Attributes only known once the query settled: the connection it ran on, the server-reported\n * command and, on failure, the Postgres error code.\n *\n * @internal Exported for testing only\n */\nexport function getPostgresJsQueryEndAttributes(data: PostgresJsQueryData): SpanAttributes {\n const attributes = _getConnectionAttributes(getPostgresJsConnectionContext(data));\n\n if (data.command) {\n attributes[DB_OPERATION_NAME] = data.command;\n }\n\n if ('error' in data) {\n const code = isObjectLike(data.error) && 'code' in data.error ? data.error.code : undefined;\n attributes[DB_RESPONSE_STATUS_CODE] = typeof code === 'string' && code ? code : 'unknown';\n }\n\n return attributes;\n}\n\nfunction callRequestHook(\n requestHook: NonNullable<PostgresJsSqlInstrumentationOptions['requestHook']>,\n span: Span,\n sanitizedSqlQuery: string,\n connectionContext: PostgresConnectionContext,\n): void {\n try {\n requestHook(span, sanitizedSqlQuery, connectionContext);\n } catch (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error in requestHook:', e);\n }\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport { debug, defineIntegration, startInactiveSpan, waitForTracingChannelBinding } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../../utils/sql';\nimport {\n _buildConnectionContext,\n _getConnectionAttributes,\n _reconstructQuery,\n _wrapQuerySettlement,\n type PostgresConnectionContext,\n type PostgresQuerySettlement,\n} from '../postgresjs-wrapper';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { postgresJsModuleNames } from '../../orchestrion/config/postgres';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { subscribePostgresJsDiagnosticChannels } from './postgresjs-dc-subscriber';\n\n// Same name as the OTel `PostgresJs` integration by design, so the OTel\n// integration of the same name is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'PostgresJs' as const;\n\nconst ORIGIN = 'auto.db.postgresjs';\n\nconst DB_SYSTEM_NAME_POSTGRES = 'postgres';\n\nconst NOOP = (): void => {};\n\n// Same `Symbol.for()` marker the core `instrumentPostgresJsSql` wrapper sets on\n// queries it manually instruments, so we skip them there and never double-span.\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n// The query span, stashed on the `Query` so the `execute`/`connect` channels can\n// attach connection attributes to it.\nconst QUERY_SPAN = Symbol('sentryPostgresJsSpan');\n// Set on the channel context once the resolve/reject wrappers have ended the\n// span, so `deferSpanEnd` knows the wrappers own the lifecycle.\nconst SPAN_ENDED = Symbol('sentryPostgresJsSpanEnded');\n\nexport interface PostgresJsIntegrationOptions {\n /**\n * Only create spans when there's already an active parent span. Defaults to\n * `true`, matching the OTel `postgresJsIntegration`.\n */\n requireParentSpan?: boolean;\n /**\n * Hook to modify the query span before the query runs. Receives the span, the\n * sanitized SQL, and (when resolvable) the connection context.\n */\n requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) => void;\n}\n\n/** The `Query` instance postgres.js passes as `self` to `Query.prototype.handle`. */\ninterface PostgresQuery extends PostgresQuerySettlement {\n strings?: string[];\n executed?: boolean;\n}\n\ninterface PostgresJsQueryContext extends OrchestrionChannelContext {\n self?: PostgresQuery;\n [SPAN_ENDED]?: boolean;\n}\n\n// A connection object -> its resolved context, populated on the `connection`\n// channel and read on the `execute`/`connect` channels (keyed by the same object).\nconst connectionContexts = new WeakMap<object, PostgresConnectionContext>();\n// Distinct endpoints seen so far (value-compared, so N connections to one DB\n// count once). When exactly one endpoint exists — the common case, and the only\n// one the tests exercise — every query resolves to it at handle-start.\nconst endpointRegistry: PostgresConnectionContext[] = [];\n\nfunction registerEndpoint(context: PostgresConnectionContext): void {\n const alreadyKnown = endpointRegistry.some(\n e =>\n e.ATTR_SERVER_ADDRESS === context.ATTR_SERVER_ADDRESS &&\n e.ATTR_SERVER_PORT === context.ATTR_SERVER_PORT &&\n e.ATTR_DB_NAMESPACE === context.ATTR_DB_NAMESPACE,\n );\n if (!alreadyKnown) {\n endpointRegistry.push(context);\n }\n}\n\n/** The single known endpoint, or `undefined` when zero or multiple are known. */\nfunction resolveSingleEndpoint(): PostgresConnectionContext | undefined {\n return endpointRegistry.length === 1 ? endpointRegistry[0] : undefined;\n}\n\n/**\n * Record a connection from the `connection` channel `end` (`result` is the\n * connection object, `arguments[0]` the parsed options), keying its resolved\n * context by the connection object and tracking its endpoint.\n */\nfunction recordConnectionFromChannel(message: PostgresJsQueryContext): void {\n const connection = message.result;\n const options = message.arguments?.[0] as { host?: string[]; port?: number[]; database?: string } | undefined;\n if (!connection || typeof connection !== 'object' || !options) {\n return;\n }\n const context = _buildConnectionContext(options);\n connectionContexts.set(connection, context);\n registerEndpoint(context);\n}\n\n/**\n * Backfill connection attributes onto a query's span from a channel whose `self`\n * is the connection object and `arguments[0]` the query. Shared by the `execute`\n * and `connect` channels; both carry that shape and both resolve the context via\n * the `connectionContexts` WeakMap.\n */\nfunction attachConnectionAttributesFromChannel(message: PostgresJsQueryContext): void {\n const connection = message.self;\n const query = message.arguments?.[0] as PostgresQuery | undefined;\n if (!connection || !query) {\n return;\n }\n const span = (query as Record<symbol, unknown>)[QUERY_SPAN] as Span | undefined;\n const context = connectionContexts.get(connection);\n if (span && context) {\n span.setAttributes(_getConnectionAttributes(context));\n }\n}\n\nconst _postgresJsIntegration = ((options: PostgresJsIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // postgres >= 4 publishes its own `postgres:query` tracing channel, with no orchestrion event to\n // signal that it was loaded, so subscribe eagerly.\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n waitForTracingChannelBinding(() => {\n subscribePostgresJsDiagnosticChannels(diagnosticsChannel.tracingChannel, options);\n });\n },\n setup(client) {\n // postgres 3.x is covered by the orchestrion-injected channels, subscribed lazily.\n invokeOrchestrionInstrumentation(client, postgresJsModuleNames, instrumentPostgresJs, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPostgresJs(options: PostgresJsIntegrationOptions): void {\n const { requireParentSpan, requestHook } = options;\n\n // Connection + execute are pure observers (no span, no async binding).\n diagnosticsChannel.tracingChannel<PostgresJsQueryContext>(CHANNELS.POSTGRESJS_CONNECTION).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: recordConnectionFromChannel,\n });\n\n // Per-connection attributes for queries reusing an already-open connection\n // (`c.execute(q)`, `self === c`). `execute` is also called bare\n // (`self === undefined`) for the first query on each connection, `fetchState`\n // and `retry`; those miss here (the `connect` channel below covers the first\n // user query, and the single-endpoint fallback covers the common case).\n diagnosticsChannel.tracingChannel<PostgresJsQueryContext>(CHANNELS.POSTGRESJS_EXECUTE).subscribe({\n end: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n start: attachConnectionAttributesFromChannel,\n });\n\n // The connection's `connect(query)` method (`self === c`, `arguments[0]` the\n // query) fires when a fresh connection is opened for a query. That first query\n // is later dispatched via a bare `execute` (no `self`), so this is where it\n // gets its connection attributes in multi-endpoint apps.\n diagnosticsChannel.tracingChannel<PostgresJsQueryContext>(CHANNELS.POSTGRESJS_CONNECT).subscribe({\n end: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n start: attachConnectionAttributesFromChannel,\n });\n\n bindTracingChannelToSpan<PostgresJsQueryContext>(\n diagnosticsChannel.tracingChannel<PostgresJsQueryContext>(CHANNELS.POSTGRESJS_HANDLE),\n data => {\n const query = data.self;\n if (!query) {\n return undefined;\n }\n\n // Opt out of re-entrant `handle()` calls (then/catch/finally re-invoke\n // it, guarded by `executed`) and queries already wrapped by the portable\n // `instrumentPostgresJsSql`.\n if (query.executed === true || (query as Record<symbol, unknown>)[QUERY_FROM_INSTRUMENTED_SQL]) {\n return undefined;\n }\n\n const queryAttributes = getSqlQueryAttributes(_reconstructQuery(query.strings));\n\n // Single-endpoint fallback: resolve context now so the span name and `requestHook` have\n // it, and the first-query-per-connection (bare `execute`) path still gets attrs.\n const context = resolveSingleEndpoint();\n\n // `sentry.kind: client` matches the mysql/pg channel subscribers.\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n [DB_SYSTEM_NAME]: DB_SYSTEM_NAME_POSTGRES,\n ...queryAttributes,\n ...(context && _getConnectionAttributes(context)),\n };\n const span = startInactiveSpan({\n name: getSqlSpanName(attributes, 'postgresjs.query'),\n onlyIfParent: requireParentSpan !== false,\n attributes,\n });\n\n // Stash for the `execute`/`connect` channels to attach per-connection attributes.\n (query as Record<symbol, unknown>)[QUERY_SPAN] = span;\n\n if (requestHook) {\n try {\n requestHook(span, queryAttributes[DB_QUERY_TEXT] ?? '', context);\n } catch (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error('[instrumentation:postgresjs] error in requestHook:', e);\n }\n }\n\n // Claim ownership of ending the span up front, so `deferSpanEnd` defers to the\n // settlement wrappers even if `span.end()` throws in them.\n _wrapQuerySettlement(query, span, queryAttributes[DB_OPERATION_NAME], () => {\n data[SPAN_ENDED] = true;\n });\n\n return span;\n },\n {\n deferSpanEnd({ data }) {\n // `handle` is async: its promise settles on dispatch (asyncEnd), long\n // before the query does, so the resolve/reject wrappers own the ending.\n // The helper only ends the span if `handle()` itself threw.\n // NOTE: for a cursor consumed as an async iterator, only the first batch\n // reaches `handle` (the `executed` guard blocks the rest), so the span\n // ends on the first batch — a pre-existing flaw kept for parity.\n return !!data[SPAN_ENDED] || !('error' in data);\n },\n },\n );\n}\n\n/**\n * Diagnostics-channel-based postgres.js integration.\n *\n * - `postgres` 3.x: subscribes to the `orchestrion:postgres:handle` / `:connection` /\n * `:execute` / `:connect` channels injected into postgres.js' `Query.prototype.handle`\n * and `Connection`/`execute`/`connect` (in `src/*` and `cjs/src/*`). Requires the\n * Sentry runtime hook or bundler plugin.\n * - `postgres` >= 4.0.0: subscribes to the `postgres:query` tracing channel the library\n * publishes natively.\n *\n * Both paths create the same db spans.\n */\nexport const postgresJsIntegration = defineIntegration(_postgresJsIntegration);\n","import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, startInactiveSpan } from '@sentry/core';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { neonModuleNames } from '../orchestrion/config/neon';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { bindPgQueryChannel, getConnectionAttributes } from './pg';\n\nconst INTEGRATION_NAME = 'Neon' as const;\nconst ORIGIN = 'auto.db.neon';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\nconst DEFAULT_PORT = 5432;\nconst NOOP = (): void => {};\n\n// `sql.query(text, params)` builds the first shape, a tagged-template call the second.\ntype NeonQueryData = { query: string; params?: unknown[] } | NeonSqlTemplate;\n\ninterface NeonSqlTemplate {\n strings: readonly string[];\n values: unknown[];\n toParameterizedQuery?: () => { query: string };\n}\n\ninterface NeonHttpQueryContext {\n // `[queryData, opts]` for a single query, `[queryData[], opts[]]` for a `transaction()` batch.\n arguments: unknown[];\n}\n\ninterface NeonResolveConnectionContext {\n result?: { resolvedURL?: URL };\n}\n\n// The HTTP query spans this integration started, so the connection-resolver subscriber only\n// enriches those and never a user's own active span.\nconst httpQuerySpans = new WeakSet<Span>();\n\nconst _neonIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, neonModuleNames, instrumentNeon, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentNeon(): void {\n // The WebSocket driver is pg's `Client`, bundled into the package, so its query channel gets\n // the pg span shape.\n bindPgQueryChannel(CHANNELS.NEON_QUERY, { origin: ORIGIN });\n\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY), data => {\n const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));\n httpQuerySpans.add(span);\n return span;\n });\n\n // The connection string is resolved inside the HTTP executor, so the query span is active\n // when this settles. The executor's own context never sees the string.\n diagnosticsChannel.tracingChannel<NeonResolveConnectionContext>(CHANNELS.NEON_RESOLVE_CONNECTION).subscribe({\n start: NOOP,\n end: NOOP,\n asyncStart: NOOP,\n error: NOOP,\n asyncEnd(data) {\n const span = getActiveSpan();\n const url = data.result?.resolvedURL;\n if (!span || !httpQuerySpans.has(span) || !url) {\n return;\n }\n span.setAttributes(\n getConnectionAttributes({\n host: url.hostname,\n port: Number(url.port) || DEFAULT_PORT,\n database: url.pathname.slice(1),\n user: url.username || undefined,\n }),\n );\n },\n });\n}\n\nfunction httpQuerySpanOptions(args: unknown[]): Parameters<typeof startInactiveSpan>[0] {\n const queryData = args[0] as NeonQueryData | NeonQueryData[] | undefined;\n const batchSize = Array.isArray(queryData) ? queryData.length : undefined;\n // A batch gets one span whose text and summary list every statement, in order.\n const statements = (Array.isArray(queryData) ? queryData : [queryData])\n .map(getQueryText)\n .filter((text): text is string => !!text)\n .map(text => getSqlQueryAttributes(text));\n const queryText = joinDefined(statements.map(s => s[DB_QUERY_TEXT]));\n const querySummary = joinDefined(statements.map(s => s[DB_QUERY_SUMMARY]));\n const operationName =\n batchSize === undefined ? statements[0]?.[DB_OPERATION_NAME] : getBatchOperationName(statements);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_KIND]: 'client',\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n [DB_QUERY_TEXT]: queryText || undefined,\n [DB_QUERY_SUMMARY]: querySummary,\n [DB_OPERATION_NAME]: operationName,\n [DB_OPERATION_BATCH_SIZE]: batchSize,\n };\n\n return { name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_POSTGRESQL), onlyIfParent: true, attributes };\n}\n\n// OTel names a batch `BATCH <op>` when every statement shares one operation, plain `BATCH` otherwise.\nfunction getBatchOperationName(statements: ReturnType<typeof getSqlQueryAttributes>[]): string {\n const operations = new Set(statements.map(s => s[DB_OPERATION_NAME]?.toUpperCase()));\n const [operation] = operations;\n return operations.size === 1 && operation ? `BATCH ${operation}` : 'BATCH';\n}\n\nfunction joinDefined(parts: (string | undefined)[]): string | undefined {\n const defined = parts.filter((part): part is string => !!part);\n return defined.length ? defined.join('; ') : undefined;\n}\n\nfunction getQueryText(data: NeonQueryData | undefined): string | undefined {\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n if ('query' in data && typeof data.query === 'string') {\n return data.query;\n }\n if (!('strings' in data) || !Array.isArray(data.strings)) {\n return undefined;\n }\n if (typeof data.toParameterizedQuery === 'function') {\n try {\n // Neon's own rendering also inlines `sql.unsafe()` fragments and nested templates.\n return data.toParameterizedQuery().query;\n } catch {\n // fall through to the plain placeholder rendering\n }\n }\n return data.strings.reduce((text, part, i) => `${text}$${i}${part}`);\n}\n\n/**\n * Diagnostics-channel-based `@neondatabase/serverless` integration.\n *\n * Subscribes to the channels Sentry's code transform injects into the package's bundled pg\n * `Client.prototype.query` (WebSocket driver) and into the HTTP executor behind `neon()`, so both\n * drivers emit `db` spans with the same shape as the `pg` integration. Requires the Sentry runtime\n * hook or bundler plugin to be active.\n */\nexport const neonIntegration = defineIntegration(_neonIntegration);\n","// The `@sentry/conventions` db/net attribute keys are deprecated (superseded by newer semconv), but we\n// emit them deliberately to preserve parity with what `@opentelemetry/instrumentation-tedious` produced.\n/* oxlint-disable typescript/no-deprecated */\n\nimport { EventEmitter } from 'node:events';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport {\n defineIntegration,\n getClient,\n hasSpanStreamingEnabled,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n} from '@sentry/core';\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { tediousModuleNames } from '../orchestrion/config/tedious';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { getSqlQueryAttributes } from '../utils/sql';\n\n// NOTE: this uses the same name as the OTel integration by design. When orchestrion injection is active,\n// `_init` swaps the OTel `Tedious` integration out of the defaults and appends this one (matched by name).\nconst INTEGRATION_NAME = 'Tedious' as const;\nconst ORIGIN = 'auto.db.tedious';\n\n// OTel db/net semantic-convention values/keys not exported by `@sentry/conventions`, inlined to match\n// what `@opentelemetry/instrumentation-tedious` emitted.\nconst DB_SYSTEM_VALUE_MSSQL = 'mssql';\nconst ATTR_DB_SQL_TABLE = 'db.sql.table';\n\n// Tracks the connection's active database (updated on `databaseChange`), read into `db.namespace` when a query\n// runs. Mirrors the `CURRENT_DATABASE` symbol the vendored OTel instrumentation stashed on the connection.\nconst currentDatabaseSymbol = Symbol('sentry.orchestrion.tedious.current-database');\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\n\ninterface TediousConnectionConfig {\n server?: string;\n userName?: string;\n authentication?: { options?: { userName?: string } };\n options?: { database?: string; port?: number };\n}\n\ninterface TediousConnection extends EventEmitter {\n config?: TediousConnectionConfig;\n [currentDatabaseSymbol]?: string;\n}\n\ninterface TediousRequest extends EventEmitter {\n sqlTextOrProcedure?: string;\n callback?: UnknownFunction;\n table?: string;\n parametersByName?: Record<string, { value?: unknown } | undefined>;\n}\n\n/** Context orchestrion attaches to the query channels (wrapping the `Connection` request methods). */\ninterface TediousQueryChannelContext extends OrchestrionChannelContext {\n // `arguments[0]` is the `Request` (or `BulkLoad` for `execBulkLoad`), both `EventEmitter`s.\n arguments: [TediousRequest?, ...unknown[]];\n self?: TediousConnection;\n}\n\n/** Context orchestrion attaches to the `Connection.connect` channel. */\ninterface TediousConnectChannelContext extends OrchestrionChannelContext {\n self?: TediousConnection;\n}\n\n// Used both to seed the initial database and as the `databaseChange` listener, where `this` is the\n// connection (a non-arrow listener). Keeping one shared reference lets `removeListener` find it again.\nfunction setDatabase(this: TediousConnection, databaseName: string | undefined): void {\n Object.defineProperty(this, currentDatabaseSymbol, { value: databaseName, writable: true, configurable: true });\n}\n\n// The `end` cleanup listener, where `this` is the connection (a non-arrow listener). Named (like\n// `setDatabase`) so repeated `connect` calls can `removeListener` it rather than accumulate anonymous ones.\nfunction removeDatabaseListener(this: TediousConnection): void {\n this.removeListener('databaseChange', setDatabase);\n}\n\nfunction subscribeConnect(): void {\n diagnosticsChannel.tracingChannel(CHANNELS.TEDIOUS_CONNECT).start.subscribe(message => {\n const connection = (message as TediousConnectChannelContext).self;\n if (!connection) {\n return;\n }\n\n setDatabase.call(connection, connection.config?.options?.database);\n\n // Remove first in case `connect` runs more than once on the same connection, so neither listener\n // accumulates across reconnects.\n connection.removeListener('databaseChange', setDatabase);\n connection.on('databaseChange', setDatabase);\n connection.removeListener('end', removeDatabaseListener);\n connection.once('end', removeDatabaseListener);\n });\n}\n\nfunction subscribeQuery(channelName: string, operation: string): void {\n diagnosticsChannel.tracingChannel(channelName).start.subscribe(message => {\n const data = message as TediousQueryChannelContext;\n const connection = data.self;\n const request = data.arguments[0];\n\n // The vendored instrumentation only traced when the first argument is an `EventEmitter` (a `Request`\n // or `BulkLoad`); anything else is left untouched.\n if (!connection || !(request instanceof EventEmitter)) {\n return;\n }\n\n let procCount = 0;\n let statementCount = 0;\n const incrementStatementCount = (): void => {\n statementCount++;\n };\n const incrementProcCount = (): void => {\n procCount++;\n };\n\n const databaseName = connection[currentDatabaseSymbol];\n const sql = extractSql(request);\n const queryAttributes = getSqlQueryAttributes(sql, 'mssql');\n if (operation === 'callProcedure') {\n // `sql` is the procedure name here rather than a statement, so there is nothing to summarize.\n queryAttributes[DB_QUERY_SUMMARY] = undefined;\n queryAttributes[DB_OPERATION_NAME] = undefined;\n }\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_MSSQL,\n [DB_NAMESPACE]: databaseName,\n // `>=4` uses the `authentication` object; older versions expose `userName` directly.\n [DB_USER]: connection.config?.userName ?? connection.config?.authentication?.options?.userName,\n ...queryAttributes,\n [ATTR_DB_SQL_TABLE]: request.table,\n [SERVER_ADDRESS]: connection.config?.server,\n [SERVER_PORT]: connection.config?.options?.port,\n };\n\n // Not `getSqlSpanName`: bulk loads and procedure calls carry no statement, and naming them\n // after the operation (`execBulkLoad <table>`, `callProcedure <name>`) says more than the\n // namespace or db system it would fall back to.\n const client = getClient();\n\n const span = startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? queryAttributes[DB_QUERY_SUMMARY] ||\n getLowCardinalitySecondarySpanName(operation, databaseName, sql, request.table)\n : queryAttributes[DB_QUERY_TEXT] || getSecondarySpanName(operation, databaseName, request.table),\n attributes,\n onlyIfParent: true,\n });\n\n const endSpan = once((err?: { message?: string }): void => {\n request.removeListener('done', incrementStatementCount);\n request.removeListener('doneInProc', incrementStatementCount);\n request.removeListener('doneProc', incrementProcCount);\n request.removeListener('error', endSpan);\n connection.removeListener('end', endSpan);\n\n span.setAttribute('tedious.procedure_count', procCount);\n span.setAttribute('tedious.statement_count', statementCount);\n if (err) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: err.message });\n }\n\n span.end();\n });\n\n request.on('done', incrementStatementCount);\n request.on('doneInProc', incrementStatementCount);\n request.on('doneProc', incrementProcCount);\n request.once('error', endSpan);\n connection.on('end', endSpan);\n\n // tedious invokes `request.callback` when the request settles (passing the error, if any). Wrapping it\n // here (at `start`, before the method body dispatches) is the completion signal. A failed non-preparing\n // request reports its error only through this callback, not via an `'error'` event.\n if (typeof request.callback === 'function') {\n const originalCallback = request.callback;\n request.callback = function (this: unknown, ...args: unknown[]): unknown {\n endSpan(args[0] as { message?: string } | undefined);\n\n return originalCallback.apply(this, args);\n };\n }\n });\n}\n\nfunction extractSql(request: TediousRequest): string | undefined {\n // Required for <11.0.9: the SQL for a prepared statement is carried in the `stmt` parameter.\n if (request.sqlTextOrProcedure === 'sp_prepare' && request.parametersByName?.stmt?.value != null) {\n const value = request.parametersByName.stmt.value;\n\n return typeof value === 'string' ? value : undefined;\n }\n\n return request.sqlTextOrProcedure;\n}\n\n/**\n * Get a secondary span name for static trace lifecycle (not strictly adhering to sentry-convention span names)\n */\nfunction getSecondarySpanName(operation: string, db: string | undefined, bulkLoadTable: string | undefined): string {\n if (operation === 'execBulkLoad' && bulkLoadTable && db) {\n return `${operation} ${bulkLoadTable} ${db}`;\n }\n // Avoid `sql` in the general case because of its high cardinality.\n return db ? `${operation} ${db}` : operation;\n}\n\nfunction getLowCardinalitySecondarySpanName(\n operation: string,\n db: string | undefined,\n sql: string | undefined,\n bulkLoadTable: string | undefined,\n): string {\n if (operation === 'execBulkLoad' && bulkLoadTable) {\n return `${operation} ${bulkLoadTable}`;\n }\n if (operation === 'callProcedure' && sql) {\n // `sql` refers to the procedure name for `callProcedure`, so it is low-cardinality in this case.\n return `${operation} ${sql}`;\n }\n return db ? `${operation} ${db}` : operation;\n}\n\nfunction once<Args extends unknown[]>(fn: (...args: Args) => void): (...args: Args) => void {\n let called = false;\n\n return (...args: Args): void => {\n if (called) {\n return;\n }\n called = true;\n fn(...args);\n };\n}\n\nconst _tediousIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, tediousModuleNames, instrumentTedious, [], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentTedious(): void {\n subscribeConnect();\n subscribeQuery(CHANNELS.TEDIOUS_EXEC_SQL, 'execSql');\n subscribeQuery(CHANNELS.TEDIOUS_EXEC_SQL_BATCH, 'execSqlBatch');\n subscribeQuery(CHANNELS.TEDIOUS_CALL_PROCEDURE, 'callProcedure');\n subscribeQuery(CHANNELS.TEDIOUS_EXEC_BULK_LOAD, 'execBulkLoad');\n subscribeQuery(CHANNELS.TEDIOUS_PREPARE, 'prepare');\n subscribeQuery(CHANNELS.TEDIOUS_EXECUTE, 'execute');\n}\n\n/**\n * Diagnostics-channel-based tedious integration.\n *\n * Subscribes to the `orchestrion:tedious:*` diagnostics_channels that Sentry's code transform\n * injects into tedious's `Connection` request methods (each traced as one db span) and `Connection.connect`\n * (active-database bookkeeping). Requires the Sentry runtime hook or bundler plugin to be active.\n */\nexport const tediousIntegration = defineIntegration(_tediousIntegration);\n","import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.\n * They must not be written onto a span that reports usage aggregated across steps\n * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.\n */\nexport const LAST_STEP_ONLY_USAGE_KEYS = new Set<string>([\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n]);\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n","/** Shared, state-free helpers for the Vercel AI (`ai`) channel subscribers, plus the streamed model-call tap. */\n\nimport { isObjectLike } from '@sentry/core';\n\n/** Narrow to a string, or `undefined` for anything else. */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Narrow to a finite number, or `undefined` for anything else (including `NaN`). */\nexport function asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && !isNaN(value) ? value : undefined;\n}\n\n/** Add two optional numbers, treating a missing operand as `0` but returning `undefined` when both are absent. */\nexport function sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/*\n * Streaming support for the `ai:telemetry` tracing channel.\n *\n * For a streamed model call (`doStream`) the SDK resolves the `languageModelCall` channel promise as\n * soon as it hands back the *unconsumed* stream — so `result.stream` is a `ReadableStream` and the\n * final usage / finish reason / output only arrive later, as the stream is drained (they ride the\n * stream's own `finish`/`text-delta`/`tool-call` chunks, never the channel context). The SDK\n * deliberately leaves `result` undefined on the `streamText`/`step` contexts and exposes the stream\n * only on the model call, expecting consumers to tap it themselves.\n * @see https://github.com/vercel/ai/pull/15660 (discussion: \"tee off and aggregate ourselves\")\n *\n * We replace `result.stream` with a passthrough that forwards every chunk untouched (so the SDK's own\n * consumption is unaffected) while accumulating the data we need, then hand the aggregate back once the\n * stream settles so the model-call span can be enriched and ended out-of-band.\n */\n\n/** The subset of a streamed provider chunk we read. Unknown chunk types are forwarded and ignored. */\ninterface StreamChunk {\n type?: unknown;\n delta?: unknown;\n // v4 text-delta chunks carry the text on `textDelta`; v5+ uses `delta`.\n textDelta?: unknown;\n id?: unknown;\n modelId?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n input?: unknown;\n args?: unknown;\n finishReason?: unknown;\n usage?: unknown;\n providerMetadata?: unknown;\n error?: unknown;\n}\n\n/** The aggregate handed back once a streamed model call finishes, in the shape `enrichSpanOnEnd` expects. */\nexport interface StreamedModelCallResult {\n text?: string;\n toolCalls: Array<Record<string, unknown>>;\n usage?: unknown;\n finishReason?: unknown;\n responseId?: string;\n responseModel?: string;\n providerMetadata?: unknown;\n}\n\n/** The streamed model call exposes a web `ReadableStream` on `result.stream`. */\nexport { isReadableStream } from '../../ai/core/utils';\n\n/**\n * Wrap a streamed model call's `ReadableStream` so its chunks are observed as the SDK consumes them,\n * without altering what the SDK sees. Returns a replacement stream to swap onto `result.stream`.\n *\n * `onFinal` runs exactly once when the stream drains cleanly; `onError` runs exactly once if it errors\n * or is cancelled. Reading one source chunk per `pull` preserves the SDK's backpressure. The\n * `try/catch` around every read guarantees the owning span is always ended — a leaked open span on a\n * mid-stream failure would be worse than a slightly-less-enriched one.\n */\nexport function tapModelCallStream(\n stream: ReadableStream<unknown>,\n onFinal: (result: StreamedModelCallResult) => void,\n onError: (error: unknown) => void,\n): ReadableStream<unknown> {\n const reader = stream.getReader();\n const state: StreamedModelCallResult = { toolCalls: [] };\n let text = '';\n let settled = false;\n\n const finalize = (): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (text) {\n state.text = text;\n }\n onFinal(state);\n };\n\n const fail = (error: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n onError(error);\n };\n\n return new ReadableStream<unknown>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finalize();\n controller.close();\n\n return;\n }\n text += accumulateChunk(state, value) ?? '';\n controller.enqueue(value);\n } catch (error) {\n fail(error);\n controller.error(error);\n }\n },\n cancel(reason) {\n // Consumer stopped reading early (e.g. a `break` out of `for await`); close out the span with\n // whatever we have rather than leave it open. A non-error reason is a deliberate stop, not a failure.\n finalize();\n\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Fold a single streamed chunk into the running aggregate. Returns any text delta so the caller can\n * accumulate it (kept out of `state` until the end to avoid re-joining on every chunk).\n */\nfunction accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string | undefined {\n if (!isObjectLike(chunk)) {\n return undefined;\n }\n const {\n type,\n delta,\n textDelta,\n id,\n modelId,\n toolCallId,\n toolName,\n input,\n args,\n finishReason,\n usage,\n providerMetadata,\n } = chunk as StreamChunk;\n\n switch (type) {\n case 'text-delta': {\n const textChunk = delta ?? textDelta;\n return typeof textChunk === 'string' ? textChunk : undefined;\n }\n case 'tool-call':\n state.toolCalls.push({ toolCallId, toolName, input: input ?? args });\n\n return undefined;\n case 'response-metadata':\n if (typeof id === 'string') {\n state.responseId = id;\n }\n if (typeof modelId === 'string') {\n state.responseModel = modelId;\n }\n\n return undefined;\n case 'finish':\n state.finishReason = finishReason;\n state.usage = usage;\n if (providerMetadata !== undefined) {\n state.providerMetadata = providerMetadata;\n }\n\n return undefined;\n default:\n return undefined;\n }\n}\n","/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport { getEvaluationOutputMessages, type GenAiOptions } from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { asNumber, asString, isReadableStream, type StreamedModelCallResult, sum, tapModelCallStream } from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/** Integration-level recording options, pinned at subscribe time so we never look the integration up per event. */\nexport type VercelAiChannelOptions = GenAiOptions;\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data, options);\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, options, end),\n },\n );\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(\n span: Span,\n data: VercelAiChannelMessage,\n options: VercelAiChannelOptions,\n end: (error?: unknown) => void,\n): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const { recordOutputs } = getRecordingOptions(data.event, options, data.result === undefined);\n result.stream = tapModelCallStream(\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n enrichInvokeAgentFromStream(callId, final, recordOutputs);\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(\n callId: string | undefined,\n final: StreamedModelCallResult,\n recordOutputs: boolean,\n): void {\n const span = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n if (!span) {\n return;\n }\n\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const { recordInputs } = getRecordingOptions(event, channelOptions);\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(\n span: Span,\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(data.event, channelOptions, data.result === undefined);\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return Object.fromEntries(\n Object.entries(answers).map(([id, answer]) => {\n if (!isObjectLike(answer)) {\n return [id, answer];\n }\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return [id, { ...answer, confidence, legend }];\n }),\n );\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n channelOptions: VercelAiChannelOptions,\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(channelOptions.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(channelOptions.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n","import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op';\nimport { getActiveSpan, handleCallbackErrors, spanToJSON } from '@sentry/core';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport * as dc from '../../utils/diagnosticsChannel';\nimport {\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n fallbackChannelResults,\n type VercelAiChannelMessage,\n} from './vercel-ai-dc-subscriber';\n\ninterface ToolOutput {\n type: 'tool-result' | 'tool-error';\n toolCallId: string;\n output?: unknown;\n error?: unknown;\n}\n\n/** The subset of `ai`'s `Telemetry` integration interface this uses. */\ninterface TelemetryIntegration {\n executeLanguageModelCall?<T>(options: Record<string, unknown> & { execute: () => PromiseLike<T> }): PromiseLike<T>;\n executeTool?<T>(\n options: Record<string, unknown> & { toolCallId: string; execute: () => PromiseLike<T> },\n ): PromiseLike<T>;\n onToolExecutionEnd?(event: { toolOutput: ToolOutput }): void;\n}\n\nconst openToolCalls = new Map<string, { message: VercelAiChannelMessage; error?: unknown }>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for these calls.\nfunction isRecordingOff(event: Record<string, unknown>): boolean {\n return event.recordInputs === false || event.recordOutputs === false;\n}\n\n/**\n * Register a global `ai` (>= 7) telemetry integration that covers what the `ai:telemetry` channel misses.\n * Frameworks such as eve (>= 0.84) run tools outside `ai`'s tool loop, so `ai` publishes nothing for them,\n * and `ai` >= 7.0.163 publishes no results for calls with `recordInputs`/`recordOutputs: false`.\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry\n */\nexport function registerVercelAiToolTelemetry(): void {\n const channel = dc.tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL);\n const carrier = globalThis as { AI_SDK_TELEMETRY_INTEGRATIONS?: TelemetryIntegration[] };\n\n (carrier.AI_SDK_TELEMETRY_INTEGRATIONS ??= []).push({\n // Runs inside the `languageModelCall` channel span, unless that span was ignored.\n async executeLanguageModelCall({ execute, ...event }) {\n const span = isRecordingOff(event) ? getActiveSpan() : undefined;\n const result = await execute();\n if (span && spanToJSON(span).attributes?.[SENTRY_OP] === GEN_AI_GENERATE_CONTENT) {\n fallbackChannelResults.set(span, result);\n }\n return result;\n },\n\n executeTool({ execute, ...event }) {\n // `ai`'s own tool loop calls this inside its own `executeTool` channel span.\n const activeSpan = getActiveSpan();\n if (activeSpan && spanToJSON(activeSpan).attributes?.[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] === event.toolCallId) {\n return isRecordingOff(event)\n ? handleCallbackErrors(execute, error => {\n fallbackChannelResults.set(activeSpan, { output: { type: 'tool-error', error } });\n })\n : execute();\n }\n\n // Also reached from `ai`'s own tool loop when its span is unsampled or ignored, where `toolOutput` is filtered.\n const call: { message: VercelAiChannelMessage; error?: unknown } = { message: { type: 'executeTool', event } };\n const { message } = call;\n openToolCalls.set(event.toolCallId, call);\n try {\n return channel.start.runStores(message, () =>\n handleCallbackErrors(execute, error => {\n call.error = error;\n }),\n );\n } finally {\n // Without a `result` this leaves the span open until `onToolExecutionEnd`.\n channel.end.publish(message);\n }\n },\n\n // The tool output only arrives here, after `execute` has settled.\n onToolExecutionEnd({ toolOutput }) {\n const call = openToolCalls.get(toolOutput.toolCallId);\n if (!call) {\n return;\n }\n openToolCalls.delete(toolOutput.toolCallId);\n const { message, error } = call;\n\n // Same result shape as `ai`'s own `executeTool` events, so the subscriber records the output or captures the error.\n // `ai` >= 7.0.163 replaces `toolOutput.error` with a generic error when recording is off.\n message.result = {\n output:\n toolOutput.type === 'tool-error' ? { ...toolOutput, error: error ?? toolOutput.error } : toolOutput.output,\n };\n channel.asyncEnd.publish(message);\n },\n });\n}\n","/* 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","import { defineIntegration, waitForTracingChannelBinding, type IntegrationFn } from '@sentry/core';\nimport type { GenAiOptions } from '../../ai/core/utils';\nimport { subscribeVercelAiTracingChannel } from './vercel-ai-dc-subscriber';\nimport { registerVercelAiToolTelemetry } from './vercel-ai-tool-telemetry';\nimport * as dc from '../../utils/diagnosticsChannel';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { vercelAiModuleNames } from '../../orchestrion/config/vercel-ai';\nimport { subscribeVercelAiOrchestrionChannels } from './vercel-ai-orchestrion-subscriber';\n\n/** Options for the Vercel AI integration. */\nexport type VercelAiOptions = GenAiOptions;\n\nconst _vercelAIIntegration = ((options: VercelAiOptions = {}) => {\n return {\n name: 'VercelAI' as const,\n setupOnce() {\n // Bail if this is not available\n if (!dc.tracingChannel) {\n return;\n }\n\n // Subscribe to the `ai` SDK's native telemetry tracing channel (ai >= 7).\n // This is a no-op on versions that don't publish to the channel, so it is always safe to call.\n waitForTracingChannelBinding(() => {\n subscribeVercelAiTracingChannel(dc.tracingChannel, options);\n });\n registerVercelAiToolTelemetry();\n },\n setup(client) {\n invokeOrchestrionInstrumentation(client, vercelAiModuleNames, instrumentVercelAiOrchestrion, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Auto-instrument the `ai` SDK. Supported are:\n * - v7 via native `ai:telemetry` tracing channel\n * - v4, v5 & v6 via the injected `orchestrion:ai:*` channels\n */\nexport const vercelAIIntegration = defineIntegration(_vercelAIIntegration);\n\nfunction instrumentVercelAiOrchestrion(options: VercelAiOptions): void {\n subscribeVercelAiOrchestrionChannels(dc.tracingChannel, options);\n}\n","import type { ExpressLayer, ExpressRequest } from './types';\n\n/**\n * Registered path *pattern* per routing `Layer`, captured when the layer is\n * registered via `Router.prototype.route`/`.use`. `undefined` means the layer\n * was registered without an explicit path (e.g. `app.use(mw)`), so it does not\n * contribute to the reconstructed route.\n *\n * This is the piece `req.baseUrl` can't provide: at request time `req.baseUrl`\n * holds the *resolved* mount prefix (`/api/v1`), whereas we want the registered\n * pattern (`/api/:version`).\n */\nconst layerRegisteredPaths = new WeakMap<ExpressLayer, string | undefined>();\n\n/** Record the path pattern a layer was registered with. */\nexport function setLayerRegisteredPath(layer: ExpressLayer, path: string | undefined): void {\n layerRegisteredPaths.set(layer, path);\n}\n\n/** Read the path pattern a layer was registered with, if any. */\nexport function getLayerRegisteredPath(layer: ExpressLayer): string | undefined {\n return layerRegisteredPaths.get(layer);\n}\n\n/**\n * Per-request ordered stack of the registered path patterns of the layers\n * currently on the matched chain. Layers push on entry and pop when they hand\n * off via `next`, so at any point it reflects the path from the app root down\n * to the currently-executing layer. `WeakMap` so entries are released with the\n * request.\n */\nconst requestLayerPaths = new WeakMap<ExpressRequest, string[]>();\n\nfunction getStore(req: ExpressRequest): string[] {\n let store = requestLayerPaths.get(req);\n if (!store) {\n store = [];\n requestLayerPaths.set(req, store);\n }\n return store;\n}\n\n/** Push a layer's registered path onto the request's chain. */\nexport function pushLayerPath(req: ExpressRequest, path: string): void {\n getStore(req).push(path);\n}\n\n/** Pop the most recently pushed layer path off the request's chain. */\nexport function popLayerPath(req: ExpressRequest): void {\n getStore(req).pop();\n}\n\n/**\n * The path pattern a `route`/`use` call registered, derived from its arguments.\n * A leading string/RegExp/number path becomes the pattern (arrays are joined\n * with `,`); a bare handler function yields `undefined`. Kept in sync with\n * `@sentry/core`'s Express `getLayerPath`.\n */\nexport function getLayerPath(args: unknown[]): string | undefined {\n const firstArg = args[0];\n if (Array.isArray(firstArg)) {\n return firstArg.map(segment => extractLayerPathSegment(segment) ?? '').join(',');\n }\n return extractLayerPathSegment(firstArg);\n}\n\nfunction extractLayerPathSegment(segment: unknown): string | undefined {\n return typeof segment === 'string'\n ? segment\n : segment instanceof RegExp || typeof segment === 'number'\n ? String(segment)\n : undefined;\n}\n\n/**\n * Concatenate the stored layer paths into the full route pattern (parameters\n * preserved), e.g. `/api/:version/user`. Mirrors `@sentry/core`.\n */\nexport function getConstructedRoute(req: ExpressRequest): string {\n const layersStore = getStore(req);\n\n let constructedRoute = '';\n for (const path of layersStore) {\n if (path === '/' || path === '/*') {\n continue;\n }\n constructedRoute += !constructedRoute || constructedRoute.endsWith('/') ? path : `/${path}`;\n }\n\n return constructedRoute.replace(/\\/{2,}/g, '/');\n}\n\n/**\n * Validate the constructed route against the request URL, returning it only\n * when it plausibly corresponds to a real match (otherwise `undefined`). Mirrors\n * `@sentry/core`'s `getActualMatchedRoute` — used for the `http.route` attribute.\n */\nexport function getActualMatchedRoute(req: ExpressRequest, constructedRoute: string): string | undefined {\n const layersStore = getStore(req);\n\n if (layersStore.length === 0) {\n return undefined;\n }\n\n const originalUrl = typeof req.originalUrl === 'string' ? req.originalUrl : '';\n\n // The layer store also includes root paths in case a non-existing url was requested.\n if (layersStore.every(path => path === '/')) {\n return originalUrl === '/' ? '/' : undefined;\n }\n\n if (constructedRoute === '*') {\n return constructedRoute;\n }\n\n // For RegExp routes or route arrays, return the constructed route as-is.\n if (\n constructedRoute.includes('/') &&\n (constructedRoute.includes(',') ||\n constructedRoute.includes('\\\\') ||\n constructedRoute.includes('*') ||\n constructedRoute.includes('['))\n ) {\n return constructedRoute;\n }\n\n const normalizedRoute = constructedRoute.startsWith('/') ? constructedRoute : `/${constructedRoute}`;\n\n const isValidRoute =\n normalizedRoute.length > 0 &&\n (originalUrl === normalizedRoute || originalUrl.startsWith(normalizedRoute) || isRoutePattern(normalizedRoute));\n\n return isValidRoute ? normalizedRoute : undefined;\n}\n\n/** Whether a route contains parameter/wildcard patterns (`:id`, `*`). */\nfunction isRoutePattern(route: string): boolean {\n return route.includes(':') || route.includes('*');\n}\n","import type { MiddlewareError } from './types';\n\nfunction getStatusCodeFromResponse(error: MiddlewareError): number {\n const statusCode = error.status || error.statusCode || error.status_code || error.output?.statusCode;\n return statusCode ? parseInt(statusCode as string, 10) : 500;\n}\n\n/**\n * Default function deciding whether an error should be sent to Sentry: captures\n * 5xx errors, and treats an error without a resolvable status as a 500. Errors\n * carrying a 3xx/4xx status are skipped (client errors / redirects).\n */\nexport function defaultShouldHandleError(error: MiddlewareError): boolean {\n return getStatusCodeFromResponse(error) >= 500;\n}\n","import { addNonEnumerableProperty } from '@sentry/core';\n\n// Non-enumerable marker set on the Express *request* once the channel-based `expressIntegration()` has\n// taken responsibility for an error on it — either captured it, or deliberately skipped it per\n// `shouldHandleError`. The deprecated `expressErrorHandler` middleware reads this to defer to the\n// integration, so an Express error is only ever handled once and the integration's `shouldHandleError`\n// decision always wins.\n//\n// The marker lives on the request (not the error) on purpose: the request is always a mutable object\n// and is the same instance across every layer the error bubbles through and the error-handling\n// middleware, whereas the thrown value may be frozen or a primitive. It also does not rely on\n// `captureException`'s global `__sentry_captured__` dedup, which is only set when an error is actually\n// captured and so cannot express a \"deliberately skipped\" decision.\nconst EXPRESS_ERROR_HANDLED = '__sentry_express_error_handled__';\n\n/**\n * Mark an Express request as having had its error handled by the channel-based `expressIntegration()`,\n * so the deprecated `expressErrorHandler` middleware defers to that decision.\n */\nexport function markExpressErrorHandled(request: unknown): void {\n if (request && typeof request === 'object') {\n addNonEnumerableProperty(request, EXPRESS_ERROR_HANDLED, true);\n }\n}\n\n/**\n * Whether the channel-based `expressIntegration()` has already handled an error on this Express request.\n */\nexport function isExpressErrorHandled(request: unknown): boolean {\n return !!(request && typeof request === 'object' && (request as Record<string, unknown>)[EXPRESS_ERROR_HANDLED]);\n}\n","import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { expressModuleNames } from '../../orchestrion/config/express';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport type { ExpressIntegrationOptions } from './types';\nimport { instrumentExpress } from './instrumentation';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Express' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Express' as const;\n\nconst _expressIntegration = ((options: ExpressIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, expressModuleNames, instrumentExpress, [\n options,\n diagnosticsChannel.tracingChannel,\n ]);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Diagnostics-channel-based Express integration.\n *\n * Subscribes to the `orchestrion:express:handle` (Express v4) and\n * `orchestrion:router:handle` (Express v5, via the `router` package)\n * diagnostics_channels that Sentry's code transform injects into the\n * routing layer's request handler (`Layer.prototype.handle_request` /\n * `handleRequest`). One span is opened per layer invocation — producing the\n * same spans as the OTel Express instrumentation.\n *\n * Requires the Sentry runtime hook or bundler plugin to be active.\n */\nexport const expressIntegration = defineIntegration(_expressIntegration);\n","import { captureException, getIsolationScope, httpRequestToRequestData } from '@sentry/core';\nimport { isExpressErrorHandled } from './error-handled';\nimport type { ExpressRequest, ExpressResponse, MiddlewareError } from './types';\nimport { defaultShouldHandleError } from './utils';\n\ntype ExpressErrorMiddleware = (\n error: MiddlewareError,\n request: ExpressRequest,\n res: ExpressResponse,\n next: (error: MiddlewareError) => void,\n) => void;\n\ntype ExpressMiddleware = (request: ExpressRequest, res: ExpressResponse, next: () => void) => void;\n\n/**\n * Set request data on the isolation scope so a captured error carries request context. Mirrors the\n * request handler middleware, which does not run once an error short-circuits the middleware chain.\n */\nfunction setSDKProcessingMetadata(request: ExpressRequest): void {\n const sdkProcMeta = getIsolationScope()?.getScopeData()?.sdkProcessingMetadata;\n if (!sdkProcMeta?.normalizedRequest) {\n const normalizedRequest = httpRequestToRequestData(request);\n getIsolationScope().setSDKProcessingMetadata({ normalizedRequest });\n }\n}\n\n/**\n * An Express-compatible error handler, used by {@link setupExpressErrorHandler}.\n *\n * @deprecated `expressIntegration()` now captures errors automatically. This export is deprecated and\n * will be removed in the next major version. Migrate to the `expressIntegration` to filter with `shouldHandleError`.\n */\nexport function expressErrorHandler(): ExpressErrorMiddleware {\n return function sentryErrorMiddleware(error, request, res, next): void {\n // When an error happens, the request handler middleware does not run, so we set it here too.\n setSDKProcessingMetadata(request);\n\n // The channel-based `expressIntegration()` captures at the throw site, before this middleware runs,\n // and marks the request when it does. If it already handled this request's error (captured it, or\n // deliberately skipped it per its own `shouldHandleError`), defer to that decision: the integration\n // is the single registered handler and its `shouldHandleError` wins, so we never double-capture or\n // override it here.\n if (isExpressErrorHandled(request)) {\n next(error);\n return;\n }\n\n // `shouldHandleError` is an `expressIntegration()` feature and is deliberately not honoured here:\n // this path exists to keep capturing errors, not to filter them.\n if (defaultShouldHandleError(error)) {\n const eventId = captureException(error, {\n mechanism: { type: 'auto.middleware.express', handled: false },\n });\n (res as { sentry?: string }).sentry = eventId;\n }\n\n next(error);\n };\n}\n\nfunction expressRequestHandler(): ExpressMiddleware {\n return function sentryRequestMiddleware(request, _res, next): void {\n setSDKProcessingMetadata(request);\n next();\n };\n}\n\n/**\n * Add an Express error handler to capture errors to Sentry.\n *\n * The error handler must be before any other middleware and after all controllers.\n *\n * @param app The Express instance\n *\n * @deprecated `expressIntegration()` now captures errors automatically, so calling this error handler is no longer\n * necessary. To customize which errors are captured, pass `shouldHandleError` to `expressIntegration()`.\n * This export is deprecated and will be removed in the next major version.\n */\nexport function setupExpressErrorHandler(app: {\n // oxlint-disable-next-line no-explicit-any\n use: (middleware: any) => unknown;\n}): void {\n app.use(expressRequestHandler());\n // oxlint-disable-next-line typescript/no-deprecated\n app.use(expressErrorHandler());\n}\n","import * as net from 'node:net';\nimport {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { startInactiveSpan } from '@sentry/core';\nimport type { FirebaseApp, FirebaseOptions, FirestoreReference, FirestoreSettings } from './firestore-types';\n\n/**\n * Opens the inactive `db.query` span for a Firestore operation. `bindTracingChannelToSpan` makes it the\n * active span for the traced call and ends it when the call settles. Mirrors the OTel integration's span.\n */\nexport function startFirestoreSpan(spanName: string, reference: FirestoreReference): Span {\n return startInactiveSpan({\n name: `${spanName} ${reference.path}`,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: 'auto.db.firebase.firestore',\n [DB_OPERATION_NAME]: spanName,\n ...buildAttributes(reference),\n },\n });\n}\n\n/**\n * Gets the server address and port attributes from the Firestore settings.\n * It's best effort to extract the address and port from the settings, especially for IPv6.\n * @param settings - The Firestore settings containing host information.\n */\nexport function getPortAndAddress(settings: FirestoreSettings): {\n address?: string;\n port?: number;\n} {\n let address: string | undefined;\n let port: string | undefined;\n\n if (typeof settings.host === 'string') {\n if (settings.host.startsWith('[')) {\n // IPv6 addresses can be enclosed in square brackets, e.g., [2001:db8::1]:8080\n if (settings.host.endsWith(']')) {\n // IPv6 with square brackets without port\n address = settings.host.replace(/^\\[|\\]$/g, '');\n } else if (settings.host.includes(']:')) {\n // IPv6 with square brackets with port\n const lastColonIndex = settings.host.lastIndexOf(':');\n if (lastColonIndex !== -1) {\n address = settings.host.slice(1, lastColonIndex).replace(/^\\[|\\]$/g, '');\n port = settings.host.slice(lastColonIndex + 1);\n }\n }\n } else {\n // IPv4 or IPv6 without square brackets\n // If it's an IPv6 address without square brackets, we assume it does not have a port.\n if (net.isIPv6(settings.host)) {\n address = settings.host;\n }\n // If it's an IPv4 address, we can extract the port if it exists.\n else {\n const lastColonIndex = settings.host.lastIndexOf(':');\n if (lastColonIndex !== -1) {\n address = settings.host.slice(0, lastColonIndex);\n port = settings.host.slice(lastColonIndex + 1);\n } else {\n address = settings.host;\n }\n }\n }\n }\n return {\n address: address,\n port: port ? parseInt(port, 10) : undefined,\n };\n}\n\nfunction buildAttributes(reference: FirestoreReference): SpanAttributes {\n const firestoreApp: FirebaseApp = reference.firestore.app;\n const firestoreOptions: FirebaseOptions = firestoreApp.options;\n const settings: FirestoreSettings = reference.firestore.toJSON()?.settings || {};\n\n const attributes: SpanAttributes = {\n [DB_COLLECTION_NAME]: reference.path,\n [DB_NAMESPACE]: firestoreApp.name,\n [DB_SYSTEM_NAME]: 'firebase.firestore',\n 'firebase.firestore.type': reference.type,\n 'firebase.firestore.options.projectId': firestoreOptions.projectId,\n 'firebase.firestore.options.appId': firestoreOptions.appId,\n 'firebase.firestore.options.messagingSenderId': firestoreOptions.messagingSenderId,\n 'firebase.firestore.options.storageBucket': firestoreOptions.storageBucket,\n };\n\n const { address, port } = getPortAndAddress(settings);\n\n if (address) {\n attributes[SERVER_ADDRESS] = address;\n }\n if (port) {\n attributes[SERVER_PORT] = port;\n }\n\n return attributes;\n}\n","import type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport {\n FAAS_NAME,\n FAAS_TRIGGER,\n GCP_FUNCTION_CONTEXT_TYPE,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION_GCP } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport {\n captureException,\n flush,\n getClient,\n hasSpanStreamingEnabled,\n SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startSpanManual,\n} from '@sentry/core';\n\nconst FUNCTIONS_ORIGIN = 'auto.function.firebase';\n\n// Set on a wrapped handler so re-entrant `start` events don't double-wrap it.\nconst WRAPPED = '__sentryFirebaseWrapped';\n\ntype Handler = (this: unknown, ...args: unknown[]) => unknown;\n\n/**\n * Rewrap the handler argument of a firebase-functions `onX(...)` registration so the returned cloud\n * function opens a `SERVER` span (and error boundary) each time it's invoked. Runs as the tracing\n * channel's `start` subscriber, before orchestrion forwards the (mutated) arguments to the real call.\n *\n * The registration call itself is trivial and synchronous, so — unlike the firestore path — this does\n * not bind a span to the channel; it only uses the channel as an injection point.\n */\nexport function wrapFunctionsRegistration(data: OrchestrionChannelContext, triggerType: string): void {\n const args = data.arguments;\n if (!Array.isArray(args) || args.length === 0) {\n return;\n }\n\n const handlerIndex = typeof args[0] === 'function' ? 0 : 1;\n const handler = args[handlerIndex];\n\n if (typeof handler !== 'function' || (handler as unknown as Record<string, unknown>)[WRAPPED]) {\n return;\n }\n\n args[handlerIndex] = wrapHandler(handler as Handler, triggerType);\n}\n\nfunction wrapHandler(handler: Handler, triggerType: string): Handler {\n const wrapped = async function (this: unknown, ...handlerArgs: unknown[]): Promise<unknown> {\n const functionName = getFunctionName();\n\n const enhancedTriggerType = `firebase.function.${triggerType}`;\n\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: FUNCTIONS_ORIGIN,\n [FAAS_NAME]: functionName,\n [FAAS_TRIGGER]: triggerType,\n 'faas.provider': 'firebase',\n [SENTRY_KIND]: 'server',\n [SENTRY_OP]: FUNCTION_GCP,\n [SENTRY_SEGMENT_NAME_SOURCE]: 'component',\n\n // This is a bit of \"cheating\" but not entirely wrong:\n // by setting this attribute, the span description of a streamed span will be set to the\n // static span name, which is the triggerType string.\n [GCP_FUNCTION_CONTEXT_TYPE]: enhancedTriggerType,\n };\n\n if (process.env.GCLOUD_PROJECT) {\n attributes['cloud.project_id'] = process.env.GCLOUD_PROJECT;\n }\n\n if (process.env.EVENTARC_CLOUD_EVENT_SOURCE) {\n attributes['cloud.event_source'] = process.env.EVENTARC_CLOUD_EVENT_SOURCE;\n }\n\n const client = getClient();\n const name =\n client && hasSpanStreamingEnabled(client)\n ? functionName || SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK\n : enhancedTriggerType;\n\n // `startSpanManual` keeps the span active while still allowing us to end it before flushing on error.\n return startSpanManual(\n {\n name,\n attributes,\n },\n async span => {\n try {\n const result = await handler.apply(this, handlerArgs);\n span.end();\n return result;\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n captureException(error, {\n mechanism: {\n type: FUNCTIONS_ORIGIN,\n handled: false,\n },\n });\n span.end();\n await flush(2000);\n throw error;\n }\n },\n );\n };\n\n (wrapped as unknown as Record<string, unknown>)[WRAPPED] = true;\n return wrapped;\n}\n\n/**\n * Resolves the name of the currently executing cloud function.\n *\n * Mirrors `getFunctionName` in `@sentry/google-cloud-serverless`: both feed `faas.name` for\n * `function.gcp` spans, so the resolution order has to stay the same in the two places.\n */\nfunction getFunctionName(): string | undefined {\n return process.env.FUNCTION_TARGET || process.env.K_SERVICE || undefined;\n}\n","import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan, safeChannelCallback } from '../../tracing-channel';\nimport type { FirestoreReference } from './firestore-types';\nimport { startFirestoreSpan } from './firestore';\nimport { wrapFunctionsRegistration } from './functions';\n\n// The context orchestrion's transform attaches to each firestore channel: `arguments` is the live args\n// of the wrapped `addDoc`/`getDocs`/`setDoc`/`deleteDoc` call, `arguments[0]` the reference.\n// The firestore operations, keyed by channel. `useParent` mirrors the OTel integration: `setDoc`/\n// `deleteDoc` take a *document* reference but the span is named after its parent *collection*.\nconst FIRESTORE_OPERATIONS: Array<{ channel: string; spanName: string; useParent: boolean }> = [\n { channel: CHANNELS.FIREBASE_FIRESTORE_ADD_DOC, spanName: 'addDoc', useParent: false },\n { channel: CHANNELS.FIREBASE_FIRESTORE_GET_DOCS, spanName: 'getDocs', useParent: false },\n { channel: CHANNELS.FIREBASE_FIRESTORE_SET_DOC, spanName: 'setDoc', useParent: true },\n { channel: CHANNELS.FIREBASE_FIRESTORE_DELETE_DOC, spanName: 'deleteDoc', useParent: true },\n];\n\n// The firebase-functions triggers, keyed by channel. The value is the faas trigger type used for the\n// span name (`firebase.function.<trigger>`) and `faas.trigger` attribute.\nconst FUNCTIONS_TRIGGERS: Array<{ channel: string; triggerType: string }> = [\n { channel: CHANNELS.FIREBASE_FUNCTIONS_HTTP_REQUEST, triggerType: 'http.request' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_HTTP_CALL, triggerType: 'http.call' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_FIRESTORE_CREATED, triggerType: 'firestore.document.created' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_FIRESTORE_UPDATED, triggerType: 'firestore.document.updated' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_FIRESTORE_DELETED, triggerType: 'firestore.document.deleted' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_FIRESTORE_WRITTEN, triggerType: 'firestore.document.written' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_SCHEDULER, triggerType: 'scheduler.scheduled' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_STORAGE_FINALIZED, triggerType: 'storage.object.finalized' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_STORAGE_ARCHIVED, triggerType: 'storage.object.archived' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_STORAGE_DELETED, triggerType: 'storage.object.deleted' },\n { channel: CHANNELS.FIREBASE_FUNCTIONS_STORAGE_METADATA_UPDATED, triggerType: 'storage.object.metadataUpdated' },\n];\n\nconst NOOP = (): void => {};\n\nexport function instrumentFirebase() {\n for (const { channel, spanName, useParent } of FIRESTORE_OPERATIONS) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel), data =>\n safeChannelCallback(() => {\n const reference = data.arguments[0] as FirestoreReference | undefined;\n if (!reference) {\n return undefined;\n }\n const spanReference = useParent ? reference.parent || reference : reference;\n return startFirestoreSpan(spanName, spanReference);\n }),\n );\n }\n\n for (const { channel, triggerType } of FUNCTIONS_TRIGGERS) {\n // Functions are wrapped, not span-bound: the handler runs long after this synchronous\n // registration call, so we only rewrap the handler argument here (in `start`) and open the\n // span inside that wrapper. The other lifecycle events are irrelevant, so no-op them.\n diagnosticsChannel.tracingChannel(channel).subscribe({\n start: data =>\n safeChannelCallback(() => wrapFunctionsRegistration(data as OrchestrionChannelContext, triggerType)),\n end: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n });\n }\n}\n","import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { firebaseModuleNames } from '../../orchestrion/config/firebase';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { instrumentFirebase } from './instrumentation';\n\nconst INTEGRATION_NAME = 'Firebase' as const;\n\nconst _firebaseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, firebaseModuleNames, instrumentFirebase, []);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Diagnostics-channel-based firebase integration.\n *\n * Subscribes to the `orchestrion:@firebase/firestore:*` and `orchestrion:firebase-functions:*`\n * diagnostics_channels Sentry's code transform injects into firestore's `addDoc`/`getDocs`/\n * `setDoc`/`deleteDoc` and firebase-functions' `onX` registration functions, emitting spans identical\n * to the OTel integration. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const firebaseIntegration = defineIntegration(_firebaseIntegration);\n","import {\n CACHE_HIT,\n CACHE_KEY,\n CACHE_OPERATION,\n SENTRY_OP,\n SENTRY_ORIGIN,\n DB_COLLECTION_NAME,\n DB_OPERATION_NAME,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op';\nimport {\n CACHE_OPERATION_NAMES,\n getClient,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n isObjectLike,\n _INTERNAL_safeDateNow as safeDateNow,\n startInactiveSpan,\n} from '@sentry/core';\nimport { flushIfServerless } from '@sentry/core/server';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { UnstorageTraceContext } from './nitroTypes';\n\nconst ORIGIN = 'auto.cache.nitro';\n\ntype GlobalWithStorageChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\nconst TRACED_OPERATIONS = [\n 'hasItem',\n 'getItem',\n 'getItemRaw',\n 'getItems',\n 'setItem',\n 'setItemRaw',\n 'setItems',\n 'removeItem',\n 'getKeys',\n 'clear',\n] as const;\n\ntype TracedOperation = (typeof TRACED_OPERATIONS)[number];\n\nconst CACHE_HIT_OPERATIONS = new Set<TracedOperation>(['hasItem', 'getItem', 'getItemRaw', 'getItems']);\n\n/**\n * Maps each unstorage operation to a convention cache op. Reads (including existence and key\n * listing) are `cache.get`, writes are `cache.put`, and deletions are `cache.remove`.\n * The precise operation stays available on `db.operation.name`.\n */\nconst OPERATION_SPAN_OPS = {\n hasItem: CACHE_GET,\n getItem: CACHE_GET,\n getItemRaw: CACHE_GET,\n getItems: CACHE_GET,\n getKeys: CACHE_GET,\n setItem: CACHE_PUT,\n setItemRaw: CACHE_PUT,\n setItems: CACHE_PUT,\n removeItem: CACHE_REMOVE,\n clear: CACHE_REMOVE,\n} as const satisfies Record<TracedOperation, string>;\n\nconst CACHED_FN_HANDLERS_RE = /^nitro:(functions|handlers):/i;\n\n/**\n * Subscribes to unstorage tracing channels and creates Sentry spans for storage operations.\n */\nexport function captureStorageEvents(): void {\n const globalWithStorageChannels = GLOBAL_OBJ as GlobalWithStorageChannels;\n if (globalWithStorageChannels.__SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n for (const operation of TRACED_OPERATIONS) {\n setupStorageTracingChannel(operation);\n }\n\n globalWithStorageChannels.__SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__ = true;\n}\n\nfunction setupStorageTracingChannel(operation: TracedOperation): void {\n const keys = (data: UnstorageTraceContext): string[] => data.keys ?? [];\n const mountBase = (data: UnstorageTraceContext): string => (data.base ?? '').replace(/:$/, '');\n\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<UnstorageTraceContext>(`unstorage.${operation}`),\n data => {\n const cacheKeys = keys(data);\n const cacheOperationName = CACHE_OPERATION_NAMES[OPERATION_SPAN_OPS[operation]];\n const client = getClient();\n\n return startInactiveSpan({\n // With span streaming, span names have to be low cardinality, so we can't fall back to the cache keys.\n name:\n client && hasSpanStreamingEnabled(client) ? OPERATION_SPAN_OPS[operation] : cacheKeys.join(', ') || operation,\n attributes: {\n [SENTRY_OP]: OPERATION_SPAN_OPS[operation],\n [CACHE_OPERATION]: cacheOperationName,\n [SENTRY_ORIGIN]: ORIGIN,\n [CACHE_KEY]: cacheKeys.length > 1 ? cacheKeys : cacheKeys[0],\n [DB_OPERATION_NAME]: operation,\n [DB_COLLECTION_NAME]: mountBase(data),\n [DB_SYSTEM_NAME]: data.driver?.name ?? 'unknown',\n },\n });\n },\n {\n beforeSpanEnd(span, data) {\n // Error status is set by the binding; the error itself is captured at the request boundary,\n // not here (cache ops aren't an error boundary). Only enrich the success path.\n if (!('error' in data)) {\n const result = (data as { result?: unknown }).result;\n if (CACHE_HIT_OPERATIONS.has(operation)) {\n span.setAttribute(CACHE_HIT, resolveCacheHit(operation, data.keys?.[0], result));\n }\n }\n\n void flushIfServerless();\n },\n },\n );\n}\n\n/**\n * Resolves the `cache.hit` value for a read operation. `hasItem` returns a boolean directly,\n * `getItems` returns a `{ key, value }[]` where a hit means at least one entry has a value,\n * and single-key reads fall back to the value-based `isCacheHit` check.\n */\nfunction resolveCacheHit(operation: TracedOperation, key: unknown, result: unknown): boolean {\n if (operation === 'hasItem') {\n return Boolean(result);\n }\n\n if (operation === 'getItems') {\n return Array.isArray(result) && result.some(item => isObjectLike(item) && item.value != null);\n }\n\n return isCacheHit(key, result);\n}\n\ninterface CacheEntry<T = unknown> {\n value?: T;\n expires?: number;\n}\n\ninterface ResponseCacheEntry {\n status?: number;\n body?: unknown;\n headers?: Record<string, string | undefined>;\n}\n\nfunction isCacheHit(key: unknown, value: unknown): boolean {\n try {\n const isEmpty = value == null;\n if (isEmpty || typeof key !== 'string' || !CACHED_FN_HANDLERS_RE.test(key)) {\n return !isEmpty;\n }\n\n const entry = typeof value === 'string' ? (JSON.parse(value) as CacheEntry) : (value as CacheEntry);\n\n return validateCacheEntry(key, entry);\n } catch {\n return false;\n }\n}\n\nfunction validateCacheEntry(\n key: string,\n entry: CacheEntry | CacheEntry<ResponseCacheEntry & { status: number }>,\n): boolean {\n if (entry.value == null) {\n return false;\n }\n\n if (safeDateNow() > (entry.expires || 0)) {\n return false;\n }\n\n if (isResponseCacheEntry(key, entry)) {\n if ((entry.value.status ?? 0) >= 400) {\n return false;\n }\n\n if (entry.value.body === undefined) {\n return false;\n }\n\n if (entry.value.headers?.etag === 'undefined' || entry.value.headers?.['last-modified'] === 'undefined') {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isResponseCacheEntry(key: string, _: CacheEntry): _ is CacheEntry<ResponseCacheEntry & { status: number }> {\n return key.startsWith('nitro:handlers:');\n}\n","import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, SERVER_PORT } from '@sentry/conventions/attributes';\nimport { HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n getRootSpan,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n type Span,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes';\n\ntype GlobalWithTraceChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Captures tracing events emitted by Nitro tracing channels.\n */\nexport function captureTracingEvents(): void {\n // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized.\n const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels;\n if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n setupH3TracingChannels();\n setupSrvxTracingChannels();\n globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;\n}\n\n/**\n * Extracts the HTTP status code from a tracing channel result.\n * The result is the return value of the traced handler, which is a Response for srvx\n * and may or may not be a Response for h3.\n */\nfunction getResponseStatusCode(result: unknown): number | undefined {\n if (isObjectLike(result) && 'status' in result && typeof result.status === 'number') {\n return result.status;\n }\n return undefined;\n}\n\n/** Applies the HTTP status from the traced handler's result to the span, when present. */\nfunction applyResponseStatus(span: Span, data: TracingChannelPayloadWithSpan<{ result?: unknown }>): void {\n const statusCode = getResponseStatusCode(data.result);\n if (statusCode !== undefined) {\n setHttpStatus(span, statusCode);\n }\n}\n\n/**\n * Whether the request already has an `http.server` root span, created by the runtime's own HTTP\n * server instrumentation (Node `http`, `Bun.serve`, `Deno.serve`, Cloudflare's request wrapper).\n */\nfunction hasHttpServerRootSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && spanToJSON(getRootSpan(activeSpan)).attributes[SENTRY_OP] === HTTP_SERVER;\n}\n\n/**\n * The port the srvx server listens on. `options.port` is only the configured one, which is `0` for a\n * random port.\n */\nfunction getServerPort(server: SrvxRequestEvent['server']): number | undefined {\n const url = server.url ? parseStringToURLObject(server.url) : undefined;\n const port = url && 'port' in url ? Number(url.port) : undefined;\n return port || server.options.port || undefined;\n}\n\n/**\n * Extracts the parameterized route pattern from the h3 event context.\n */\nfunction getParameterizedRoute(event: NitroH3Event): string | undefined {\n const matchedRoute = event.context?.matchedRoute;\n if (!matchedRoute) {\n return undefined;\n }\n\n const routePath = matchedRoute.route;\n\n // Skip catch-all routes as they're not useful for transaction grouping\n if (!routePath || routePath === '/**') {\n return undefined;\n }\n\n return routePath;\n}\n\nfunction setupH3TracingChannels(): void {\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request'),\n data => {\n const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n // The route lives on the request's `http.server` root span, so the route handler only gets a\n // span that times the handler itself instead of yet another nested `http.server` span.\n if (data.type === 'route' && hasHttpServerRootSpan()) {\n const matchedRoute = data.event.context?.matchedRoute?.route;\n const span = startInactiveSpan({\n name: matchedRoute ? `${method} ${matchedRoute}` : method,\n attributes: {\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: HANDLER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n }\n\n const parsedUrl = parseStringToURLObject(data.event.url.href);\n const routePattern = getParameterizedRoute(data.event);\n\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.h3',\n { method: data.event.req.method },\n routePattern,\n );\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n const isUnparameterizedStreamedServerSpan =\n data.type !== 'middleware' &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n const span = startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan ? method : spanName,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: data.type === 'middleware' ? MIDDLEWARE : HTTP_SERVER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Update the root span with the parameterized route name. The root span is created before h3\n // resolves the route, so it initially has the raw URL.\n // Note: data.type is always 'middleware' here regardless of handler type, so we rely on\n // getParameterizedRoute() to filter out catch-all routes instead.\n const routePattern = getParameterizedRoute(data.event);\n if (routePattern) {\n setHttpServerSpanRouteAttribute(routePattern);\n }\n },\n },\n );\n}\n\nfunction setupSrvxTracingChannels(): void {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Store the parent span per-request so middleware and fetch share the same parent.\n // WeakMap ensures per-request isolation in concurrent environments and automatic cleanup.\n const requestParentSpans = new WeakMap<SrvxRequestEvent['request'], Span>();\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.request'),\n data => {\n // srvx only opens the request's `http.server` span when the runtime has not already created one.\n if (hasHttpServerRootSpan()) {\n return undefined;\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const client = getClient();\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.srvx',\n { method: data.request.method },\n undefined,\n client,\n );\n\n const headerAttributes = client\n ? httpHeadersToSpanAttributes(\n Object.fromEntries(data.request.headers.entries()),\n client.getDataCollectionOptions(),\n )\n : {};\n\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n // h3 renames this span via `setHttpServerSpanRouteAttribute` once it resolves the route.\n const isUnparameterizedStreamedServerSpan =\n !data.middleware &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n return startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan\n ? data.request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK\n : spanName,\n attributes: {\n ...urlAttributes,\n ...headerAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: data.middleware ? MIDDLEWARE : HTTP_SERVER,\n [SERVER_PORT]: getServerPort(data.server),\n },\n // Use the same parent span as middleware to make them siblings\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Clean up parent span reference after the fetch handler completes (success or error).\n requestParentSpans.delete(data.request);\n },\n },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.middleware'),\n data => {\n // For the first middleware, capture the current parent span per-request\n if (data.middleware?.index === 0) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n requestParentSpans.set(data.request, activeSpan);\n }\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const [, urlAttributes] = getHttpSpanDetailsFromUrlObject(parsedUrl, 'server', 'auto.http.nitro.srvx', {\n method: data.request.method,\n });\n\n // Create span as a child of the original parent, not the previous middleware\n return startInactiveSpan({\n name: `${data.middleware?.handler.name ?? 'unknown'} - ${data.request.method} ${data.request._url?.pathname}`,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: MIDDLEWARE,\n },\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n },\n },\n );\n}\n\n/**\n * Sets the parameterized route attributes on the span.\n */\nfunction setParameterizedRouteAttributes(span: Span, event: NitroH3Event): void {\n const matchedRoutePath = getParameterizedRoute(event);\n if (!matchedRoutePath) {\n return;\n }\n\n setHttpServerSpanRouteAttribute(matchedRoutePath);\n\n const rootSpan = getRootSpan(span);\n if (!rootSpan) {\n return;\n }\n\n const params = event.context?.params;\n\n if (isObjectLike(params)) {\n Object.entries(params).forEach(([key, value]) => {\n // Based on this convention: https://conventions.sentry.dev/attributes/url/#url-path-parameter-key\n rootSpan.setAttributes({\n [`url.path.parameter.${key}`]: String(value),\n [`params.${key}`]: String(value),\n });\n });\n }\n}\n","import { getTraceData, GLOBAL_OBJ } from '@sentry/core';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { H3TracingRequestEvent, NitroH3Event } from './nitroTypes';\n\ntype GlobalWithServerTiming = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Subscribes to the h3 request tracing channel to set Server-Timing trace headers on every response.\n *\n * This is deliberately independent of span sampling: `getTraceData()` returns valid trace\n * propagation data even in tracing-without-performance mode, and the browser SDK reads these headers\n * (via the Performance API) to connect a pageload to the backend trace regardless of whether the\n * server records spans.\n */\nexport function captureServerTimingHeaders(): void {\n const globalWithServerTiming = GLOBAL_OBJ as GlobalWithServerTiming;\n if (globalWithServerTiming.__SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__) {\n return;\n }\n\n // Bail if this is not available (e.g. Node without tracing channel support)\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request').start.subscribe(message => {\n setServerTimingHeaders((message as H3TracingRequestEvent).event);\n });\n\n globalWithServerTiming.__SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__ = true;\n}\n\n/**\n * Sets Server-Timing response headers for trace propagation to the client.\n * The browser SDK reads these via the Performance API to connect pageload traces.\n */\nfunction setServerTimingHeaders(event: NitroH3Event): void {\n if (event.context?._sentryServerTimingSet) {\n return;\n }\n\n const headers = event.res?.headers;\n if (!headers) {\n return;\n }\n\n const traceData = getTraceData();\n if (traceData['sentry-trace']) {\n headers.append('Server-Timing', `sentry-trace;desc=\"${traceData['sentry-trace']}\"`);\n }\n if (traceData.baggage) {\n headers.append('Server-Timing', `baggage;desc=\"${traceData.baggage}\"`);\n }\n\n if (event.context) {\n event.context._sentryServerTimingSet = true;\n }\n}\n","import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { captureStorageEvents } from './captureStorageEvents';\nimport { captureTracingEvents } from './captureTracingEvents';\nimport { captureServerTimingHeaders } from './setServerTimingHeaders';\n\nconst INTEGRATION_NAME = 'Nitro' as const;\n\nexport interface NitroIntegrationOptions {\n /**\n * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser\n * SDK can connect a pageload trace to the backend trace.\n *\n * @default true\n */\n serverTiming?: boolean;\n\n /**\n * Create cache spans for unstorage operations.\n *\n * @default true\n */\n storage?: boolean;\n}\n\nconst _nitroIntegration = ((options: NitroIntegrationOptions = {}) => {\n const { serverTiming = true, storage = true } = options;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n captureTracingEvents();\n\n if (storage) {\n captureStorageEvents();\n }\n\n if (serverTiming) {\n captureServerTimingHeaders();\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Instruments a Nitro server via its `node:diagnostics_channel` tracing channels: HTTP server and\n * middleware spans (h3/srvx), cache spans (unstorage) and `Server-Timing` trace-propagation headers.\n * It subscribes to those channels, so it is inert unless a Nitro app (or a framework that enables the\n * same tracing channels) is running.\n *\n * Registered regardless of whether tracing is enabled, because trace propagation must work in\n * tracing-without-performance mode too; without tracing, the spans it starts are non-recording.\n * Error capture is handled by the `@sentry/nitro` runtime plugin's Nitro `error` hook.\n */\nexport const nitroIntegration = defineIntegration(_nitroIntegration);\n","import { amqplibIntegration } from './amqplib';\nimport { dataloaderIntegration } from './dataloader';\nimport { knexIntegration } from './knex';\nimport { mongoIntegration } from './mongodb';\nimport { graphqlIntegration } from './graphql';\nimport { redisIntegration } from './redis';\nimport { mysqlIntegration } from './mysql';\nimport { mysql2Integration } from './mysql2';\nimport { postgresIntegration } from './pg';\nimport { prismaIntegration } from './prisma';\nimport { tediousIntegration } from './tedious';\nimport { genericPoolIntegration } from './generic-pool';\nimport { kafkaIntegration } from './kafkajs';\nimport { mongooseIntegration } from './mongoose';\nimport { lruMemoizerIntegration } from './lru-memoizer';\nimport { langChainIntegration } from './langchain';\nimport { langGraphIntegration } from './langgraph';\nimport { piAiIntegration } from './pi-ai';\nimport { piDurableIntegration } from './pi-durable';\nimport { mastraIntegration } from './mastra';\nimport { mcpServerIntegration } from './mcp-server';\nimport { vercelAIIntegration } from './vercel-ai';\nimport { openAIIntegration } from './openai';\nimport { anthropicAIIntegration } from './anthropic';\nimport { googleGenAIIntegration } from './google-genai';\nimport { mistralAIIntegration } from './mistral';\nimport { groqIntegration } from './groq';\nimport { togetherAIIntegration } from './together-ai';\nimport { typesafeIntegration } from './typesafe';\nimport { postgresJsIntegration } from './postgresjs';\nimport { neonIntegration } from './neon';\nimport { firebaseIntegration } from './firebase';\nimport { expressIntegration } from './express';\nimport { fastifyIntegration } from './fastify';\nimport { nitroIntegration } from './nitro';\nimport { hapiIntegration } from './hapi';\nimport { honoIntegration } from './hono';\nimport { koaIntegration } from './koa';\nimport type { Integration } from '@sentry/core';\nimport { awsIntegration } from './aws-sdk';\n\n/** These are integrations that are tracing-only integrations. */\nexport function getTracingIntegrations(): Integration[] {\n return [\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n prismaIntegration(),\n tediousIntegration(),\n knexIntegration(),\n genericPoolIntegration(),\n kafkaIntegration(),\n amqplibIntegration(),\n lruMemoizerIntegration(),\n dataloaderIntegration(),\n awsIntegration(),\n // AI providers\n // LangChain must come first to disable AI provider integrations before they instrument\n langChainIntegration(),\n langGraphIntegration(),\n mastraIntegration(),\n piAiIntegration(),\n piDurableIntegration(),\n vercelAIIntegration(),\n openAIIntegration(),\n anthropicAIIntegration(),\n googleGenAIIntegration(),\n mistralAIIntegration(),\n groqIntegration(),\n togetherAIIntegration(),\n typesafeIntegration(),\n postgresJsIntegration(),\n neonIntegration(),\n firebaseIntegration(),\n mcpServerIntegration(),\n ];\n}\n\n/**\n * These are default integrations that are registered regardless of whether tracing is enabled -\n * either because they cover error capture in addition to tracing, or because they handle trace\n * propagation (which must work in tracing-without-performance mode too).\n */\nexport function getErrorIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n hapiIntegration(),\n honoIntegration(),\n koaIntegration(),\n nitroIntegration(),\n ];\n}\n","export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport {\n isReadAlikeByNodeCron3 as _INTERNAL_isReadAlikeByNodeCron3,\n nodeCronIntegration,\n} from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport type { CronDialect as _INTERNAL_CronDialect } from './utils/cronMonitoring';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,MAAM,yBAAyB;;;;;;;AAQ/B,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;AA6BhC,SAAgB,sBAAsB,KAAmB;CACvD,MAAM,YAAY;CAClB,IAAI,CAAC,aAAa,OAAO,UAAU,OAAO,cAAc,UAAU,yBAChE;CAEFA,CAAAA,GAAAA,aAAAA,yBAAAA,CAAyB,WAAW,wBAAwB,IAAI;CAEhE,UAAU,GAAG,UAAU,OAAgB,YAAsB;EAC3D,MAAM,OAAQ,UAAwD;EACtE,MAAM,gBAAsB;GAC1BC,CAAAA,GAAAA,aAAAA,iBAAAA,CAAiB,OAAO,EACtB,WAAW;IACT,MAAM;IACN,SAAS;GACX,EACF,CAAC;EACH;EAEA,IAAI,MACFC,CAAAA,GAAAA,aAAAA,eAAAA,CAAe,MAAM,OAAO;OAE5B,QAAQ;CAEZ,CAAC;AACH;;ACzDA,MAAM,u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