@sentry/server-utils 11.21.0 → 11.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/build/cjs/chunks/config.js +2 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +4 -1
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/index.js +53 -16
  6. package/build/cjs/index.js.map +1 -1
  7. package/build/esm/ai/workers-ai/utils.js +4 -1
  8. package/build/esm/ai/workers-ai/utils.js.map +1 -1
  9. package/build/esm/integrations/fastify/instrumentation.js +5 -1
  10. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  11. package/build/esm/integrations/neon.js +10 -2
  12. package/build/esm/integrations/neon.js.map +1 -1
  13. package/build/esm/integrations/pg.js +41 -14
  14. package/build/esm/integrations/pg.js.map +1 -1
  15. package/build/esm/integrations/pino.js.map +1 -1
  16. package/build/esm/integrations/vercel-ai/extract.js +2 -3
  17. package/build/esm/integrations/vercel-ai/extract.js.map +1 -1
  18. package/build/esm/orchestrion/config/prisma.js +2 -0
  19. package/build/esm/orchestrion/config/prisma.js.map +1 -1
  20. package/build/esm/package.json +1 -1
  21. package/build/esm/tracing-channel.js.map +1 -1
  22. package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
  23. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  24. package/build/types/integrations/neon.d.ts.map +1 -1
  25. package/build/types/integrations/pg.d.ts +6 -1
  26. package/build/types/integrations/pg.d.ts.map +1 -1
  27. package/build/types/integrations/pino.d.ts.map +1 -1
  28. package/build/types/integrations/vercel-ai/extract.d.ts +2 -5
  29. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -1
  30. package/build/types/orchestrion/channels.d.ts +1 -0
  31. package/build/types/orchestrion/channels.d.ts.map +1 -1
  32. package/build/types/orchestrion/config/prisma.d.ts +2 -1
  33. package/build/types/orchestrion/config/prisma.d.ts.map +1 -1
  34. package/build/types/tracing-channel.d.ts.map +1 -1
  35. package/package.json +4 -4
@@ -69,7 +69,10 @@ function addRequestAttributes(span, inputs, operationName) {
69
69
  }
70
70
  if (operationName === "extract") {
71
71
  const { model: _model, ...request } = inputs;
72
- if (Array.isArray(request.images)) request.images = request.images.map(() => BLOB_SUBSTITUTE);
72
+ for (const key of ["images", "documents"]) {
73
+ const blobs = request[key];
74
+ if (Array.isArray(blobs)) request[key] = blobs.map(() => BLOB_SUBSTITUTE);
75
+ }
73
76
  span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));
74
77
  return;
75
78
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n if (Array.isArray(request.images)) {\n request.images = request.images.map(() => BLOB_SUBSTITUTE);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n"],"mappings":";;;;;;;;AAwCA,MAAa,gCAAwE;CACnF,MAAM;CACN,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;;;;AAKA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AAK,aAAa,uBAAuB,KAAK;CAGhD,IAAI,aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
1
+ {"version":3,"file":"utils.js","names":["addDecideResponseAttributes"],"sources":["../../../../src/ai/workers-ai/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_CHAT, GEN_AI_EMBEDDINGS, GEN_AI_DECIDE, GEN_AI_EXTRACT } from '@sentry/conventions/op';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport {\n extractSystemInstructions,\n getEvaluationInputMessages,\n getTokenUsageAttributes,\n setOutputMessagesAttribute,\n} from '../core/utils';\nimport { addResponseAttributes as addDecideResponseAttributes } from '../typesafe';\n// Re-exported so `workers-ai/streaming.ts` keeps importing it from this module.\nexport { setOutputMessagesAttribute };\nimport { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants';\nimport type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types';\n\nexport type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract';\n\nexport const WORKERS_AI_OPERATION_SPAN_OPS: Record<WorkersAiOperationName, string> = {\n chat: GEN_AI_CHAT,\n embeddings: GEN_AI_EMBEDDINGS,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n};\n\n/**\n * Model ID prefixes of the evaluation models (TypeSafe Jev and Cloudflare Clef), traced as `decide` spans.\n */\nconst DECIDE_MODEL_PREFIXES = ['typesafe/jev', '@cf/cloudflare/clef'];\n\n/**\n * Model ID prefixes of the field extraction models (Cloudflare Clairic), traced as `extract` spans.\n */\nconst EXTRACT_MODEL_PREFIXES = ['@cf/cloudflare/clairic'];\n\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\n/**\n * Determine the gen_ai operation name from the model and inputs passed to `AI.run`.\n * Workers AI exposes a single `run` method, so we infer the operation from the model ID and the input shape.\n */\nexport function getOperationName(model: unknown, inputs: unknown): WorkersAiOperationName {\n if (typeof model === 'string' && DECIDE_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'decide';\n }\n if (typeof model === 'string' && EXTRACT_MODEL_PREFIXES.some(prefix => model.startsWith(prefix))) {\n return 'extract';\n }\n if (inputs && typeof inputs === 'object') {\n if ('messages' in inputs || 'prompt' in inputs) {\n return 'chat';\n }\n if ('text' in inputs) {\n return 'embeddings';\n }\n }\n return 'chat';\n}\n\n/**\n * Extract the request attributes (model, request parameters, system, origin) from a `run` call.\n */\nexport function extractRequestAttributes(\n model: unknown,\n inputs: unknown,\n operationName: string,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: WORKERS_AI_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: WORKERS_AI_ORIGIN,\n [GEN_AI_REQUEST_MODEL]: typeof model === 'string' ? model : 'unknown',\n };\n\n if (inputs && typeof inputs === 'object') {\n const params = inputs as WorkersAiInput;\n\n if (typeof params.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n }\n if (typeof params.max_tokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n if (typeof params.top_p === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n }\n if (typeof params.top_k === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n }\n if (typeof params.frequency_penalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n }\n if (typeof params.presence_penalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presence_penalty;\n }\n if (params.stream === true) {\n attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = true;\n }\n }\n\n return attributes;\n}\n\n/**\n * Record the request inputs (messages/prompt/embeddings input) on the span.\n * Only called when `recordInputs` is enabled.\n */\nexport function addRequestAttributes(span: Span, inputs: unknown, operationName: string): void {\n if (!inputs || typeof inputs !== 'object') {\n return;\n }\n const params = inputs as WorkersAiInput;\n\n if (operationName === 'decide') {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(inputs as Record<string, unknown>));\n return;\n }\n\n if (operationName === 'extract') {\n // Record the request body as passed, but never the image or document data.\n const { model: _model, ...request } = inputs as Record<string, unknown>;\n for (const key of ['images', 'documents']) {\n const blobs = request[key];\n if (Array.isArray(blobs)) {\n request[key] = blobs.map(() => BLOB_SUBSTITUTE);\n }\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify([request]));\n return;\n }\n\n // Store embeddings input on a separate attribute\n if (operationName === 'embeddings') {\n const text = params.text;\n\n if (text == null || (typeof text === 'string' && text.length === 0) || (Array.isArray(text) && text.length === 0)) {\n return;\n }\n\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(text, String));\n return;\n }\n\n const src = params.messages ?? params.prompt;\n\n if (src == null || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Record the response attributes (token usage, response text, tool calls) on the span.\n */\nexport function addResponseAttributes(\n span: Span,\n result: unknown,\n recordOutputs: boolean,\n operationName?: WorkersAiOperationName,\n): void {\n if (operationName === 'decide') {\n // The binding wraps the TypeSafe response as `{ state, result }`, but the docs show it unwrapped.\n const body = isObjectLike(result) && isObjectLike(result.result) ? result.result : result;\n addDecideResponseAttributes(span, body, recordOutputs);\n return;\n }\n\n if (operationName === 'extract') {\n addExtractResponseAttributes(span, result, recordOutputs);\n return;\n }\n\n if (\n !result ||\n typeof result !== 'object' ||\n // Raw `Response` objects (from `returnRawResponse`/`websocket`) cannot be introspected without consuming them.\n (typeof Response !== 'undefined' && result instanceof Response)\n ) {\n return;\n }\n\n const response = result as WorkersAiOutput;\n\n if (response.usage) {\n span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));\n }\n\n if (Array.isArray(response.choices)) {\n if (typeof response.id === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_ID, response.id);\n }\n if (typeof response.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model);\n }\n addChoicesResponseAttributes(span, response.choices, recordOutputs);\n return;\n }\n\n if (recordOutputs) {\n let responseText: string | undefined;\n if (typeof response.response === 'string') {\n responseText = response.response;\n span.setAttribute(GEN_AI_RESPONSE_TEXT, response.response);\n } else if (response.response != null) {\n responseText = JSON.stringify(response.response);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, responseText);\n }\n\n const toolCalls =\n Array.isArray(response.tool_calls) && response.tool_calls.length > 0 ? response.tool_calls : undefined;\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n setOutputMessagesAttribute(span, { responseText, toolCalls });\n }\n}\n\nfunction addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void {\n const finishReasons = choices\n .map(choice => choice.finish_reason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons));\n }\n\n if (!recordOutputs) {\n return;\n }\n\n const messages = choices.map(({ message, finish_reason }) => ({\n responseText: typeof message?.content === 'string' ? message.content : undefined,\n toolCalls: message?.tool_calls,\n finishReason: typeof finish_reason === 'string' ? finish_reason : undefined,\n }));\n\n setOutputMessagesAttribute(span, messages);\n}\n\nfunction addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(body)) {\n return;\n }\n\n const { model, usage, ...response } = body;\n\n if (typeof model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, model);\n }\n\n if (isObjectLike(usage)) {\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.input_tokens === 'number' ? usage.input_tokens : undefined,\n typeof usage.output_tokens === 'number' ? usage.output_tokens : undefined,\n ),\n );\n }\n\n if (recordOutputs) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([response]));\n }\n}\n"],"mappings":";;;;;;;;AAwCA,MAAa,gCAAwE;CACnF,MAAM;CACN,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;;;;AAKA,MAAM,wBAAwB,CAAC,gBAAgB,qBAAqB;;;;AAKpE,MAAM,yBAAyB,CAAC,wBAAwB;AAExD,MAAM,kBAAkB;;;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aAAa,KAAK,GACpB,KAAK,cACH,wBACE,OAAO,MAAM,iBAAiB,WAAW,MAAM,eAAe,KAAA,GAC9D,OAAO,MAAM,kBAAkB,WAAW,MAAM,gBAAgB,KAAA,CAClE,CACF;CAGF,IAAI,eACF,KAAK,aAAa,wBAAwB,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEnE"}
@@ -97,6 +97,10 @@ function onRequest(request, _reply, hookDone) {
97
97
  const routeName = getRequestRouteUrl(request);
98
98
  const method = request.method || "GET";
99
99
  getIsolationScope().setTransactionName(`${method} ${routeName}`);
100
+ if (!getActiveSpan()) {
101
+ hookDone();
102
+ return;
103
+ }
100
104
  const attributes = {
101
105
  [SENTRY_ORIGIN]: ORIGIN,
102
106
  [SENTRY_OP]: HANDLER,
@@ -195,7 +199,7 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
195
199
  if (!request) return handler.call(this, ...args);
196
200
  const parentSpan = request[kRequestSpan] ?? void 0;
197
201
  const effectiveParentSpan = parentSpan ?? getActiveSpan();
198
- if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
202
+ if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
199
203
  const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
200
204
  const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
201
205
  const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\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 getActiveSpan,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n spanIsSampled,\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\n // A child of an unsampled span is never sampled either, so skip creating it. Hooks that run after\n // the request span ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would.\n const effectiveParentSpan = parentSpan ?? getActiveSpan();\n if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) {\n return handler.call(this, ...args);\n }\n\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"],"mappings":";;;;;;;AA4CA,MAAM,SAAS;AAEf,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,+BAA+B;AAErC,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAEhC,MAAM,eAAe,OAAO,6BAA6B;AACzD,MAAM,mBAAmB,OAAO,iCAAiC;AACjE,MAAM,uBAAuB,OAAO,4CAA4C;;;;;AAQhF,SAAS,mBAAmB,SAAkC;CAC5D,OAAO,QAAQ,cAAc,OAAO,QAAQ;AAC9C;;;;;;AAOA,SAAS,iBAAiB,KAAmB;CAC3C,OAAO,aAAa,GAAG,KAAK,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC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EA,IAAI,kBAAkB;;;;;AAMtB,SAAgB,oBAA0B;CACxC,IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
1
+ {"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\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 getActiveSpan,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n spanIsSampled,\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 // No active parent span means this request is being ignored (e.g. via `ignoreIncomingRequests`),\n // so don't open a span that would become the root of a new trace.\n if (!getActiveSpan()) {\n hookDone();\n return;\n }\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\n // Without a parent span the request is being ignored, and a child of an unsampled span is never\n // sampled either, so skip creating the span in both cases. Hooks that run after the request span\n // ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would.\n const effectiveParentSpan = parentSpan ?? getActiveSpan();\n if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) {\n return handler.call(this, ...args);\n }\n\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 instrumentFastifyInst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AK7D,MAAM,sBAAsB,cAAc,cAAc;EACxD,IAAI,CAAC,uBAAuB,CAAC,cAAc,mBAAmB,GAC5D,OAAO,QAAQ,KAAK,MAAM,GAAG,IAAI;EAGnC,MAAM,cAAc,QAAQ,MAAM,SAAS,IAAI,QAAQ,OAAQ,KAAK,cAAc;EAElF,MAAM,WAAW,eAAe;EAChC,MAAM,KAAK,aAAa,qBAAqB,aAAa,aAAa,oBAAoB,UAAU,KAAA;EAErG,MAAM,SAAS,UAAU;EAGzB,MAAM,+BAA+B,aAAa,qBAAqB,CAAC,CAAC,UAAU,wBAAwB,MAAM;EAEjH,MAAM,oBAAoB,eAAe;EAEzC,MAAM,OAAO,+BACT,eAAe,eAAe,qCAC9B,MAAM,OAAO,sBAAsB,WACjC,oBACA,GAAG,SAAS,KAAK;EAEvB,OAAO,UACL;GACE;GACA,YAAY;IACV,GAAG;KACF,YAAY;KACZ,gBAAgB;GACnB;GACA;EACF,SACM,QAAQ,KAAK,MAAM,GAAG,IAAI,CAClC;CACF;AACF;AAEA,IAAI,kBAAkB;;;;;AAMtB,SAAgB,oBAA0B;CACxC,IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
@@ -4,7 +4,7 @@ import { CHANNELS } from "../orchestrion/channels.js";
4
4
  import { neonModuleNames } from "../orchestrion/config/neon.js";
5
5
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
6
6
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
7
- import { bindPgQueryChannel, getConnectionAttributes } from "./pg.js";
7
+ import { bindPgQueryChannel, getConnectionAttributes, setReturnedRows } from "./pg.js";
8
8
  import { DB_OPERATION_BATCH_SIZE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_QUERY_TEXT, DB_SYSTEM_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
9
9
  import { defineIntegration, getActiveSpan, startInactiveSpan } from "@sentry/core";
10
10
  import { DB } from "@sentry/conventions/op";
@@ -29,7 +29,12 @@ function instrumentNeon() {
29
29
  const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));
30
30
  httpQuerySpans.add(span);
31
31
  return span;
32
- });
32
+ }, { beforeSpanEnd(span, data) {
33
+ if ("error" in data) return;
34
+ const { result } = data;
35
+ const isBatch = Array.isArray(data.arguments[0]);
36
+ setReturnedRows(span, isBatch && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));
37
+ } });
33
38
  tracingChannel(CHANNELS.NEON_RESOLVE_CONNECTION).subscribe({
34
39
  start: NOOP,
35
40
  end: NOOP,
@@ -71,6 +76,9 @@ function httpQuerySpanOptions(args) {
71
76
  attributes
72
77
  };
73
78
  }
79
+ function toPgResult(result) {
80
+ return Array.isArray(result) ? { rows: result } : result;
81
+ }
74
82
  function getBatchOperationName(statements) {
75
83
  const operations = new Set(statements.map((s) => s[DB_OPERATION_NAME]?.toUpperCase()));
76
84
  const [operation] = operations;
@@ -1 +1 @@
1
- {"version":3,"file":"neon.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/neon.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;AAqBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,eAAe;AACrB,MAAM,aAAmB,CAAC;AAsB1B,MAAM,iCAAiB,IAAI,QAAc;AAEzC,MAAM,0BAA0B;CAC9B,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,CAAC;EAC9E;CACF;AACF;AAEA,SAAS,iBAAuB;CAG9B,mBAAmB,SAAS,YAAY,EAAE,QAAQ,OAAO,CAAC;CAE1D,yBAAyBA,eAAwD,SAAS,eAAe,IAAG,SAAQ;EAClH,MAAM,OAAO,kBAAkB,qBAAqB,KAAK,SAAS,CAAC;EACnE,eAAe,IAAI,IAAI;EACvB,OAAO;CACT,CAAC;CAIDA,eAAgE,SAAS,uBAAuB,CAAC,CAAC,UAAU;EAC1G,OAAO;EACP,KAAK;EACL,YAAY;EACZ,OAAO;EACP,SAAS,MAAM;GACb,MAAM,OAAO,cAAc;GAC3B,MAAM,MAAM,KAAK,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B,CAAC,CAAC,IAAI;CAC7D,OAAO,QAAQ,SAAS,QAAQ,KAAK,IAAI,IAAI,KAAA;AAC/C;AAEA,SAAS,aAAa,MAAqD;CACzE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B;CAEF,IAAI,WAAW,QAAQ,OAAO,KAAK,UAAU,UAC3C,OAAO,KAAK;CAEd,IAAI,EAAE,aAAa,SAAS,CAAC,MAAM,QAAQ,KAAK,OAAO,GACrD;CAEF,IAAI,OAAO,KAAK,yBAAyB,YACvC,IAAI;EAEF,OAAO,KAAK,qBAAqB,CAAC,CAAC;CACrC,QAAQ,CAER;CAEF,OAAO,KAAK,QAAQ,QAAQ,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,IAAI,MAAM;AACrE;;;;;;;;;AAUA,MAAa,kBAAkB,kBAAkB,gBAAgB"}
1
+ {"version":3,"file":"neon.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/neon.ts"],"sourcesContent":["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, setReturnedRows } 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 // Per statement: the rows array, or `{ rowCount, rows, ... }` with `fullResults`. A batch resolves to an array of these.\n result?: 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(\n diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY),\n data => {\n const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));\n httpQuerySpans.add(span);\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n if ('error' in data) {\n return;\n }\n const { result } = data;\n const isBatch = Array.isArray(data.arguments[0]);\n setReturnedRows(span, isBatch && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));\n },\n },\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\nfunction toPgResult(result: unknown): unknown {\n return Array.isArray(result) ? { rows: result } : result;\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"],"mappings":";;;;;;;;;;;AAqBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,eAAe;AACrB,MAAM,aAAmB,CAAC;AAwB1B,MAAM,iCAAiB,IAAI,QAAc;AAEzC,MAAM,0BAA0B;CAC9B,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,CAAC;EAC9E;CACF;AACF;AAEA,SAAS,iBAAuB;CAG9B,mBAAmB,SAAS,YAAY,EAAE,QAAQ,OAAO,CAAC;CAE1D,yBACEA,eAAwD,SAAS,eAAe,IAChF,SAAQ;EACN,MAAM,OAAO,kBAAkB,qBAAqB,KAAK,SAAS,CAAC;EACnE,eAAe,IAAI,IAAI;EACvB,OAAO;CACT,GACA,EACE,cAAc,MAAM,MAAM;EACxB,IAAI,WAAW,M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BAA0B;CAC7B;CAEA,OAAO;EAAE,MAAM,6BAA6B,YAAY,oBAAoB;EAAG,cAAc;EAAM;CAAW;AAChH;AAEA,SAAS,WAAW,QAA0B;CAC5C,OAAO,MAAM,QAAQ,MAAM,IAAI,EAAE,MAAM,OAAO,IAAI;AACpD;AAGA,SAAS,sBAAsB,YAAgE;CAC7F,MAAM,aAAa,IAAI,IAAI,WAAW,KAAI,MAAK,EAAE,kBAAkB,EAAE,YAAY,CAAC,CAAC;CACnF,MAAM,CAAC,aAAa;CACpB,OAAO,WAAW,SAAS,KAAK,YAAY,SAAS,cAAc;AACrE;AAEA,SAAS,YAAY,OAAmD;CACtE,MAAM,UAAU,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI;CAC7D,OAAO,QAAQ,SAAS,QAAQ,KAAK,IAAI,IAAI,KAAA;AAC/C;AAEA,SAAS,aAAa,MAAqD;CACzE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B;CAEF,IAAI,WAAW,QAAQ,OAAO,KAAK,UAAU,UAC3C,OAAO,KAAK;CAEd,IAAI,EAAE,aAAa,SAAS,CAAC,MAAM,QAAQ,KAAK,OAAO,GACrD;CAEF,IAAI,OAAO,KAAK,yBAAyB,YACvC,IAAI;EAEF,OAAO,KAAK,qBAAqB,CAAC,CAAC;CACrC,QAAQ,CAER;CAEF,OAAO,KAAK,QAAQ,QAAQ,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,IAAI,MAAM;AACrE;;;;;;;;;AAUA,MAAa,kBAAkB,kBAAkB,gBAAgB"}
@@ -4,7 +4,7 @@ import { CHANNELS } from "../orchestrion/channels.js";
4
4
  import { bindTracingChannelToSpan } from "../tracing-channel.js";
5
5
  import { pgModuleNames } from "../orchestrion/config/pg.js";
6
6
  import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
7
- import { DB_CONNECTION_STRING, DB_NAMESPACE, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
7
+ import { DB_CONNECTION_STRING, DB_NAMESPACE, DB_RESPONSE_RETURNED_ROWS, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
8
8
  import { bindScopeToEmitter, defineIntegration, getCurrentScope, isObjectLike, startInactiveSpan } from "@sentry/core";
9
9
  import { DB } from "@sentry/conventions/op";
10
10
  // src/integrations/pg.ts
@@ -41,15 +41,16 @@ function instrumentPostgres(options) {
41
41
  * streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.
42
42
  */
43
43
  function bindPgQueryChannel(channelName, options) {
44
- subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), { deferStreamedResult: true });
44
+ subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), { isQuery: true });
45
45
  }
46
46
  /**
47
47
  * Subscribe to a pg tracing-channel and manage a span across its lifecycle.
48
48
  * Shared by the query/connect/pool-connect channels. They differ only in how
49
49
  * the span's name + attributes are built (`getSpanOptions`), and whether the
50
- * result can be a streamable emitter (`deferStreamedResult`, query-only).
50
+ * result is a query result that can be a streamable emitter and carries a row
51
+ * count (`isQuery`).
51
52
  */
52
- function subscribeQueryLikeChannel(channelName, getSpanOptions, { deferStreamedResult = false } = {}) {
53
+ function subscribeQueryLikeChannel(channelName, getSpanOptions, { isQuery = false } = {}) {
53
54
  bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
54
55
  data._sentryCallerScope = getCurrentScope();
55
56
  const spanOptions = getSpanOptions(data);
@@ -61,15 +62,24 @@ function subscribeQueryLikeChannel(channelName, getSpanOptions, { deferStreamedR
61
62
  [SENTRY_KIND]: "client"
62
63
  }
63
64
  });
64
- }, deferStreamedResult ? { deferSpanEnd({ data, end }) {
65
- const result = data.result;
66
- if (!result || typeof result !== "object" || !hasOnMethod(result)) return false;
67
- const callerScope = data._sentryCallerScope;
68
- if (callerScope) bindScopeToEmitter(result, callerScope);
69
- result.on("error", (err) => end(err));
70
- result.on("end", () => end());
71
- return true;
72
- } } : void 0);
65
+ }, isQuery ? {
66
+ beforeSpanEnd(span, data) {
67
+ if ("error" in data || isObjectLike(data.result) && hasOnMethod(data.result)) return;
68
+ setReturnedRows(span, data.result);
69
+ },
70
+ deferSpanEnd({ span, data, end }) {
71
+ const result = data.result;
72
+ if (!result || typeof result !== "object" || !hasOnMethod(result)) return false;
73
+ const callerScope = data._sentryCallerScope;
74
+ if (callerScope) bindScopeToEmitter(result, callerScope);
75
+ result.on("error", (err) => end(err));
76
+ result.on("end", (endResult) => {
77
+ if (!hasReadMethod(result)) setReturnedRows(span, endResult);
78
+ end();
79
+ });
80
+ return true;
81
+ }
82
+ } : void 0);
73
83
  }
74
84
  function querySpanOptions(ctx, { origin, connectionString }) {
75
85
  const params = ctx.self?.connectionParameters ?? {};
@@ -109,6 +119,23 @@ function poolConnectSpanOptions(ctx) {
109
119
  function hasOnMethod(obj) {
110
120
  return "on" in obj && typeof obj.on === "function";
111
121
  }
122
+ function hasReadMethod(obj) {
123
+ return "read" in obj && typeof obj.read === "function";
124
+ }
125
+ /**
126
+ * Sets `db.response.returned_rows` from a pg-style result (`{ rowCount, rows }`), or an array of them
127
+ * (one per statement of a multi-statement query), summed. Sets nothing when no count is known.
128
+ */
129
+ function setReturnedRows(span, results) {
130
+ const counts = (Array.isArray(results) ? results : [results]).map(getRowCount).filter((count) => count !== void 0);
131
+ if (counts.length) span.setAttribute(DB_RESPONSE_RETURNED_ROWS, counts.reduce((sum, count) => sum + count, 0));
132
+ }
133
+ function getRowCount(result) {
134
+ if (!isObjectLike(result)) return;
135
+ const { rowCount, rows } = result;
136
+ if (typeof rowCount === "number") return rowCount;
137
+ return Array.isArray(rows) ? rows.length : void 0;
138
+ }
112
139
  function extractQueryConfig(args) {
113
140
  const arg0 = args[0];
114
141
  if (typeof arg0 === "string") return { text: arg0 };
@@ -179,6 +206,6 @@ function getConnectionString(params) {
179
206
  * hook or bundler plugin to be active.
180
207
  */
181
208
  const postgresIntegration = defineIntegration(_postgresIntegration);
182
- export { bindPgQueryChannel, getConnectionAttributes, postgresIntegration };
209
+ export { bindPgQueryChannel, getConnectionAttributes, postgresIntegration, setReturnedRows };
183
210
 
184
211
  //# sourceMappingURL=pg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pg.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/pg.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;AAwBA,MAAM,mBAAmB;AAIzB,MAAM,SAAS;AAEf,MAAM,eAAe;AACrB,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAS7B,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AA4B1B,MAAM,yBAAyB,UAA4C,CAAC,MAAM;CAChF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,eAAe,oBAAoB,CAAC,OAAO,CAAC;EACvF;CACF;AACF;AAEA,SAAS,mBAAmB,SAAiD;CAC3E,mBAAmB,SAAS,UAAU;EAAE,QAA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Y,KAAK;CAInC,MAAM,OAAO,OAAO,KAAK,IAAI,MAAM,OAAO,UAAU,KAAK,IAAI,IAAI,KAAK,OAAO,KAAA;CAC7E,MAAM,OAAO,KAAK,YAAY,KAAK;CACnC,OAAO;GACJ,iBAAiB;GAEjB,uBAAuB,oBAAoB,IAAI;GAC/C,uBAAuB,KAAK;GAC5B,qBAAqB,KAAK;GAC1B,eAAe;GACf,cAAc;GAEd,iBAAiB,QAAQ,KAAA;GACzB,UAAU,QAAQ,KAAA;CACrB;AACF;AAIA,SAAS,oBAAoB,QAAoC;CAC/D,IAAI,OAAO,kBACT,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,OAAO,gBAAgB;EAC3C,IAAI,WAAW;EACf,IAAI,WAAW;EACf,OAAO,IAAI,SAAS;CACtB,QAAQ;EACN,OAAO;CACT;CAKF,OAAO,gBAHM,OAAO,QAAQ,YAGA,GAFf,OAAO,QAAQ,KAEQ,GADnB,OAAO,YAAY;AAEtC;;;;;;;;;;AAWA,MAAa,sBAAsB,kBAAkB,oBAAoB"}
1
+ {"version":3,"file":"pg.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/pg.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_NAMESPACE,\n DB_RESPONSE_RETURNED_ROWS,\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, Span, 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), { isQuery: 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 is a query result that can be a streamable emitter and carries a row\n * count (`isQuery`).\n */\nfunction subscribeQueryLikeChannel(\n channelName: string,\n getSpanOptions: (ctx: PgChannelContext) => { name: string; attributes: SpanAttributes },\n { isQuery = false }: { isQuery?: 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 isQuery\n ? {\n beforeSpanEnd(span, data) {\n // A streamed `Submittable` reports its rows on its own `'end'` event (see `deferSpanEnd`).\n if ('error' in data || (isObjectLike(data.result) && hasOnMethod(data.result))) {\n return;\n }\n setReturnedRows(span, data.result);\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({ span, 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', (endResult?: unknown) => {\n // A `Query` ends with its full result(s). A cursor (`pg-cursor`, `pg-query-stream`) is read in\n // batches and ends with only the last batch, so its count would be wrong.\n if (!hasReadMethod(result)) {\n setReturnedRows(span, endResult);\n }\n end();\n });\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\nfunction hasReadMethod(obj: object): boolean {\n return 'read' in obj && typeof (obj as { read?: unknown }).read === 'function';\n}\n\n/**\n * Sets `db.response.returned_rows` from a pg-style result (`{ rowCount, rows }`), or an array of them\n * (one per statement of a multi-statement query), summed. Sets nothing when no count is known.\n */\nexport function setReturnedRows(span: Span, results: unknown): void {\n const counts = (Array.isArray(results) ? results : [results])\n .map(getRowCount)\n .filter((count): count is number => count !== undefined);\n if (counts.length) {\n span.setAttribute(\n DB_RESPONSE_RETURNED_ROWS,\n counts.reduce((sum, count) => sum + count, 0),\n );\n }\n}\n\nfunction getRowCount(result: unknown): number | undefined {\n if (!isObjectLike(result)) {\n return undefined;\n }\n const { rowCount, rows } = result as { rowCount?: unknown; rows?: unknown };\n if (typeof rowCount === 'number') {\n return rowCount;\n }\n return Array.isArray(rows) ? rows.length : undefined;\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"],"mappings":";;;;;;;;;;AAyBA,MAAM,mBAAmB;AAIzB,MAAM,SAAS;AAEf,MAAM,eAAe;AACrB,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAS7B,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AA4B1B,MAAM,yBAAyB,UAA4C,CAAC,MAAM;CAChF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,eAAe,oBAAoB,CAAC,OAAO,CAAC;EACvF;CACF;AACF;AAEA,SAAS,mBAAmB,SAAiD;CAC3E,mBAAmB,SAAS,UAAU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SAAS;CACtB,QAAQ;EACN,OAAO;CACT;CAKF,OAAO,gBAHM,OAAO,QAAQ,YAGA,GAFf,OAAO,QAAQ,KAEQ,GADnB,OAAO,YAAY;AAEtC;;;;;;;;;;AAWA,MAAa,sBAAsB,kBAAkB,oBAAoB"}
@@ -1 +1 @@
1
- {"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n captureLogEvent,\n addExceptionMechanism,\n captureException,\n captureMessage,\n defineIntegration,\n isObjectLike,\n severityLevelFromString,\n withScope,\n} from '@sentry/core';\nimport { tracingChannel } from '../utils/diagnosticsChannel';\n\nconst SENTRY_TRACK_SYMBOL = Symbol('sentry-track-pino-logger');\n\ntype LevelMapping = {\n // Fortunately pino uses the same levels as Sentry\n labels: { [level: number]: LogSeverityLevel };\n};\n\ntype Pino = {\n [key: symbol]: unknown;\n levels: LevelMapping;\n [SENTRY_TRACK_SYMBOL]?: 'track' | 'ignore';\n};\n\n/**\n * Gets a custom Pino key from a logger instance by searching for the symbol.\n * Pino uses non-global symbols like Symbol('pino.messageKey'): https://github.com/pinojs/pino/blob/8a816c0b1f72de5ae9181f3bb402109b66f7d812/lib/symbols.js\n */\nfunction getPinoKey(logger: Pino, symbolName: string, defaultKey: string): string {\n const symbols = Object.getOwnPropertySymbols(logger);\n const symbolString = `Symbol(${symbolName})`;\n for (const sym of symbols) {\n if (sym.toString() === symbolString) {\n const value = logger[sym];\n return typeof value === 'string' ? value : defaultKey;\n }\n }\n return defaultKey;\n}\n\ntype MergeObject = {\n [key: string]: unknown;\n err?: Error;\n};\n\ntype PinoHookArgs = [MergeObject, string, number];\n\ntype PinoOptions = {\n /**\n * Automatically instrument all Pino loggers.\n *\n * When set to `false`, only loggers marked with `pinoIntegration.trackLogger(logger)` will be captured.\n *\n * @default true\n */\n autoInstrument: boolean;\n /**\n * Options to enable capturing of error events.\n */\n error: {\n /**\n * Levels that trigger capturing of events.\n *\n * @default []\n */\n levels: LogSeverityLevel[];\n /**\n * By default, Sentry will mark captured errors as handled.\n * Set this to `false` if you want to mark them as unhandled instead.\n *\n * @default true\n */\n handled: boolean;\n };\n /**\n * Options to enable capturing of logs.\n */\n log: {\n /**\n * Levels that trigger capturing of logs.\n *\n * @default [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]\n */\n levels: LogSeverityLevel[];\n };\n};\n\nconst DEFAULT_OPTIONS: PinoOptions = {\n autoInstrument: true,\n error: { levels: [], handled: true },\n log: { levels: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] },\n};\n\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? Partial<T[P]> : T[P];\n};\n\ntype PinoResult = {\n level?: string;\n time?: string;\n pid?: number;\n hostname?: string;\n} & Record<string, unknown>;\n\nfunction stripIgnoredFields(result: PinoResult): PinoResult {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, time, pid, hostname, ...rest } = result;\n return rest;\n}\n\nconst _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions> = {}) => {\n const options: PinoOptions = {\n autoInstrument: userOptions.autoInstrument !== false,\n error: { ...DEFAULT_OPTIONS.error, ...userOptions.error },\n log: { ...DEFAULT_OPTIONS.log, ...userOptions.log },\n };\n\n function shouldTrackLogger(logger: Pino): boolean {\n const override = logger[SENTRY_TRACK_SYMBOL];\n return override === 'track' || (override !== 'ignore' && options.autoInstrument);\n }\n\n return {\n name: 'Pino',\n setup: () => {\n const integratedChannel = tracingChannel('pino_asJson');\n\n function onPinoStart(self: Pino, args: PinoHookArgs, result: PinoResult): void {\n if (!shouldTrackLogger(self)) {\n return;\n }\n\n const resultObj = stripIgnoredFields(result);\n\n const [captureObj, message, levelNumber] = args;\n const level = self?.levels?.labels?.[levelNumber] || 'info';\n const messageKey = getPinoKey(self, 'pino.messageKey', 'msg');\n const logMessage = message || (resultObj?.[messageKey] as string | undefined) || '';\n\n if (options.log.levels.includes(level)) {\n const attributes: Record<string, unknown> = {\n ...resultObj,\n [SENTRY_ORIGIN]: 'auto.log.pino',\n 'pino.logger.level': levelNumber,\n };\n\n captureLogEvent({ level, message: logMessage, attributes });\n }\n\n if (options.error.levels.includes(level)) {\n const errorKey = getPinoKey(self, 'pino.errorKey', 'err');\n\n // Attach the log message and remaining log fields (e.g. child logger\n // bindings, merge object fields) to the event. The serialized error is\n // excluded since it is captured as the event exception itself.\n const pinoContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(resultObj)) {\n if (key !== errorKey && key !== messageKey) {\n pinoContext[key] = value;\n }\n }\n if (logMessage) {\n pinoContext[messageKey] = logMessage;\n }\n\n const captureContext = {\n level: severityLevelFromString(level),\n contexts: { pino: pinoContext },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'pino';\n\n addExceptionMechanism(event, {\n handled: options.error.handled,\n type: 'auto.log.pino',\n });\n\n return event;\n });\n\n const error = captureObj[errorKey];\n if (error) {\n captureException(error, captureContext);\n return;\n }\n\n captureMessage(logMessage, captureContext);\n });\n }\n }\n\n integratedChannel.end.subscribe(data => {\n const {\n instance,\n arguments: args,\n result,\n } = data as { instance: Pino; arguments: PinoHookArgs; result: string };\n onPinoStart(instance, args, JSON.parse(result));\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Integration for Pino logging library.\n * Captures Pino logs as Sentry logs and optionally captures some log levels as events.\n *\n * By default, all Pino loggers will be captured. To ignore a specific logger, use `pinoIntegration.untrackLogger(logger)`.\n *\n * If you disable automatic instrumentation with `autoInstrument: false`, you can mark specific loggers to be tracked with `pinoIntegration.trackLogger(logger)`.\n *\n * Requires Pino >=v8.0.0\n */\nexport const pinoIntegration = Object.assign(_pinoIntegration, {\n trackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'track';\n }\n },\n untrackL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Aa,MAAM,KAAK,YAAY,QACrC,OAAgB,uBAAuB;CAE5C;AACF,CAAC"}
1
+ {"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n captureLogEvent,\n addExceptionMechanism,\n captureException,\n captureMessage,\n defineIntegration,\n isObjectLike,\n severityLevelFromString,\n withScope,\n} from '@sentry/core';\nimport { tracingChannel } from '../utils/diagnosticsChannel';\n\nconst SENTRY_TRACK_SYMBOL = Symbol('sentry-track-pino-logger');\n\ntype LevelMapping = {\n // Fortunately pino uses the same levels as Sentry\n labels: { [level: number]: LogSeverityLevel };\n};\n\ntype Pino = {\n [key: symbol]: unknown;\n levels: LevelMapping;\n [SENTRY_TRACK_SYMBOL]?: 'track' | 'ignore';\n};\n\n/**\n * Gets a custom Pino key from a logger instance by searching for the symbol.\n * Pino uses non-global symbols like Symbol('pino.messageKey'): https://github.com/pinojs/pino/blob/8a816c0b1f72de5ae9181f3bb402109b66f7d812/lib/symbols.js\n */\nfunction getPinoKey(logger: Pino, symbolName: string, defaultKey: string): string {\n const symbols = Object.getOwnPropertySymbols(logger);\n const symbolString = `Symbol(${symbolName})`;\n for (const sym of symbols) {\n if (sym.toString() === symbolString) {\n const value = logger[sym];\n return typeof value === 'string' ? value : defaultKey;\n }\n }\n return defaultKey;\n}\n\ntype MergeObject = {\n [key: string]: unknown;\n err?: Error;\n};\n\ntype PinoHookArgs = [MergeObject, string, number];\n\ntype PinoOptions = {\n /**\n * Automatically instrument all Pino loggers.\n *\n * When set to `false`, only loggers marked with `pinoIntegration.trackLogger(logger)` will be captured.\n *\n * @default true\n */\n autoInstrument: boolean;\n /**\n * Options to enable capturing of error events.\n */\n error: {\n /**\n * Levels that trigger capturing of events.\n *\n * @default []\n */\n levels: LogSeverityLevel[];\n /**\n * By default, Sentry will mark captured errors as handled.\n * Set this to `false` if you want to mark them as unhandled instead.\n *\n * @default true\n */\n handled: boolean;\n };\n /**\n * Options to enable capturing of logs.\n */\n log: {\n /**\n * Levels that trigger capturing of logs.\n *\n * @default [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]\n */\n levels: LogSeverityLevel[];\n };\n};\n\nconst DEFAULT_OPTIONS: PinoOptions = {\n autoInstrument: true,\n error: { levels: [], handled: true },\n log: { levels: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] },\n};\n\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? Partial<T[P]> : T[P];\n};\n\ntype PinoResult = {\n level?: string;\n time?: string;\n pid?: number;\n hostname?: string;\n} & Record<string, unknown>;\n\nfunction stripIgnoredFields(result: PinoResult): PinoResult {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, time, pid, hostname, ...rest } = result;\n return rest;\n}\n\nconst _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions> = {}) => {\n const options: PinoOptions = {\n autoInstrument: userOptions.autoInstrument !== false,\n error: { ...DEFAULT_OPTIONS.error, ...userOptions.error },\n log: { ...DEFAULT_OPTIONS.log, ...userOptions.log },\n };\n\n function shouldTrackLogger(logger: Pino): boolean {\n const override = logger[SENTRY_TRACK_SYMBOL];\n return override === 'track' || (override !== 'ignore' && options.autoInstrument);\n }\n\n return {\n name: 'Pino',\n setup: () => {\n const integratedChannel = tracingChannel('pino_asJson');\n\n function onPinoStart(self: Pino, args: PinoHookArgs, result: PinoResult): void {\n if (!shouldTrackLogger(self)) {\n return;\n }\n\n const resultObj = stripIgnoredFields(result);\n\n const [captureObj, message, levelNumber] = args;\n const level = self?.levels?.labels?.[levelNumber] || 'info';\n const messageKey = getPinoKey(self, 'pino.messageKey', 'msg');\n const logMessage = message || (resultObj?.[messageKey] as string | undefined) || '';\n\n if (options.log.levels.includes(level)) {\n const attributes: Record<string, unknown> = {\n ...resultObj,\n [SENTRY_ORIGIN]: 'auto.log.pino',\n 'pino.logger.level': levelNumber,\n };\n\n captureLogEvent({ level, message: logMessage, attributes });\n }\n\n if (options.error.levels.includes(level)) {\n const errorKey = getPinoKey(self, 'pino.errorKey', 'err');\n\n // Attach the log message and remaining log fields (e.g. child logger\n // bindings, merge object fields) to the event. The serialized error is\n // excluded since it is captured as the event exception itself.\n const pinoContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(resultObj)) {\n if (key !== errorKey && key !== messageKey) {\n pinoContext[key] = value;\n }\n }\n if (logMessage) {\n pinoContext[messageKey] = logMessage;\n }\n\n const captureContext = {\n level: severityLevelFromString(level),\n contexts: { pino: pinoContext },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'pino';\n\n addExceptionMechanism(event, {\n handled: options.error.handled,\n type: 'auto.log.pino',\n });\n\n return event;\n });\n\n const error = captureObj[errorKey];\n if (error) {\n // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor above\n captureException(error, captureContext);\n return;\n }\n\n captureMessage(logMessage, captureContext);\n });\n }\n }\n\n integratedChannel.end.subscribe(data => {\n const {\n instance,\n arguments: args,\n result,\n } = data as { instance: Pino; arguments: PinoHookArgs; result: string };\n onPinoStart(instance, args, JSON.parse(result));\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Integration for Pino logging library.\n * Captures Pino logs as Sentry logs and optionally captures some log levels as events.\n *\n * By default, all Pino loggers will be captured. To ignore a specific logger, use `pinoIntegration.untrackLogger(logger)`.\n *\n * If you disable automatic instrumentation with `autoInstrument: false`, you can mark specific loggers to be tracked with `pinoIntegration.trackLogger(logger)`.\n *\n * Requires Pino >=v8.0.0\n */\nexport const pinoIntegration = Object.assign(_pinoIntegration, {\n trackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'track';\n }\n },\n untrackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMB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,6 @@
1
- import { mapObjectValues } from "./util.js";
1
+ import { asNumber, mapObjectValues } from "./util.js";
2
2
  import { isObjectLike, stringify } from "@sentry/core";
3
3
  // src/integrations/vercel-ai/extract.ts
4
- /** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */
5
4
  /**
6
5
  * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on
7
6
  * the server and does not show its separator, so this one is our choice. It only makes the recorded text
@@ -62,7 +61,7 @@ function toExtractAnswers(answers, parts) {
62
61
  return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {
63
62
  const mapped = {
64
63
  ...rest,
65
- p_null: pNull
64
+ p_null: asNumber(pNull)
66
65
  };
67
66
  const span = toExtractSpan(source, parts);
68
67
  if (span) {
@@ -1 +1 @@
1
- {"version":3,"file":"extract.js","names":[],"sources":["../../../../src/integrations/vercel-ai/extract.ts"],"sourcesContent":["/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */\n\nimport { isObjectLike, stringify } from '@sentry/core';\nimport { mapObjectValues } from './util';\n\n/**\n * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on\n * the server and does not show its separator, so this one is our choice. It only makes the recorded text\n * easier to read: the answer spans stay correct with any separator, because we add each part's offset.\n */\nconst EXTRACT_STATE_SEPARATOR = '\\n\\n';\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\ninterface ExtractState {\n request: { state?: string; images?: string[]; documents?: string[] };\n /** For each AI SDK state part, the offset of its text in `request.state`, or `'image'` for an image part. */\n parts: (number | 'image' | undefined)[];\n}\n\n/**\n * Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK\n * also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the\n * offset of each part, so that the answer spans point into the joined `state`.\n */\nexport function toExtractState(state: unknown): ExtractState {\n const images: string[] = [];\n const documents: string[] = [];\n // Each text gets a separator in front, which is cut off from the start of `state` at the end.\n let joined = '';\n\n const parts = (Array.isArray(state) ? state : [{ type: 'json', value: state }]).map(part => {\n if (!isObjectLike(part)) {\n return undefined;\n }\n if (part.type === 'file') {\n if (String(part.mediaType).split('/')[0] === 'image') {\n images.push(BLOB_SUBSTITUTE);\n return 'image' as const;\n }\n if (part.mediaType === 'application/pdf') {\n documents.push(BLOB_SUBSTITUTE);\n }\n return undefined;\n }\n const text = part.type === 'text' ? part.text : stringify(part.value);\n if (typeof text !== 'string') {\n return undefined;\n }\n joined += EXTRACT_STATE_SEPARATOR + text;\n return joined.length - text.length - EXTRACT_STATE_SEPARATOR.length;\n });\n\n return {\n request: {\n state: joined ? joined.slice(EXTRACT_STATE_SEPARATOR.length) : undefined,\n images: images.length ? images : undefined,\n documents: documents.length ? documents : undefined,\n },\n parts,\n };\n}\n\n/**\n * The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string.\n */\nexport function toExtractFields(fields: unknown): unknown {\n return isObjectLike(fields)\n ? mapObjectValues(fields, field => ({\n ...field,\n instructions: field.instructions === null ? undefined : stringify(field.instructions),\n }))\n : fields;\n}\n\n/**\n * The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of\n * `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`.\n */\nexport function toExtractAnswers(\n answers: Record<string, unknown>,\n parts: ExtractState['parts'],\n): Record<string, unknown> {\n return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {\n const mapped: Record<string, unknown> = { ...rest, p_null: pNull };\n const span = toExtractSpan(source, parts);\n if (span) {\n mapped.source = 'input';\n mapped.span = span;\n } else if (isObjectLike(source) && parts[Number(source.part)] === 'image') {\n mapped.source = 'image';\n }\n if (Array.isArray(items)) {\n const confidences = items.map(item => (isObjectLike(item) ? item.confidence : undefined));\n if (confidences.every(confidence => typeof confidence === 'number')) {\n mapped.confidences = confidences;\n }\n const spans = items.map(item => toExtractSpan(isObjectLike(item) ? item.source : undefined, parts));\n if (spans.some(Boolean)) {\n mapped.spans = spans;\n }\n }\n return mapped;\n });\n}\n\nfunction toExtractSpan(source: unknown, parts: ExtractState['parts']): [number, number] | null {\n if (!isObjectLike(source) || source.type !== 'text') {\n return null;\n }\n const offset = parts[Number(source.part)];\n return typeof offset === 'number' ? [offset + Number(source.start), offset + Number(source.end)] : null;\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,0BAA0B;AAChC,MAAM,kBAAkB;;;;;;AAaxB,SAAgB,eAAe,OAA8B;CAC3D,MAAM,SAAmB,CAAC;CAC1B,MAAM,YAAsB,CAAC;CAE7B,IAAI,SAAS;CAEb,MAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;EAAE,MAAM;EAAQ,OAAO;CAAM,CAAC,EAAA,CAAG,KAAI,SAAQ;EAC1F,IAAI,CAAC,aAAa,IAAI,GACpB;EAEF,IAAI,KAAK,SAAS,QAAQ;GACxB,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,SAAS;IACpD,OAAO,KAAK,eAAe;IAC3B,OAAO;GACT;GACA,IAAI,KAAK,cAAc,mBACrB,UAAU,KAAK,eAAe;GAEhC;EACF;EACA,MAAM,OAAO,KAAK,SAAS,SAAS,KAAK,OAAO,UAAU,KAAK,KAAK;EACpE,IAAI,OAAO,SAAS,UAClB;EAEF,UAAU,0BAA0B;EACpC,OAAO,OAAO,SAAS,KAAK,SAAS;CACvC,CAAC;CAED,OAAO;EACL,SAAS;GACP,OAAO,SAAS,OAAO,MAAM,CAA8B,IAAI,KAAA;GAC/D,QAAQ,OAAO,SAAS,SAAS,KAAA;GACjC,WAAW,UAAU,SAAS,YAAY,KAAA;EAC5C;EACA;CACF;AACF;;;;AAKA,SAAgB,gBAAgB,QAA0B;CACxD,OAAO,aAAa,MAAM,IACtB,gBAAgB,SAAQ,WAAU;EAChC,GAAG;EACH,cAAc,MAAM,iBAAiB,OAAO,KAAA,IAAY,UAAU,MAAM,YAAY;CACtF,EAAE,IACF;AACN;;;;;AAMA,SAAgB,iBACd,SACA,OACyB;CACzB,OAAO,gBAAgB,UAAU,EAAE,OAAO,QAAQ,OAAO,GAAG,WAAW;EACrE,MAAM,SAAkC;GAAE,GAAG;GAAM,QAAQ;EAAM;EACjE,MAAM,OAAO,cAAc,QAAQ,KAAK;EACxC,IAAI,MAAM;GACR,OAAO,SAAS;GAChB,OAAO,OAAO;EAChB,OAAO,IAAI,aAAa,MAAM,KAAK,MAAM,OAAO,OAAO,IAAI,OAAO,SAChE,OAAO,SAAS;EAElB,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,MAAM,cAAc,MAAM,KAAI,SAAS,aAAa,IAAI,IAAI,KAAK,aAAa,KAAA,CAAU;GACxF,IAAI,YAAY,OAAM,eAAc,OAAO,eAAe,QAAQ,GAChE,OAAO,cAAc;GAEvB,MAAM,QAAQ,MAAM,KAAI,SAAQ,cAAc,aAAa,IAAI,IAAI,KAAK,SAAS,KAAA,GAAW,KAAK,CAAC;GAClG,IAAI,MAAM,KAAK,OAAO,GACpB,OAAO,QAAQ;EAEnB;EACA,OAAO;CACT,CAAC;AACH;AAEA,SAAS,cAAc,QAAiB,OAAuD;CAC7F,IAAI,CAAC,aAAa,MAAM,KAAK,OAAO,SAAS,QAC3C,OAAO;CAET,MAAM,SAAS,MAAM,OAAO,OAAO,IAAI;CACvC,OAAO,OAAO,WAAW,WAAW,CAAC,SAAS,OAAO,OAAO,KAAK,GAAG,SAAS,OAAO,OAAO,GAAG,CAAC,IAAI;AACrG"}
1
+ {"version":3,"file":"extract.js","names":[],"sources":["../../../../src/integrations/vercel-ai/extract.ts"],"sourcesContent":["/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */\n\nimport type { ExtractAnswer, ExtractRequest, ExtractSpan } from '@sentry/conventions/attributes';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport { asNumber, mapObjectValues } from './util';\n\n/**\n * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on\n * the server and does not show its separator, so this one is our choice. It only makes the recorded text\n * easier to read: the answer spans stay correct with any separator, because we add each part's offset.\n */\nconst EXTRACT_STATE_SEPARATOR = '\\n\\n';\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\ninterface ExtractState {\n request: Pick<ExtractRequest, 'state' | 'images' | 'documents'>;\n /** For each AI SDK state part, the offset of its text in `request.state`, or `'image'` for an image part. */\n parts: (number | 'image' | undefined)[];\n}\n\n/**\n * Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK\n * also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the\n * offset of each part, so that the answer spans point into the joined `state`.\n */\nexport function toExtractState(state: unknown): ExtractState {\n const images: string[] = [];\n const documents: string[] = [];\n // Each text gets a separator in front, which is cut off from the start of `state` at the end.\n let joined = '';\n\n const parts = (Array.isArray(state) ? state : [{ type: 'json', value: state }]).map(part => {\n if (!isObjectLike(part)) {\n return undefined;\n }\n if (part.type === 'file') {\n if (String(part.mediaType).split('/')[0] === 'image') {\n images.push(BLOB_SUBSTITUTE);\n return 'image' as const;\n }\n if (part.mediaType === 'application/pdf') {\n documents.push(BLOB_SUBSTITUTE);\n }\n return undefined;\n }\n const text = part.type === 'text' ? part.text : stringify(part.value);\n if (typeof text !== 'string') {\n return undefined;\n }\n joined += EXTRACT_STATE_SEPARATOR + text;\n return joined.length - text.length - EXTRACT_STATE_SEPARATOR.length;\n });\n\n return {\n request: {\n state: joined ? joined.slice(EXTRACT_STATE_SEPARATOR.length) : undefined,\n images: images.length ? images : undefined,\n documents: documents.length ? documents : undefined,\n },\n parts,\n };\n}\n\n/**\n * The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string.\n */\nexport function toExtractFields(fields: unknown): unknown {\n return isObjectLike(fields)\n ? mapObjectValues(fields, field => ({\n ...field,\n instructions: field.instructions === null ? undefined : stringify(field.instructions),\n }))\n : fields;\n}\n\n/**\n * The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of\n * `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`.\n */\nexport function toExtractAnswers(\n answers: Record<string, unknown>,\n parts: ExtractState['parts'],\n): Record<string, unknown> {\n return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {\n const mapped: Record<string, unknown> & Partial<ExtractAnswer> = { ...rest, p_null: asNumber(pNull) };\n const span = toExtractSpan(source, parts);\n if (span) {\n mapped.source = 'input';\n mapped.span = span;\n } else if (isObjectLike(source) && parts[Number(source.part)] === 'image') {\n mapped.source = 'image';\n }\n if (Array.isArray(items)) {\n const confidences = items.map(item => (isObjectLike(item) ? item.confidence : undefined));\n if (confidences.every(confidence => typeof confidence === 'number')) {\n mapped.confidences = confidences;\n }\n const spans = items.map(item => toExtractSpan(isObjectLike(item) ? item.source : undefined, parts));\n if (spans.some(Boolean)) {\n mapped.spans = spans;\n }\n }\n return mapped;\n });\n}\n\nfunction toExtractSpan(source: unknown, parts: ExtractState['parts']): ExtractSpan | null {\n if (!isObjectLike(source) || source.type !== 'text') {\n return null;\n }\n const offset = parts[Number(source.part)];\n return typeof offset === 'number' ? [offset + Number(source.start), offset + Number(source.end)] : null;\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,0BAA0B;AAChC,MAAM,kBAAkB;;;;;;AAaxB,SAAgB,eAAe,OAA8B;CAC3D,MAAM,SAAmB,CAAC;CAC1B,MAAM,YAAsB,CAAC;CAE7B,IAAI,SAAS;CAEb,MAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;EAAE,MAAM;EAAQ,OAAO;CAAM,CAAC,EAAA,CAAG,KAAI,SAAQ;EAC1F,IAAI,CAAC,aAAa,IAAI,GACpB;EAEF,IAAI,KAAK,SAAS,QAAQ;GACxB,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,SAAS;IACpD,OAAO,KAAK,eAAe;IAC3B,OAAO;GACT;GACA,IAAI,KAAK,cAAc,mBAC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,CAAC;AACH;AAEA,SAAS,cAAc,QAAiB,OAAkD;CACxF,IAAI,CAAC,aAAa,MAAM,KAAK,OAAO,SAAS,QAC3C,OAAO;CAET,MAAM,SAAS,MAAM,OAAO,OAAO,IAAI;CACvC,OAAO,OAAO,WAAW,WAAW,CAAC,SAAS,OAAO,OAAO,KAAK,GAAG,SAAS,OAAO,OAAO,GAAG,CAAC,IAAI;AACrG"}
@@ -6,6 +6,7 @@ const VERSION_RANGE = ">=8.0.0-rc.15 <9";
6
6
  const PRISMA_ASYNC_TERMINALS = [
7
7
  "aggregate",
8
8
  "first",
9
+ "firstOrThrow",
9
10
  "create",
10
11
  "createAndCount",
11
12
  "upsert",
@@ -40,6 +41,7 @@ const prismaModuleNames = getModuleNames(prismaConfig);
40
41
  const prismaChannels = {
41
42
  PRISMA_AGGREGATE: "orchestrion:@prisma/orm-family-sql:aggregate",
42
43
  PRISMA_FIRST: "orchestrion:@prisma/orm-family-sql:first",
44
+ PRISMA_FIRST_OR_THROW: "orchestrion:@prisma/orm-family-sql:firstOrThrow",
43
45
  PRISMA_CREATE: "orchestrion:@prisma/orm-family-sql:create",
44
46
  PRISMA_CREATE_AND_COUNT: "orchestrion:@prisma/orm-family-sql:createAndCount",
45
47
  PRISMA_UPSERT: "orchestrion:@prisma/orm-family-sql:upsert",