@sentry/server-utils 11.14.0 → 11.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/build/cjs/chunks/exports.js +526 -217
  2. package/build/cjs/chunks/exports.js.map +1 -1
  3. package/build/cjs/index.js +1028 -120
  4. package/build/cjs/index.js.map +1 -1
  5. package/build/esm/ai/anthropic-ai/index.js +32 -56
  6. package/build/esm/ai/anthropic-ai/index.js.map +1 -1
  7. package/build/esm/ai/anthropic-ai/streaming.js +10 -6
  8. package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
  9. package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
  10. package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
  11. package/build/esm/ai/anthropic-ai/utils.js +41 -3
  12. package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
  13. package/build/esm/ai/core/span-hooks.js +23 -0
  14. package/build/esm/ai/core/span-hooks.js.map +1 -0
  15. package/build/esm/ai/core/time-to-first-chunk.js +14 -0
  16. package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
  17. package/build/esm/ai/core/utils.js +29 -3
  18. package/build/esm/ai/core/utils.js.map +1 -1
  19. package/build/esm/ai/flue/index.js +15 -12
  20. package/build/esm/ai/flue/index.js.map +1 -1
  21. package/build/esm/ai/flue/utils.js +24 -17
  22. package/build/esm/ai/flue/utils.js.map +1 -1
  23. package/build/esm/ai/google-genai/index.js +21 -8
  24. package/build/esm/ai/google-genai/index.js.map +1 -1
  25. package/build/esm/ai/google-genai/streaming.js +6 -2
  26. package/build/esm/ai/google-genai/streaming.js.map +1 -1
  27. package/build/esm/ai/langchain/embeddings.js +5 -2
  28. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  29. package/build/esm/ai/langchain/index.js +82 -24
  30. package/build/esm/ai/langchain/index.js.map +1 -1
  31. package/build/esm/ai/langchain/utils.js +9 -1
  32. package/build/esm/ai/langchain/utils.js.map +1 -1
  33. package/build/esm/ai/langgraph/agent-span.js +13 -5
  34. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  35. package/build/esm/ai/langgraph/index.js +13 -15
  36. package/build/esm/ai/langgraph/index.js.map +1 -1
  37. package/build/esm/ai/langgraph/stream.js +4 -3
  38. package/build/esm/ai/langgraph/stream.js.map +1 -1
  39. package/build/esm/ai/langgraph/utils.js +17 -8
  40. package/build/esm/ai/langgraph/utils.js.map +1 -1
  41. package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
  42. package/build/esm/ai/mastra/index.js +33 -16
  43. package/build/esm/ai/mastra/index.js.map +1 -1
  44. package/build/esm/ai/mastra/utils.js +3 -5
  45. package/build/esm/ai/mastra/utils.js.map +1 -1
  46. package/build/esm/ai/mistral/index.js +21 -7
  47. package/build/esm/ai/mistral/index.js.map +1 -1
  48. package/build/esm/ai/mistral/streaming.js +4 -2
  49. package/build/esm/ai/mistral/streaming.js.map +1 -1
  50. package/build/esm/ai/openai/index.js +19 -8
  51. package/build/esm/ai/openai/index.js.map +1 -1
  52. package/build/esm/ai/openai/streaming.js +7 -2
  53. package/build/esm/ai/openai/streaming.js.map +1 -1
  54. package/build/esm/ai/pi-ai/chat.js +18 -1
  55. package/build/esm/ai/pi-ai/chat.js.map +1 -1
  56. package/build/esm/ai/pi-ai/recording.js +34 -15
  57. package/build/esm/ai/pi-ai/recording.js.map +1 -1
  58. package/build/esm/ai/pi-durable/index.js +7 -2
  59. package/build/esm/ai/pi-durable/index.js.map +1 -1
  60. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  61. package/build/esm/ai/pi-durable/tools.js +18 -3
  62. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  63. package/build/esm/ai/typesafe/index.js +14 -6
  64. package/build/esm/ai/typesafe/index.js.map +1 -1
  65. package/build/esm/ai/workers-ai/index.js +26 -9
  66. package/build/esm/ai/workers-ai/index.js.map +1 -1
  67. package/build/esm/ai/workers-ai/streaming.js +6 -4
  68. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  69. package/build/esm/cron/common.js +16 -0
  70. package/build/esm/cron/common.js.map +1 -0
  71. package/build/esm/cron/cron.js +82 -0
  72. package/build/esm/cron/cron.js.map +1 -0
  73. package/build/esm/cron/index.js +13 -0
  74. package/build/esm/cron/index.js.map +1 -0
  75. package/build/esm/cron/node-cron.js +66 -0
  76. package/build/esm/cron/node-cron.js.map +1 -0
  77. package/build/esm/cron/node-schedule.js +43 -0
  78. package/build/esm/cron/node-schedule.js.map +1 -0
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/index.js.map +1 -1
  81. package/build/esm/integrations/anthropic.js +25 -16
  82. package/build/esm/integrations/anthropic.js.map +1 -1
  83. package/build/esm/integrations/aws-sdk/index.js +1 -0
  84. package/build/esm/integrations/aws-sdk/index.js.map +1 -1
  85. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
  86. package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
  87. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
  88. package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
  89. package/build/esm/integrations/bullmq/contextManager.js +45 -0
  90. package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
  91. package/build/esm/integrations/bullmq/index.js +44 -0
  92. package/build/esm/integrations/bullmq/index.js.map +1 -0
  93. package/build/esm/integrations/bullmq/meter.js +86 -0
  94. package/build/esm/integrations/bullmq/meter.js.map +1 -0
  95. package/build/esm/integrations/bullmq/span.js +114 -0
  96. package/build/esm/integrations/bullmq/span.js.map +1 -0
  97. package/build/esm/integrations/bullmq/tracer.js +62 -0
  98. package/build/esm/integrations/bullmq/tracer.js.map +1 -0
  99. package/build/esm/integrations/express/instrumentation.js +10 -1
  100. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  101. package/build/esm/integrations/google-genai.js +17 -9
  102. package/build/esm/integrations/google-genai.js.map +1 -1
  103. package/build/esm/integrations/langgraph.js +5 -7
  104. package/build/esm/integrations/langgraph.js.map +1 -1
  105. package/build/esm/integrations/mastra-classifier.js +1 -1
  106. package/build/esm/integrations/mastra-classifier.js.map +1 -1
  107. package/build/esm/integrations/mistral.js +13 -4
  108. package/build/esm/integrations/mistral.js.map +1 -1
  109. package/build/esm/integrations/openai-compatible.js +16 -8
  110. package/build/esm/integrations/openai-compatible.js.map +1 -1
  111. package/build/esm/integrations/openai.js +16 -8
  112. package/build/esm/integrations/openai.js.map +1 -1
  113. package/build/esm/integrations/pi-ai.js +39 -18
  114. package/build/esm/integrations/pi-ai.js.map +1 -1
  115. package/build/esm/integrations/pino.js +131 -0
  116. package/build/esm/integrations/pino.js.map +1 -0
  117. package/build/esm/integrations/typesafe.js +17 -3
  118. package/build/esm/integrations/typesafe.js.map +1 -1
  119. package/build/esm/integrations/vercel-ai/index.js.map +1 -1
  120. package/build/esm/integrations/vercel-ai/util.js +3 -2
  121. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  122. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
  123. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  124. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
  125. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  126. package/build/esm/integrations/winston.js +90 -0
  127. package/build/esm/integrations/winston.js.map +1 -0
  128. package/build/esm/orchestrion/detect.js +1 -1
  129. package/build/esm/orchestrion/detect.js.map +1 -1
  130. package/build/esm/package.json +1 -1
  131. package/build/types/ai/anthropic-ai/index.d.ts +1 -5
  132. package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
  133. package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
  134. package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
  135. package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
  136. package/build/types/ai/anthropic-ai/types.d.ts +24 -3
  137. package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
  138. package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
  139. package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
  140. package/build/types/ai/core/span-hooks.d.ts +31 -0
  141. package/build/types/ai/core/span-hooks.d.ts.map +1 -0
  142. package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
  143. package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
  144. package/build/types/ai/core/utils.d.ts +30 -1
  145. package/build/types/ai/core/utils.d.ts.map +1 -1
  146. package/build/types/ai/flue/index.d.ts +13 -5
  147. package/build/types/ai/flue/index.d.ts.map +1 -1
  148. package/build/types/ai/flue/types.d.ts +20 -2
  149. package/build/types/ai/flue/types.d.ts.map +1 -1
  150. package/build/types/ai/flue/utils.d.ts +5 -9
  151. package/build/types/ai/flue/utils.d.ts.map +1 -1
  152. package/build/types/ai/google-genai/index.d.ts.map +1 -1
  153. package/build/types/ai/google-genai/streaming.d.ts +2 -1
  154. package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
  155. package/build/types/ai/google-genai/types.d.ts +17 -3
  156. package/build/types/ai/google-genai/types.d.ts.map +1 -1
  157. package/build/types/ai/langchain/index.d.ts.map +1 -1
  158. package/build/types/ai/langchain/types.d.ts +49 -3
  159. package/build/types/ai/langchain/types.d.ts.map +1 -1
  160. package/build/types/ai/langchain/utils.d.ts +6 -0
  161. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  162. package/build/types/ai/langgraph/agent-span.d.ts +4 -1
  163. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  164. package/build/types/ai/langgraph/index.d.ts +1 -1
  165. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  166. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  167. package/build/types/ai/langgraph/types.d.ts +14 -3
  168. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  169. package/build/types/ai/langgraph/utils.d.ts +3 -0
  170. package/build/types/ai/langgraph/utils.d.ts.map +1 -1
  171. package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
  172. package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
  173. package/build/types/ai/mastra/index.d.ts +17 -3
  174. package/build/types/ai/mastra/index.d.ts.map +1 -1
  175. package/build/types/ai/mastra/types.d.ts +2 -0
  176. package/build/types/ai/mastra/types.d.ts.map +1 -1
  177. package/build/types/ai/mastra/utils.d.ts.map +1 -1
  178. package/build/types/ai/mistral/index.d.ts.map +1 -1
  179. package/build/types/ai/mistral/streaming.d.ts +2 -1
  180. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  181. package/build/types/ai/mistral/types.d.ts +14 -3
  182. package/build/types/ai/mistral/types.d.ts.map +1 -1
  183. package/build/types/ai/openai/index.d.ts.map +1 -1
  184. package/build/types/ai/openai/streaming.d.ts +3 -1
  185. package/build/types/ai/openai/streaming.d.ts.map +1 -1
  186. package/build/types/ai/openai/types.d.ts +14 -3
  187. package/build/types/ai/openai/types.d.ts.map +1 -1
  188. package/build/types/ai/pi-ai/chat.d.ts +7 -1
  189. package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
  190. package/build/types/ai/pi-ai/recording.d.ts +21 -9
  191. package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
  192. package/build/types/ai/pi-ai/types.d.ts +16 -0
  193. package/build/types/ai/pi-ai/types.d.ts.map +1 -1
  194. package/build/types/ai/pi-durable/index.d.ts +12 -3
  195. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  196. package/build/types/ai/pi-durable/runs.d.ts +2 -0
  197. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  198. package/build/types/ai/pi-durable/tools.d.ts +4 -3
  199. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  200. package/build/types/ai/pi-durable/types.d.ts +15 -0
  201. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  202. package/build/types/ai/typesafe/index.d.ts +10 -2
  203. package/build/types/ai/typesafe/index.d.ts.map +1 -1
  204. package/build/types/ai/workers-ai/index.d.ts.map +1 -1
  205. package/build/types/ai/workers-ai/streaming.d.ts +2 -1
  206. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  207. package/build/types/ai/workers-ai/types.d.ts +18 -3
  208. package/build/types/ai/workers-ai/types.d.ts.map +1 -1
  209. package/build/types/cron/common.d.ts +8 -0
  210. package/build/types/cron/common.d.ts.map +1 -0
  211. package/build/types/cron/cron.d.ts +45 -0
  212. package/build/types/cron/cron.d.ts.map +1 -0
  213. package/build/types/cron/index.d.ts +10 -0
  214. package/build/types/cron/index.d.ts.map +1 -0
  215. package/build/types/cron/node-cron.d.ts +33 -0
  216. package/build/types/cron/node-cron.d.ts.map +1 -0
  217. package/build/types/cron/node-schedule.d.ts +19 -0
  218. package/build/types/cron/node-schedule.d.ts.map +1 -0
  219. package/build/types/index.d.ts +5 -2
  220. package/build/types/index.d.ts.map +1 -1
  221. package/build/types/integrations/anthropic.d.ts +2 -1
  222. package/build/types/integrations/anthropic.d.ts.map +1 -1
  223. package/build/types/integrations/aws-sdk/index.d.ts +3 -3
  224. package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
  225. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
  226. package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
  227. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
  228. package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
  229. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
  230. package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
  231. package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
  232. package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
  233. package/build/types/integrations/bullmq/index.d.ts +43 -0
  234. package/build/types/integrations/bullmq/index.d.ts.map +1 -0
  235. package/build/types/integrations/bullmq/meter.d.ts +7 -0
  236. package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
  237. package/build/types/integrations/bullmq/span.d.ts +35 -0
  238. package/build/types/integrations/bullmq/span.d.ts.map +1 -0
  239. package/build/types/integrations/bullmq/tracer.d.ts +5 -0
  240. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
  241. package/build/types/integrations/bullmq/types.d.ts +72 -0
  242. package/build/types/integrations/bullmq/types.d.ts.map +1 -0
  243. package/build/types/integrations/express/types.d.ts +1 -0
  244. package/build/types/integrations/express/types.d.ts.map +1 -1
  245. package/build/types/integrations/flue.d.ts +2 -1
  246. package/build/types/integrations/flue.d.ts.map +1 -1
  247. package/build/types/integrations/google-genai.d.ts +2 -1
  248. package/build/types/integrations/google-genai.d.ts.map +1 -1
  249. package/build/types/integrations/groq.d.ts +1 -1
  250. package/build/types/integrations/langchain.d.ts +2 -1
  251. package/build/types/integrations/langchain.d.ts.map +1 -1
  252. package/build/types/integrations/langgraph.d.ts +2 -1
  253. package/build/types/integrations/langgraph.d.ts.map +1 -1
  254. package/build/types/integrations/mistral.d.ts +2 -1
  255. package/build/types/integrations/mistral.d.ts.map +1 -1
  256. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  257. package/build/types/integrations/openai.d.ts +2 -1
  258. package/build/types/integrations/openai.d.ts.map +1 -1
  259. package/build/types/integrations/pi-ai.d.ts +6 -3
  260. package/build/types/integrations/pi-ai.d.ts.map +1 -1
  261. package/build/types/integrations/pi-durable.d.ts +2 -1
  262. package/build/types/integrations/pi-durable.d.ts.map +1 -1
  263. package/build/types/integrations/pino.d.ts +61 -0
  264. package/build/types/integrations/pino.d.ts.map +1 -0
  265. package/build/types/integrations/together-ai.d.ts +1 -1
  266. package/build/types/integrations/typesafe.d.ts +2 -2
  267. package/build/types/integrations/typesafe.d.ts.map +1 -1
  268. package/build/types/integrations/vercel-ai/index.d.ts +3 -3
  269. package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
  270. package/build/types/integrations/vercel-ai/util.d.ts +2 -1
  271. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  272. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
  273. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  274. package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
  275. package/build/types/integrations/winston.d.ts +55 -0
  276. package/build/types/integrations/winston.d.ts.map +1 -0
  277. package/package.json +3 -3
@@ -0,0 +1,114 @@
1
+ import { MESSAGING_BATCH_MESSAGE_COUNT, MESSAGING_BULLMQ_FLOW_NAME, MESSAGING_BULLMQ_JOB_ATTEMPT_FINISHED_TIMESTAMP, MESSAGING_BULLMQ_JOB_BULK_NAMES, MESSAGING_BULLMQ_JOB_DEDUPLICATION_KEY, MESSAGING_BULLMQ_JOB_IDS, MESSAGING_BULLMQ_JOB_KEY, MESSAGING_BULLMQ_JOB_NAME, MESSAGING_BULLMQ_JOB_PROCESSED_TIMESTAMP, MESSAGING_BULLMQ_JOB_SCHEDULER_ID, MESSAGING_BULLMQ_JOB_STATE, MESSAGING_BULLMQ_JOB_TYPE, MESSAGING_BULLMQ_QUEUE_CLEAN_COUNT, MESSAGING_BULLMQ_QUEUE_CLEAN_LIMIT, MESSAGING_BULLMQ_QUEUE_DRAIN_DELAY, MESSAGING_BULLMQ_QUEUE_EVENT_MAX_LENGTH, MESSAGING_BULLMQ_QUEUE_GRACE, MESSAGING_BULLMQ_QUEUE_JOBS_STATE, MESSAGING_BULLMQ_QUEUE_RATE_LIMIT, MESSAGING_BULLMQ_WORKER_DO_NOT_WAIT_ACTIVE, MESSAGING_BULLMQ_WORKER_FORCE_CLOSE, MESSAGING_BULLMQ_WORKER_JOBS_TO_EXTEND_LOCKS, MESSAGING_BULLMQ_WORKER_NAME, MESSAGING_BULLMQ_WORKER_RATE_LIMIT, MESSAGING_BULLMQ_WORKER_STALLED_JOBS, MESSAGING_CLIENT_ID, MESSAGING_DESTINATION_NAME, MESSAGING_MESSAGE_ID, MESSAGING_MESSAGE_RETRY_COUNT, MESSAGING_OPERATION_NAME } from "@sentry/conventions/attributes";
2
+ import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
3
+ // src/integrations/bullmq/span.ts
4
+ const DROPPED_ATTRIBUTES = /* @__PURE__ */ new Set([
5
+ "bullmq.job.options",
6
+ "bullmq.job.progress",
7
+ "bullmq.queue.options",
8
+ "bullmq.worker.options",
9
+ "bullmq.job.finished.timestamp"
10
+ ]);
11
+ const MESSAGING_BULLMQ_KEYS = /* @__PURE__ */ new Map([
12
+ ["bullmq.flow.name", MESSAGING_BULLMQ_FLOW_NAME],
13
+ ["bullmq.job.attempt_finished_timestamp", MESSAGING_BULLMQ_JOB_ATTEMPT_FINISHED_TIMESTAMP],
14
+ ["bullmq.job.bulk.names", MESSAGING_BULLMQ_JOB_BULK_NAMES],
15
+ ["bullmq.job.deduplication.key", MESSAGING_BULLMQ_JOB_DEDUPLICATION_KEY],
16
+ ["bullmq.job.ids", MESSAGING_BULLMQ_JOB_IDS],
17
+ ["bullmq.job.key", MESSAGING_BULLMQ_JOB_KEY],
18
+ ["bullmq.job.name", MESSAGING_BULLMQ_JOB_NAME],
19
+ ["bullmq.job.processed.timestamp", MESSAGING_BULLMQ_JOB_PROCESSED_TIMESTAMP],
20
+ ["bullmq.job.scheduler.id", MESSAGING_BULLMQ_JOB_SCHEDULER_ID],
21
+ ["bullmq.job.type", MESSAGING_BULLMQ_JOB_TYPE],
22
+ ["bullmq.queue.clean.count", MESSAGING_BULLMQ_QUEUE_CLEAN_COUNT],
23
+ ["bullmq.queue.clean.limit", MESSAGING_BULLMQ_QUEUE_CLEAN_LIMIT],
24
+ ["bullmq.queue.drain.delay", MESSAGING_BULLMQ_QUEUE_DRAIN_DELAY],
25
+ ["bullmq.queue.event.max.length", MESSAGING_BULLMQ_QUEUE_EVENT_MAX_LENGTH],
26
+ ["bullmq.queue.grace", MESSAGING_BULLMQ_QUEUE_GRACE],
27
+ ["bullmq.queue.jobs.state", MESSAGING_BULLMQ_QUEUE_JOBS_STATE],
28
+ ["bullmq.queue.rate.limit", MESSAGING_BULLMQ_QUEUE_RATE_LIMIT],
29
+ ["bullmq.worker.do.not.wait.active", MESSAGING_BULLMQ_WORKER_DO_NOT_WAIT_ACTIVE],
30
+ ["bullmq.worker.force.close", MESSAGING_BULLMQ_WORKER_FORCE_CLOSE],
31
+ ["bullmq.worker.jobs.to.extend.locks", MESSAGING_BULLMQ_WORKER_JOBS_TO_EXTEND_LOCKS],
32
+ ["bullmq.worker.name", MESSAGING_BULLMQ_WORKER_NAME],
33
+ ["bullmq.worker.rate.limit", MESSAGING_BULLMQ_WORKER_RATE_LIMIT],
34
+ ["bullmq.worker.stalled.jobs", MESSAGING_BULLMQ_WORKER_STALLED_JOBS]
35
+ ]);
36
+ /**
37
+ * Returns the Sentry key for a `bullmq.*` attribute key or metric name: the key from `MESSAGING_BULLMQ_KEYS`, or
38
+ * `messaging.<key>` for the keys that are not in it, such as the metric names. Returns all other keys unchanged.
39
+ */
40
+ function toMessagingKey(key) {
41
+ return MESSAGING_BULLMQ_KEYS.get(key) ?? (key.startsWith("bullmq.") ? `messaging.${key}` : key);
42
+ }
43
+ /**
44
+ * Returns the BullMQ attributes with Sentry keys: the `messaging.*` convention where one exists, and the
45
+ * `messaging.bullmq.*` key for all others. The attributes that hold JSON strings and the deprecated ones are left out.
46
+ */
47
+ function toSentryAttributes(attributes) {
48
+ const { "bullmq.queue.name": queueName, "bullmq.queue.operation": operation, "bullmq.job.id": jobId, "bullmq.job.attempts.made": attemptsMade, "bullmq.job.bulk.count": bulkCount, "bullmq.worker.id": workerId, "bullmq.job.state": jobState, "bullmq.job.status": jobStatus, ...rest } = attributes;
49
+ const result = {};
50
+ for (const [key, value] of Object.entries(rest)) if (!DROPPED_ATTRIBUTES.has(key)) result[toMessagingKey(key)] = value;
51
+ if (typeof queueName === "string") result[MESSAGING_DESTINATION_NAME] = queueName;
52
+ if (typeof operation === "string") result[MESSAGING_OPERATION_NAME] = operation;
53
+ if (jobId !== void 0) result[MESSAGING_MESSAGE_ID] = String(jobId);
54
+ if (typeof attemptsMade === "number") result[MESSAGING_MESSAGE_RETRY_COUNT] = Math.max(attemptsMade - 1, 0);
55
+ if (typeof bulkCount === "number") result[MESSAGING_BATCH_MESSAGE_COUNT] = bulkCount;
56
+ if (typeof workerId === "string") result[MESSAGING_CLIENT_ID] = workerId;
57
+ const state = jobState ?? jobStatus;
58
+ if (typeof state === "string") result[MESSAGING_BULLMQ_JOB_STATE] = state;
59
+ return result;
60
+ }
61
+ var SentryBullMQSpan = class {
62
+ constructor(span, scope) {
63
+ this._span = span;
64
+ this._scope = scope;
65
+ }
66
+ setAttribute(key, value) {
67
+ this.setAttributes({ [key]: value });
68
+ }
69
+ setAttributes(attributes) {
70
+ this._span.setAttributes(toSentryAttributes(attributes));
71
+ }
72
+ addEvent(name, attributes) {
73
+ this._span.addEvent(name, attributes);
74
+ if (name === "job failed") {
75
+ this._span.setStatus({
76
+ code: SPAN_STATUS_ERROR,
77
+ message: "internal_error"
78
+ });
79
+ let error = this._recordedError;
80
+ this._recordedError = void 0;
81
+ if (!error) {
82
+ error = new Error(String(attributes?.["bullmq.job.failed.reason"] || "Unknown error"));
83
+ error.stack = void 0;
84
+ }
85
+ captureException(error, { mechanism: {
86
+ handled: false,
87
+ type: "auto.queue.bullmq"
88
+ } });
89
+ }
90
+ }
91
+ /**
92
+ * Does not capture to Sentry. BullMQ calls this for Redis, lock and serialization errors that it
93
+ * retries itself, often several times for one fault, and for the job error right before the `job failed` event.
94
+ * Job failures are captured in `addEvent`.
95
+ */
96
+ recordException(exception) {
97
+ this._recordedError = exception instanceof Error ? exception : void 0;
98
+ const error = this._recordedError ?? new Error(typeof exception === "string" ? exception : exception.message || "Unknown error");
99
+ this._span.recordException(error);
100
+ }
101
+ setSpanOnContext(context) {
102
+ return {
103
+ ...context,
104
+ span: this._span,
105
+ scope: this._scope
106
+ };
107
+ }
108
+ end() {
109
+ this._span.end();
110
+ }
111
+ };
112
+ export { SentryBullMQSpan, toMessagingKey, toSentryAttributes };
113
+
114
+ //# sourceMappingURL=span.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span.js","names":[],"sources":["../../../../src/integrations/bullmq/span.ts"],"sourcesContent":["import type { Attributes, Span } from '@opentelemetry/api';\nimport {\n MESSAGING_BATCH_MESSAGE_COUNT,\n MESSAGING_BULLMQ_FLOW_NAME,\n MESSAGING_BULLMQ_JOB_ATTEMPT_FINISHED_TIMESTAMP,\n MESSAGING_BULLMQ_JOB_BULK_NAMES,\n MESSAGING_BULLMQ_JOB_DEDUPLICATION_KEY,\n MESSAGING_BULLMQ_JOB_IDS,\n MESSAGING_BULLMQ_JOB_KEY,\n MESSAGING_BULLMQ_JOB_NAME,\n MESSAGING_BULLMQ_JOB_PROCESSED_TIMESTAMP,\n MESSAGING_BULLMQ_JOB_SCHEDULER_ID,\n MESSAGING_BULLMQ_JOB_STATE,\n MESSAGING_BULLMQ_JOB_TYPE,\n MESSAGING_BULLMQ_QUEUE_CLEAN_COUNT,\n MESSAGING_BULLMQ_QUEUE_CLEAN_LIMIT,\n MESSAGING_BULLMQ_QUEUE_DRAIN_DELAY,\n MESSAGING_BULLMQ_QUEUE_EVENT_MAX_LENGTH,\n MESSAGING_BULLMQ_QUEUE_GRACE,\n MESSAGING_BULLMQ_QUEUE_JOBS_STATE,\n MESSAGING_BULLMQ_QUEUE_RATE_LIMIT,\n MESSAGING_BULLMQ_WORKER_DO_NOT_WAIT_ACTIVE,\n MESSAGING_BULLMQ_WORKER_FORCE_CLOSE,\n MESSAGING_BULLMQ_WORKER_JOBS_TO_EXTEND_LOCKS,\n MESSAGING_BULLMQ_WORKER_NAME,\n MESSAGING_BULLMQ_WORKER_RATE_LIMIT,\n MESSAGING_BULLMQ_WORKER_STALLED_JOBS,\n MESSAGING_CLIENT_ID,\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_ID,\n MESSAGING_MESSAGE_RETRY_COUNT,\n MESSAGING_OPERATION_NAME,\n} from '@sentry/conventions/attributes';\nimport type { Scope } from '@sentry/core';\nimport { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { AttributeValue, TelemetrySpan } from './types';\n\nconst DROPPED_ATTRIBUTES = new Set([\n // BullMQ sets these to `JSON.stringify()` output. They are left out until Sentry attributes support objects.\n 'bullmq.job.options',\n 'bullmq.job.progress',\n 'bullmq.queue.options',\n 'bullmq.worker.options',\n // BullMQ deprecated this for `bullmq.job.attempt_finished_timestamp`, which it sets on the same spans.\n 'bullmq.job.finished.timestamp',\n]);\n\n// The BullMQ attribute keys and their `messaging.bullmq.*` keys in the Sentry conventions. Where BullMQ separates\n// the words of a key with dots, the Sentry key uses snake_case.\nconst MESSAGING_BULLMQ_KEYS = new Map([\n ['bullmq.flow.name', MESSAGING_BULLMQ_FLOW_NAME],\n ['bullmq.job.attempt_finished_timestamp', MESSAGING_BULLMQ_JOB_ATTEMPT_FINISHED_TIMESTAMP],\n ['bullmq.job.bulk.names', MESSAGING_BULLMQ_JOB_BULK_NAMES],\n ['bullmq.job.deduplication.key', MESSAGING_BULLMQ_JOB_DEDUPLICATION_KEY],\n ['bullmq.job.ids', MESSAGING_BULLMQ_JOB_IDS],\n ['bullmq.job.key', MESSAGING_BULLMQ_JOB_KEY],\n ['bullmq.job.name', MESSAGING_BULLMQ_JOB_NAME],\n ['bullmq.job.processed.timestamp', MESSAGING_BULLMQ_JOB_PROCESSED_TIMESTAMP],\n ['bullmq.job.scheduler.id', MESSAGING_BULLMQ_JOB_SCHEDULER_ID],\n ['bullmq.job.type', MESSAGING_BULLMQ_JOB_TYPE],\n ['bullmq.queue.clean.count', MESSAGING_BULLMQ_QUEUE_CLEAN_COUNT],\n ['bullmq.queue.clean.limit', MESSAGING_BULLMQ_QUEUE_CLEAN_LIMIT],\n ['bullmq.queue.drain.delay', MESSAGING_BULLMQ_QUEUE_DRAIN_DELAY],\n ['bullmq.queue.event.max.length', MESSAGING_BULLMQ_QUEUE_EVENT_MAX_LENGTH],\n ['bullmq.queue.grace', MESSAGING_BULLMQ_QUEUE_GRACE],\n ['bullmq.queue.jobs.state', MESSAGING_BULLMQ_QUEUE_JOBS_STATE],\n ['bullmq.queue.rate.limit', MESSAGING_BULLMQ_QUEUE_RATE_LIMIT],\n ['bullmq.worker.do.not.wait.active', MESSAGING_BULLMQ_WORKER_DO_NOT_WAIT_ACTIVE],\n ['bullmq.worker.force.close', MESSAGING_BULLMQ_WORKER_FORCE_CLOSE],\n ['bullmq.worker.jobs.to.extend.locks', MESSAGING_BULLMQ_WORKER_JOBS_TO_EXTEND_LOCKS],\n ['bullmq.worker.name', MESSAGING_BULLMQ_WORKER_NAME],\n ['bullmq.worker.rate.limit', MESSAGING_BULLMQ_WORKER_RATE_LIMIT],\n ['bullmq.worker.stalled.jobs', MESSAGING_BULLMQ_WORKER_STALLED_JOBS],\n]);\n\n/**\n * Returns the Sentry key for a `bullmq.*` attribute key or metric name: the key from `MESSAGING_BULLMQ_KEYS`, or\n * `messaging.<key>` for the keys that are not in it, such as the metric names. Returns all other keys unchanged.\n */\nexport function toMessagingKey(key: string): string {\n return MESSAGING_BULLMQ_KEYS.get(key) ?? (key.startsWith('bullmq.') ? `messaging.${key}` : key);\n}\n\n/**\n * Returns the BullMQ attributes with Sentry keys: the `messaging.*` convention where one exists, and the\n * `messaging.bullmq.*` key for all others. The attributes that hold JSON strings and the deprecated ones are left out.\n */\nexport function toSentryAttributes(attributes: Record<string, AttributeValue>): Attributes {\n const {\n 'bullmq.queue.name': queueName,\n 'bullmq.queue.operation': operation,\n 'bullmq.job.id': jobId,\n 'bullmq.job.attempts.made': attemptsMade,\n 'bullmq.job.bulk.count': bulkCount,\n 'bullmq.worker.id': workerId,\n 'bullmq.job.state': jobState,\n 'bullmq.job.status': jobStatus,\n ...rest\n } = attributes;\n const result: Attributes = {};\n\n for (const [key, value] of Object.entries(rest)) {\n if (!DROPPED_ATTRIBUTES.has(key)) {\n result[toMessagingKey(key)] = value;\n }\n }\n\n if (typeof queueName === 'string') {\n result[MESSAGING_DESTINATION_NAME] = queueName;\n }\n\n if (typeof operation === 'string') {\n result[MESSAGING_OPERATION_NAME] = operation;\n }\n\n if (jobId !== undefined) {\n result[MESSAGING_MESSAGE_ID] = String(jobId);\n }\n\n // BullMQ counts the attempt that just finished in `attemptsMade`.\n if (typeof attemptsMade === 'number') {\n result[MESSAGING_MESSAGE_RETRY_COUNT] = Math.max(attemptsMade - 1, 0);\n }\n\n if (typeof bulkCount === 'number') {\n result[MESSAGING_BATCH_MESSAGE_COUNT] = bulkCount;\n }\n\n if (typeof workerId === 'string') {\n result[MESSAGING_CLIENT_ID] = workerId;\n }\n\n // BullMQ before 5.81.2 sets `bullmq.job.status` instead of `bullmq.job.state`.\n const state = jobState ?? jobStatus;\n if (typeof state === 'string') {\n result[MESSAGING_BULLMQ_JOB_STATE] = state;\n }\n\n return result;\n}\n\nexport class SentryBullMQSpan implements TelemetrySpan {\n private _span: Span;\n private _scope: Scope;\n private _recordedError: Error | undefined;\n\n public constructor(span: Span, scope: Scope) {\n this._span = span;\n this._scope = scope;\n }\n\n public setAttribute(key: string, value: AttributeValue): void {\n this.setAttributes({ [key]: value });\n }\n\n public setAttributes(attributes: Record<string, AttributeValue>): void {\n this._span.setAttributes(toSentryAttributes(attributes));\n }\n\n public addEvent(name: string, attributes?: Record<string, AttributeValue>): void {\n this._span.addEvent(name, attributes);\n\n // BullMQ sends this event from `Worker.handleFailed`, and the event name is not an exported constant:\n // https://github.com/taskforcesh/bullmq/blob/01b8b14a973984845dc0bbcefccf35b3ed30782d/src/classes/worker.ts#L1223-L1225\n if (name === 'job failed') {\n this._span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n\n // Since 6.7.5, BullMQ passes the job error to `recordException` right before this event\n // (https://github.com/taskforcesh/bullmq/pull/4915). Older versions pass only the error message.\n let error = this._recordedError;\n this._recordedError = undefined;\n if (!error) {\n error = new Error(String(attributes?.['bullmq.job.failed.reason'] || 'Unknown error'));\n // This stack has only BullMQ and SDK frames, the same for every job. Without it, Sentry groups the errors by\n // their message.\n error.stack = undefined;\n }\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.queue.bullmq',\n },\n });\n }\n }\n\n /**\n * Does not capture to Sentry. BullMQ calls this for Redis, lock and serialization errors that it\n * retries itself, often several times for one fault, and for the job error right before the `job failed` event.\n * Job failures are captured in `addEvent`.\n */\n public recordException(exception: Error | string | { code?: number; message?: string; name?: string }): void {\n // BullMQ passes the retried errors as strings, so only the job error is kept.\n this._recordedError = exception instanceof Error ? exception : undefined;\n const error =\n this._recordedError ??\n new Error(typeof exception === 'string' ? exception : exception.message || 'Unknown error');\n\n this._span.recordException(error);\n }\n\n public setSpanOnContext(context: unknown): unknown {\n return {\n ...(context as object),\n span: this._span,\n scope: this._scope,\n };\n }\n\n public end(): void {\n this._span.end();\n }\n}\n"],"mappings":";;;AAqCA,MAAM,qCAAqB,IAAI,IAAI;CAEjC;CACA;CACA;CACA;CAEA;AACF,CAAC;AAID,MAAM,wCAAwB,IAAI,IAAI;CACpC,CAAC,oBAAoB,0BAA0B;CAC/C,CAAC,yCAAyC,+CAA+C;CACzF,CAAC,yBAAyB,+BAA+B;CACzD,CAAC,gCAAgC,sCAAsC;CACvE,CAAC,kBAAkB,wBAAwB;CAC3C,CAAC,kBAAkB,wBAAwB;CAC3C,CAAC,mBAAmB,yBAAyB;CAC7C,CAAC,kCAAkC,wCAAwC;CAC3E,CAAC,2BAA2B,iCAAiC;CAC7D,CAAC,mBAAmB,yBAAyB;CAC7C,CAAC,4BAA4B,kCAAkC;CAC/D,CAAC,4BAA4B,kCAAkC;CAC/D,CAAC,4BAA4B,kCAAkC;CAC/D,CAAC,iCAAiC,uCAAuC;CACzE,CAAC,sBAAsB,4BAA4B;CACnD,CAAC,2BAA2B,iCAAiC;CAC7D,CAAC,2BAA2B,iCAAiC;CAC7D,CAAC,oCAAoC,0CAA0C;CAC/E,CAAC,6BAA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CACzD;CAEO,SAAS,MAAc,YAAmD;EAC/E,KAAK,MAAM,SAAS,MAAM,UAAU;EAIpC,IAAI,SAAS,cAAc;GACzB,KAAK,MAAM,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAiB,CAAC;GAI3E,IAAI,QAAQ,KAAK;GACjB,KAAK,iBAAiB,KAAA;GACtB,IAAI,CAAC,OAAO;IACV,QAAQ,IAAI,MAAM,OAAO,aAAa,+BAA+B,eAAe,CAAC;IAGrF,MAAM,QAAQ,KAAA;GAChB;GACA,iBAAiB,OAAO,EACtB,WAAW;IACT,SAAS;IACT,MAAM;GACR,EACF,CAAC;EACH;CACF;;;;;;CAOO,gBAAgB,WAAsF;EAE3G,KAAK,iBAAiB,qBAAqB,QAAQ,YAAY,KAAA;EAC/D,MAAM,QACJ,KAAK,kBACL,IAAI,MAAM,OAAO,cAAc,WAAW,YAAY,UAAU,WAAW,eAAe;EAE5F,KAAK,MAAM,gBAAgB,KAAK;CAClC;CAEO,iBAAiB,SAA2B;EACjD,OAAO;GACL,GAAI;GACJ,MAAM,KAAK;GACX,OAAO,KAAK;EACd;CACF;CAEO,MAAY;EACjB,KAAK,MAAM,IAAI;CACjB;AACF"}
@@ -0,0 +1,62 @@
1
+ import { SentryBullMQSpan, toSentryAttributes } from "./span.js";
2
+ import { MESSAGING_SYSTEM, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
3
+ import { getCurrentScope, startInactiveSpan, startNewTrace } from "@sentry/core";
4
+ import { QUEUE, QUEUE_PROCESS, QUEUE_PUBLISH } from "@sentry/conventions/op";
5
+ // src/integrations/bullmq/tracer.ts
6
+ const PRODUCER_OPERATIONS = /* @__PURE__ */ new Set([
7
+ "add",
8
+ "addbulk",
9
+ "addflow",
10
+ "addbulkflows"
11
+ ]);
12
+ const CONSUMER_OPERATIONS = /* @__PURE__ */ new Set(["process"]);
13
+ function getOperation(name) {
14
+ return name.split(" ")[0].toLowerCase();
15
+ }
16
+ function getOpFromSpanName(name) {
17
+ const operation = getOperation(name);
18
+ if (CONSUMER_OPERATIONS.has(operation)) return QUEUE_PROCESS;
19
+ if (PRODUCER_OPERATIONS.has(operation)) return QUEUE_PUBLISH;
20
+ return QUEUE;
21
+ }
22
+ function getOriginFromSpanName(name) {
23
+ const operation = getOperation(name);
24
+ if (CONSUMER_OPERATIONS.has(operation)) return "auto.queue.bullmq.consumer";
25
+ if (PRODUCER_OPERATIONS.has(operation)) return "auto.queue.bullmq.producer";
26
+ return "auto.queue.bullmq";
27
+ }
28
+ var SentryBullMQTracer = class {
29
+ startSpan(name, options, context) {
30
+ const op = getOpFromSpanName(name);
31
+ const origin = getOriginFromSpanName(name);
32
+ const attributes = {
33
+ [SENTRY_OP]: op,
34
+ [SENTRY_ORIGIN]: origin,
35
+ [MESSAGING_SYSTEM]: "bullmq",
36
+ ...options?.attributes && toSentryAttributes(options.attributes)
37
+ };
38
+ const span = op === QUEUE_PROCESS ? startNewTrace(() => startInactiveSpan({
39
+ name,
40
+ attributes
41
+ })) : startInactiveSpan({
42
+ name,
43
+ attributes,
44
+ onlyIfParent: op === QUEUE
45
+ });
46
+ if (context?.producerSpanContext) {
47
+ const producerSpanCtx = {
48
+ traceId: context.producerSpanContext.traceId,
49
+ spanId: context.producerSpanContext.spanId,
50
+ traceFlags: context.producerSpanContext.sampled ? 1 : 0
51
+ };
52
+ span.addLink({
53
+ context: producerSpanCtx,
54
+ attributes: { [SENTRY_LINK_TYPE]: "message_origin" }
55
+ });
56
+ }
57
+ return new SentryBullMQSpan(span, getCurrentScope());
58
+ }
59
+ };
60
+ export { SentryBullMQTracer };
61
+
62
+ //# sourceMappingURL=tracer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.js","names":[],"sources":["../../../../src/integrations/bullmq/tracer.ts"],"sourcesContent":["import { MESSAGING_SYSTEM, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { QUEUE, QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getCurrentScope, startInactiveSpan, startNewTrace } from '@sentry/core';\nimport { SentryBullMQSpan, toSentryAttributes } from './span';\nimport type { SpanOptions, TelemetrySpan, Tracer, SentryContext } from './types';\n\n// BullMQ span names follow OTel messaging semconv: \"{operation} {destination}\"\n// e.g. \"add myQueue\", \"addBulk myQueue\", \"process myQueue\", \"addFlow myQueue\"\nconst PRODUCER_OPERATIONS = new Set(['add', 'addbulk', 'addflow', 'addbulkflows']);\nconst CONSUMER_OPERATIONS = new Set(['process']);\n\nfunction getOperation(name: string): string {\n return name.split(' ')[0]!.toLowerCase();\n}\n\nfunction getOpFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return QUEUE_PROCESS;\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return QUEUE_PUBLISH;\n }\n\n return QUEUE;\n}\n\nfunction getOriginFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.consumer';\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.producer';\n }\n\n return 'auto.queue.bullmq';\n}\n\nexport class SentryBullMQTracer implements Tracer<SentryContext> {\n public startSpan(name: string, options?: SpanOptions, context?: SentryContext): TelemetrySpan {\n const op = getOpFromSpanName(name);\n const origin = getOriginFromSpanName(name);\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: origin,\n [MESSAGING_SYSTEM]: 'bullmq',\n ...(options?.attributes && toSentryAttributes(options.attributes)),\n };\n\n // Internal operations such as `moveStalledJobsToWait` run on timers. Without a parent, each tick would start a new root span.\n const span =\n op === QUEUE_PROCESS\n ? startNewTrace(() => startInactiveSpan({ name, attributes }))\n : startInactiveSpan({ name, attributes, onlyIfParent: op === QUEUE });\n\n if (context?.producerSpanContext) {\n const producerSpanCtx = {\n traceId: context.producerSpanContext.traceId,\n spanId: context.producerSpanContext.spanId,\n traceFlags: context.producerSpanContext.sampled ? 1 : 0,\n };\n\n span.addLink({\n context: producerSpanCtx,\n attributes: {\n [SENTRY_LINK_TYPE]: 'message_origin',\n },\n });\n }\n\n return new SentryBullMQSpan(span, getCurrentScope());\n }\n}\n"],"mappings":";;;;;AASA,MAAM,sCAAsB,IAAI,IAAI;CAAC;CAAO;CAAW;CAAW;AAAc,CAAC;AACjF,MAAM,sCAAsB,IAAI,IAAI,CAAC,SAAS,CAAC;AAE/C,SAAS,aAAa,MAAsB;CAC1C,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,YAAY;AACzC;AAEA,SAAS,kBAAkB,MAAsB;CAC/C,MAAM,YAAY,aAAa,IAAI;CAEnC,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,OAAO;AACT;AAEA,SAAS,sBAAsB,MAAsB;CACnD,MAAM,YAAY,aAAa,IAAI;CAEnC,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,OAAO;AACT;AAEA,IAAa,qBAAb,MAAiE;CACxD,UAAU,MAAc,SAAuB,SAAwC;EAC5F,MAAM,KAAK,kBAAkB,IAAI;EACjC,MAAM,SAAS,sBAAsB,IAAI;EAEzC,MAAM,aAA6B;IAChC,YAAY;IACZ,gBAAgB;IAChB,mBAAmB;GACpB,GAAI,SAAS,cAAc,mBAAmB,QAAQ,UAAU;EAClE;EAGA,MAAM,OACJ,OAAO,gBACH,oBAAoB,kBAAkB;GAAE;GAAM;EAAW,CAAC,CAAC,IAC3D,kBAAkB;GAAE;GAAM;GAAY,cAAc,OAAO;EAAM,CAAC;EAExE,IAAI,SAAS,qBAAqB;GAChC,MAAM,kBAAkB;IACtB,SAAS,QAAQ,oBAAoB;IACrC,QAAQ,QAAQ,oBAAoB;IACpC,YAAY,QAAQ,oBAAoB,UAAU,IAAI;GACxD;GAEA,KAAK,QAAQ;IACX,SAAS;IACT,YAAY,GACT,mBAAmB,iBACtB;GACF,CAAC;EACH;EAEA,OAAO,IAAI,iBAAiB,MAAM,gBAAgB,CAAC;CACrD;AACF"}
@@ -127,7 +127,7 @@ function getSpanForLayer(data, options) {
127
127
  if (!req) return;
128
128
  if (!getActiveSpan()) return;
129
129
  const type = getLayerType(layer);
130
- const registeredPath = getLayerRegisteredPath(layer);
130
+ const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);
131
131
  if (registeredPath != null) {
132
132
  pushLayerPath(req, registeredPath);
133
133
  data._sentryStoredLayer = true;
@@ -179,6 +179,15 @@ function getSpanForLayer(data, options) {
179
179
  }
180
180
  return span;
181
181
  }
182
+ /**
183
+ * The path of a matched layer for which no registration event recorded a path. That is the case when the events
184
+ * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first
185
+ * request.
186
+ */
187
+ function getMatchedLayerPath(layer) {
188
+ if (layer.route) return getLayerPath([layer.route.path]);
189
+ return layer.keys?.length ? void 0 : layer.path || void 0;
190
+ }
182
191
  function getLayerType(layer) {
183
192
  if (layer.name === "router") return "router";
184
193
  if (layer.name === "bound dispatch" || layer.name === "handle") return "request_handler";
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,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IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,S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Y;IACT,gBAAgB;IAChB,YAAY,wBAAwB;IACpC,oBAAoB;IACpB,oBAAoB;IACpB,aAAa;EAChB;CACF,CAAC;CASD,IAAI,OAAO,OAAO,IAAI,SAAS,YAAY;EACzC,MAAM,gBAAsB;GAC1B,IAAI,eAAe,UAAU,QAAQ;GACrC,IAAI,eAAe,SAAS,OAAO;EACrC;EACA,MAAM,iBAAuB;GAC3B,QAAQ;GACR,KAAK,IAAI;EACX;EACA,MAAM,gBAAsB;GAC1B,QAAQ;GACR,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAY,CAAC;GAChE,KAAK,IAAI;EACX;EACA,IAAI,KAAK,UAAU,QAAQ;EAC3B,IAAI,KAAK,SAAS,OAAO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -1,5 +1,6 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
- import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from "../ai/core/utils.js";
2
+ import { getGenAiSpanOp, markCancelledIfAborted, resolveGenAiCallRecording } from "../ai/core/utils.js";
3
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
3
4
  import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes, getAbortSignal, getCallAbortSignal, resolveChatParams } from "../ai/google-genai/index.js";
4
5
  import { shouldSkipAiProviderSpan } from "../ai/pi-ai/providers.js";
5
6
  import { instrumentStream } from "../ai/google-genai/streaming.js";
@@ -45,9 +46,10 @@ function instrumentGoogleGenai(options) {
45
46
  const params = resolveChatParams(operation, data.arguments?.[0], data.self);
46
47
  markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));
47
48
  }
48
- if (operation !== "embeddings") addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs, operation);
49
+ if (operation !== "embeddings") addResponseAttributes(span, data.result, !!data._sentryRecordOutputs, operation);
50
+ data._sentryOnSpanEnd?.("error" in data ? { error: data.error } : { response: data.result });
49
51
  },
50
- deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options)
52
+ deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation)
51
53
  });
52
54
  }
53
55
  /**
@@ -63,9 +65,14 @@ function createGenAiSpan(data, operation, options) {
63
65
  if (origin === ORIGIN && op === "gen_ai.chat") return;
64
66
  }
65
67
  }
66
- const args = data.arguments ?? [];
67
- const params = resolveChatParams(operation, args[0], data.self);
68
- const { recordInputs } = resolveAIRecordingOptions(options);
68
+ const request = (data.arguments ?? [])[0];
69
+ const params = resolveChatParams(operation, request, data.self);
70
+ const call = {
71
+ operation,
72
+ request
73
+ };
74
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
75
+ data._sentryRecordOutputs = recordOutputs;
69
76
  const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);
70
77
  const model = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
71
78
  attributes[SENTRY_ORIGIN] = ORIGIN;
@@ -76,6 +83,8 @@ function createGenAiSpan(data, operation, options) {
76
83
  attributes
77
84
  });
78
85
  if (recordInputs && params) addPrivateRequestAttributes(span, params, operation);
86
+ runGenAiSpanStart(options, span, call);
87
+ data._sentryOnSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
79
88
  return span;
80
89
  }
81
90
  function isAsyncIterable(value) {
@@ -86,13 +95,12 @@ function isAsyncIterable(value) {
86
95
  * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the
87
96
  * span when iteration finishes.
88
97
  */
89
- function wrapStreamResult(span, data, operation, options) {
98
+ function wrapStreamResult(span, data, operation) {
90
99
  const result = data.result;
91
100
  if (!isAsyncIterable(result)) return false;
92
- const { recordOutputs } = resolveAIRecordingOptions(options);
93
101
  const iterate = result[Symbol.asyncIterator].bind(result);
94
102
  const params = resolveChatParams(operation, data.arguments?.[0], data.self);
95
- const instrumented = instrumentStream({ [Symbol.asyncIterator]: iterate }, span, recordOutputs ?? false, getAbortSignal(params));
103
+ const instrumented = instrumentStream({ [Symbol.asyncIterator]: iterate }, span, !!data._sentryRecordOutputs, getAbortSignal(params), data._sentryOnSpanEnd);
96
104
  result[Symbol.asyncIterator] = () => instrumented;
97
105
  return true;
98
106
  }
@@ -1 +1 @@
1
- {"version":3,"file":"google-genai.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/google-genai.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n defineIntegration,\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport {\n addPrivateRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getAbortSignal,\n getCallAbortSignal,\n resolveChatParams,\n} from '../ai/google-genai';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport { instrumentStream } from '../ai/google-genai/streaming';\nimport type { GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { googleGenAiModuleNames } from '../orchestrion/config/google-genai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Google_GenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Google_GenAI' as const;\n\nconst ORIGIN = 'auto.ai.google_genai';\n\n// Each instrumented method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT, operation: 'generate_content' },\n { channel: CHANNELS.GOOGLE_GENAI_EMBED_CONTENT, operation: 'embeddings' },\n { channel: CHANNELS.GOOGLE_GENAI_CHAT, operation: 'chat' },\n { channel: CHANNELS.GOOGLE_GENAI_DECIDE, operation: 'decide' },\n] as const;\n\nconst _googleGenAIIntegration = ((options: GoogleGenAIOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, googleGenAiModuleNames, instrumentGoogleGenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGoogleGenai(options: GoogleGenAIOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n const params = resolveChatParams(\n operation,\n data.arguments?.[0] as Record<string, unknown> | undefined,\n data.self,\n );\n markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));\n }\n // Embeddings responses carry no content attributes.\n if (operation !== 'embeddings') {\n addResponseAttributes(\n span,\n data.result as GoogleGenAIResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n operation,\n );\n }\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `chat.sendMessage()`/`sendMessageStream()` internally call `Models.generateContent(Stream)`, which\n // publishes the `generate-content` channel while the chat span is active. Skip that nested event so a\n // chat call yields a single `gen_ai.chat` span instead of a chat span wrapping a generate_content one.\n if (operation !== 'chat') {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const {\n attributes: { [SENTRY_OP]: op, [SENTRY_ORIGIN]: origin },\n } = spanToJSON(activeSpan);\n if (origin === ORIGIN && op === 'gen_ai.chat') {\n return undefined;\n }\n }\n }\n\n const args = data.arguments ?? [];\n // `chat.sendMessage()` carries no config of its own unless the caller passes one, so recover the\n // one `chats.create()` left on the chat instance that the transform stashed in `data.self`.\n const params = resolveChatParams(operation, args[0] as Record<string, unknown> | undefined, data.self);\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * Only the streaming methods (`generateContentStream`/`sendMessageStream`) resolve to an async iterable.\n * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the\n * span when iteration finishes.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const params = resolveChatParams(operation, data.arguments?.[0] as Record<string, unknown> | undefined, data.self);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs ?? false,\n getAbortSignal(params),\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based Google GenAI integration. Subscribes to the\n * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`\n * (`generateContent`/`generateContentStream`/`embedContent`), `Chat`\n * (`sendMessage`/`sendMessageStream`) and decisions (`create`) methods, so it requires the Sentry\n * runtime hook or bundler plugin.\n */\nexport const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,mBAAmB;AAEzB,MAAM,SAAS;AAGf,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAA+B,WAAW;CAAmB;CACjF;EAAE,SAAS,SAAS;EAA4B,WAAW;CAAa;CACxE;EAAE,SAAS,SAAS;EAAmB,WAAW;CAAO;CACzD;EAAE,SAAS,SAAS;EAAqB,WAAW;CAAS;AAC/D;AAEA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,uB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AClB,4BAA4B,MAAM,QAAQ,SAAS;CAGrD,OAAO;AACT;AAIA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;;;;;;AAOA,SAAS,iBACP,MACA,MACA,WACA,SACS;CACT,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,gBAAgB,MAAM,GACzB,OAAO;CAGT,MAAM,EAAE,kBAAkB,0BAA0B,OAAO;CAC3D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;CACxD,MAAM,SAAS,kBAAkB,WAAW,KAAK,YAAY,IAA2C,KAAK,IAAI;CACjH,MAAM,eAAe,iBACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,iBAAiB,OACjB,eAAe,MAAM,CACvB;CACA,OAAO,OAAO,uBAAuB;CAErC,OAAO;AACT;;;;;;;;AASA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
1
+ {"version":3,"file":"google-genai.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/google-genai.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n defineIntegration,\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport {\n addPrivateRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getAbortSignal,\n getCallAbortSignal,\n resolveChatParams,\n} from '../ai/google-genai';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport { instrumentStream } from '../ai/google-genai/streaming';\nimport type { GoogleGenAICallInfo, GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { googleGenAiModuleNames } from '../orchestrion/config/google-genai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Google_GenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Google_GenAI' as const;\n\nconst ORIGIN = 'auto.ai.google_genai';\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype GoogleGenAIChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// Each instrumented method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT, operation: 'generate_content' },\n { channel: CHANNELS.GOOGLE_GENAI_EMBED_CONTENT, operation: 'embeddings' },\n { channel: CHANNELS.GOOGLE_GENAI_CHAT, operation: 'chat' },\n { channel: CHANNELS.GOOGLE_GENAI_DECIDE, operation: 'decide' },\n] as const;\n\nconst _googleGenAIIntegration = ((options: GoogleGenAIOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, googleGenAiModuleNames, instrumentGoogleGenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGoogleGenai(options: GoogleGenAIOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<GoogleGenAIChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n const params = resolveChatParams(\n operation,\n data.arguments?.[0] as Record<string, unknown> | undefined,\n data.self,\n );\n markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));\n }\n // Embeddings responses carry no content attributes.\n if (operation !== 'embeddings') {\n addResponseAttributes(span, data.result as GoogleGenAIResponse, !!data._sentryRecordOutputs, operation);\n }\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: GoogleGenAIChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `chat.sendMessage()`/`sendMessageStream()` internally call `Models.generateContent(Stream)`, which\n // publishes the `generate-content` channel while the chat span is active. Skip that nested event so a\n // chat call yields a single `gen_ai.chat` span instead of a chat span wrapping a generate_content one.\n if (operation !== 'chat') {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const {\n attributes: { [SENTRY_OP]: op, [SENTRY_ORIGIN]: origin },\n } = spanToJSON(activeSpan);\n if (origin === ORIGIN && op === 'gen_ai.chat') {\n return undefined;\n }\n }\n }\n\n const args = data.arguments ?? [];\n // `chat.sendMessage()` carries no config of its own unless the caller passes one, so recover the\n // one `chats.create()` left on the chat instance that the transform stashed in `data.self`.\n const request = args[0] as Record<string, unknown> | undefined;\n const params = resolveChatParams(operation, request, data.self);\n\n const call: GoogleGenAICallInfo = { operation, request };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params, operation);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * Only the streaming methods (`generateContentStream`/`sendMessageStream`) resolve to an async iterable.\n * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the\n * span when iteration finishes.\n */\nfunction wrapStreamResult(span: Span, data: GoogleGenAIChannelContext, operation: string): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const iterate = result[Symbol.asyncIterator].bind(result);\n const params = resolveChatParams(operation, data.arguments?.[0] as Record<string, unknown> | undefined, data.self);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n !!data._sentryRecordOutputs,\n getAbortSignal(params),\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based Google GenAI integration. Subscribes to the\n * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`\n * (`generateContent`/`generateContentStream`/`embedContent`), `Chat`\n * (`sendMessage`/`sendMessageStream`) and decisions (`create`) methods, so it requires the Sentry\n * runtime hook or bundler plugin.\n */\nexport const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,mBAAmB;AAEzB,MAAM,SAAS;AASf,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAA+B,WAAW;CAAmB;CACjF;EAAE,SAAS,SAAS;EAA4B,WAAW;CAAa;CACxE;EAAE,SA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AAkB,0BAA0B,SAAS,IAAI;CAC/E,KAAK,uBAAuB;CAE5B,MAAM,aAAa,yBAAyB,WAAW,QAAQ,KAAK,MAAM,YAAY;CACtF,MAAM,QAAS,WAAW,yBAAoC;CAC9D,WAAW,iBAAiB;CAC5B,MAAM,SAAS,UAAU;CAEzB,MAAM,OAAO,kBAAkB;EAE7B,MAAM,UAAU,aAAa,EAAE,UAAU,wBAAwB,MAAM,KAAK,GAAG,UAAU,GAAG,UAAU;EACtG,IAAI,eAAe,SAAS;EAC5B;CACF,CAAC;CAED,IAAI,gBAAgB,QAClB,4BAA4B,MAAM,QAAQ,SAAS;CAGrD,kBAAkB,SAAS,MAAM,IAAI;CACrC,KAAK,oBAAmB,WAAU,gBAAgB,SAAS,MAAM,MAAM,MAAM;CAE7E,OAAO;AACT;AAIA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;;;;;;AAOA,SAAS,iBAAiB,MAAY,MAAiC,WAA4B;CACjG,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,gBAAgB,MAAM,GACzB,OAAO;CAGT,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;CACxD,MAAM,SAAS,kBAAkB,WAAW,KAAK,YAAY,IAA2C,KAAK,IAAI;CACjH,MAAM,eAAe,iBACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,CAAC,CAAC,KAAK,sBACP,eAAe,MAAM,GACrB,KAAK,gBACP;CACA,OAAO,OAAO,uBAAuB;CAErC,OAAO;AACT;;;;;;;;AASA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
@@ -1,9 +1,8 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
- import { resolveAIRecordingOptions } from "../ai/core/utils.js";
3
2
  import { createLangChainCallbackHandler } from "../ai/langchain/index.js";
4
3
  import { instrumentCompiledGraph, isInsideManualLangGraphInstrumentation } from "../ai/langgraph/index.js";
5
4
  import { LANGGRAPH_INTEGRATION_NAME } from "../ai/langgraph/constants.js";
6
- import { extractAgentNameFromParams, extractLLMFromParams, wrapToolsWithSpans } from "../ai/langgraph/utils.js";
5
+ import { extractAgentNameFromParams, extractLLMFromParams, getBooleanRecordingOptions, wrapToolsWithSpans } from "../ai/langgraph/utils.js";
7
6
  import { DEBUG_BUILD } from "../debug-build.js";
8
7
  import { CHANNELS } from "../orchestrion/channels.js";
9
8
  import { langgraphModuleNames } from "../orchestrion/config/langgraph.js";
@@ -21,12 +20,11 @@ const _langGraphIntegration = ((options = {}) => {
21
20
  };
22
21
  });
23
22
  function instrumentLanggraph(options) {
24
- const resolvedOptions = resolveAIRecordingOptions(options);
25
- const sentryHandler = createLangChainCallbackHandler(resolvedOptions);
23
+ const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));
26
24
  tracingChannel(CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE).end.subscribe((message) => {
27
25
  if (insideCreateReactAgent || isInsideManualLangGraphInstrumentation()) return;
28
26
  const { arguments: args, result } = message;
29
- instrumentCompiledGraph(result, getFirstArgObject(args) ?? {}, resolvedOptions, null, sentryHandler);
27
+ instrumentCompiledGraph(result, getFirstArgObject(args) ?? {}, options, null, sentryHandler);
30
28
  });
31
29
  const reactAgentChannel = tracingChannel(CHANNELS.LANGGRAPH_CREATE_REACT_AGENT);
32
30
  reactAgentChannel.start.subscribe((message) => {
@@ -34,7 +32,7 @@ function instrumentLanggraph(options) {
34
32
  try {
35
33
  const { arguments: args } = message;
36
34
  const params = getFirstArgObject(args);
37
- if (params && Array.isArray(params.tools) && params.tools.length > 0) wrapToolsWithSpans(params.tools, resolvedOptions, extractAgentNameFromParams(args) ?? void 0);
35
+ if (params && Array.isArray(params.tools) && params.tools.length > 0) wrapToolsWithSpans(params.tools, options, extractAgentNameFromParams(args) ?? void 0);
38
36
  } catch (error) {
39
37
  DEBUG_BUILD && debug.error("[instrumentation:langgraph] failed to wrap createReactAgent tools", error);
40
38
  }
@@ -44,7 +42,7 @@ function instrumentLanggraph(options) {
44
42
  if (isInsideManualLangGraphInstrumentation()) return;
45
43
  const { arguments: args, result } = message;
46
44
  const agentName = extractAgentNameFromParams(args) ?? void 0;
47
- instrumentCompiledGraph(result, agentName ? { name: agentName } : {}, resolvedOptions, extractLLMFromParams(args), sentryHandler);
45
+ instrumentCompiledGraph(result, agentName ? { name: agentName } : {}, options, extractLLMFromParams(args), sentryHandler);
48
46
  });
49
47
  reactAgentChannel.error.subscribe(() => {
50
48
  insideCreateReactAgent = false;
@@ -1 +1 @@
1
- {"version":3,"file":"langgraph.js","names":["diagnosticsChannel\n .tracingChannel","diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/langgraph.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, isObjectLike } from '@sentry/core';\nimport { resolveAIRecordingOptions } from '../ai/core/utils';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { instrumentCompiledGraph, isInsideManualLangGraphInstrumentation } from '../ai/langgraph';\nimport { LANGGRAPH_INTEGRATION_NAME } from '../ai/langgraph/constants';\nimport type { LangGraphOptions } from '../ai/langgraph/types';\nimport { extractAgentNameFromParams, extractLLMFromParams, wrapToolsWithSpans } from '../ai/langgraph/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langgraphModuleNames } from '../orchestrion/config/langgraph';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangGraph' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGGRAPH_INTEGRATION_NAME;\n\n// `createReactAgent` compiles a `StateGraph` internally. When set, the compile subscriber skips that nested\n// graph, so the createReactAgent handler wraps it with the agent's name and model instead.\nlet insideCreateReactAgent = false;\n\nconst _langGraphIntegration = ((options: LangGraphOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Nothing here opens a span at subscribe time, so a missing async-context\n // binding must never defer the subscription.\n invokeOrchestrionInstrumentation(client, langgraphModuleNames, instrumentLanggraph, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentLanggraph(options: LangGraphOptions): void {\n const resolvedOptions = resolveAIRecordingOptions(options);\n const sentryHandler = createLangChainCallbackHandler(resolvedOptions);\n\n // StateGraph.compile returns synchronously; wrap the returned graph's `invoke` and `stream` at `end`.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE)\n .end.subscribe(message => {\n if (insideCreateReactAgent || isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n instrumentCompiledGraph(result, getFirstArgObject(args) ?? {}, resolvedOptions, null, sentryHandler);\n });\n\n // createReactAgent only wraps tools and the returned graph's `invoke` and `stream`. Tools are wrapped at\n // `start` (before the agent runs), the graph at `end`.\n const reactAgentChannel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(\n CHANNELS.LANGGRAPH_CREATE_REACT_AGENT,\n );\n reactAgentChannel.start.subscribe(message => {\n // `createReactAgent` runs synchronously and compiles a `StateGraph` internally, so the flag\n // must be on for the duration and off by `end`. It's set here (never in a branch that can\n // throw) and cleared in both `end` and `error`, so it can neither stick on across calls nor\n // stay off during this call's nested compile. Tool wrapping is guarded for the same reason.\n insideCreateReactAgent = true;\n try {\n const { arguments: args } = message as OrchestrionChannelContext;\n const params = getFirstArgObject(args);\n if (params && Array.isArray(params.tools) && params.tools.length > 0) {\n wrapToolsWithSpans(params.tools, resolvedOptions, extractAgentNameFromParams(args) ?? undefined);\n }\n } catch (error) {\n DEBUG_BUILD && debug.error('[instrumentation:langgraph] failed to wrap createReactAgent tools', error);\n }\n });\n reactAgentChannel.end.subscribe(message => {\n insideCreateReactAgent = false;\n if (isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n const agentName = extractAgentNameFromParams(args) ?? undefined;\n const compileOptions = agentName ? { name: agentName } : {};\n instrumentCompiledGraph(result, compileOptions, resolvedOptions, extractLLMFromParams(args), sentryHandler);\n });\n // Make sure a thrown `createReactAgent` doesn't leave the suppression flag stuck on.\n reactAgentChannel.error.subscribe(() => {\n insideCreateReactAgent = false;\n });\n}\n\nfunction getFirstArgObject(args: unknown[] | undefined): Record<string, unknown> | undefined {\n const first = (args ?? [])[0];\n\n return isObjectLike(first) ? first : undefined;\n}\n\n/**\n * Diagnostics-channel-based LangGraph integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/langgraph`'s `StateGraph.compile` and `createReactAgent`, so it requires\n * the Sentry runtime hook or bundler plugin.\n */\nexport const langGraphIntegration = defineIntegration(_langGraphIntegration);\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,mBAAmB;AAIzB,IAAI,yBAAyB;AAE7B,MAAM,0BAA0B,UAA4B,CAAC,MAAM;CACjE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAGZ,iCAAiC,QAAQ,sBAAsB,qBAAqB,CAAC,OAAO,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,oBAAoB,SAAiC;CAC5D,MAAM,kBAAkB,0BAA0B,OAAO;CACzD,MAAM,gBAAgB,+BAA+B,eAAe;CAGpEA,eAC6C,SAAS,6BAA6B,CAAC,CACjF,IAAI,WAAU,YAAW;EACxB,IAAI,0BAA0B,uCAAuC,GACnE;EAEF,MAAM,EAAE,WAAW,MAAM,WAAW;EACpC,wBAAwB,QAAQ,kBAAkB,IAAI,KAAK,CAAC,GAAG,iBAAiB,MAAM,aAAa;CACrG,CAAC;CAIH,MAAM,oBAAoBC,eACxB,SAAS,4BACX;CACA,kBAAkB,MAAM,WAAU,YAAW;EAK3C,yBAAyB;EACzB,IAAI;GACF,MAAM,EAAE,WAAW,SAAS;GAC5B,MAAM,SAAS,kBAAkB,IAAI;GACrC,IAAI,UAAU,MAAM,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM,SAAS,GACjE,mBAAmB,OAAO,OAAO,iBAAiB,2BAA2B,IAAI,KAAK,KAAA,CAAS;EAEnG,SAAS,OAAO;GACd,eAAe,MAAM,MAAM,qEAAqE,KAAK;EACvG;CACF,CAAC;CACD,kBAAkB,IAAI,WAAU,YAAW;EACzC,yBAAyB;EACzB,IAAI,uCAAuC,GACzC;EAEF,MAAM,EAAE,WAAW,MAAM,WAAW;EACpC,MAAM,YAAY,2BAA2B,IAAI,KAAK,KAAA;EAEtD,wBAAwB,QADD,YAAY,EAAE,MAAM,UAAU,IAAI,CAAC,GACV,iBAAiB,qBAAqB,IAAI,GAAG,aAAa;CAC5G,CAAC;CAED,kBAAkB,MAAM,gBAAgB;EACtC,yBAAyB;CAC3B,CAAC;AACH;AAEA,SAAS,kBAAkB,MAAkE;CAC3F,MAAM,SAAS,QAAQ,CAAC,EAAA,CAAG;CAE3B,OAAO,aAAa,KAAK,IAAI,QAAQ,KAAA;AACvC;;;;;;AAOA,MAAa,uBAAuB,kBAAkB,qBAAqB"}
1
+ {"version":3,"file":"langgraph.js","names":["diagnosticsChannel\n .tracingChannel","diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/langgraph.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, isObjectLike } from '@sentry/core';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { instrumentCompiledGraph, isInsideManualLangGraphInstrumentation } from '../ai/langgraph';\nimport { LANGGRAPH_INTEGRATION_NAME } from '../ai/langgraph/constants';\nimport type { LangGraphOptions } from '../ai/langgraph/types';\nimport {\n extractAgentNameFromParams,\n extractLLMFromParams,\n getBooleanRecordingOptions,\n wrapToolsWithSpans,\n} from '../ai/langgraph/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langgraphModuleNames } from '../orchestrion/config/langgraph';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangGraph' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGGRAPH_INTEGRATION_NAME;\n\n// `createReactAgent` compiles a `StateGraph` internally. When set, the compile subscriber skips that nested\n// graph, so the createReactAgent handler wraps it with the agent's name and model instead.\nlet insideCreateReactAgent = false;\n\nconst _langGraphIntegration = ((options: LangGraphOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Nothing here opens a span at subscribe time, so a missing async-context\n // binding must never defer the subscription.\n invokeOrchestrionInstrumentation(client, langgraphModuleNames, instrumentLanggraph, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentLanggraph(options: LangGraphOptions): void {\n const sentryHandler = createLangChainCallbackHandler(getBooleanRecordingOptions(options));\n\n // StateGraph.compile returns synchronously; wrap the returned graph's `invoke` and `stream` at `end`.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE)\n .end.subscribe(message => {\n if (insideCreateReactAgent || isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n instrumentCompiledGraph(result, getFirstArgObject(args) ?? {}, options, null, sentryHandler);\n });\n\n // createReactAgent only wraps tools and the returned graph's `invoke` and `stream`. Tools are wrapped at\n // `start` (before the agent runs), the graph at `end`.\n const reactAgentChannel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(\n CHANNELS.LANGGRAPH_CREATE_REACT_AGENT,\n );\n reactAgentChannel.start.subscribe(message => {\n // `createReactAgent` runs synchronously and compiles a `StateGraph` internally, so the flag\n // must be on for the duration and off by `end`. It's set here (never in a branch that can\n // throw) and cleared in both `end` and `error`, so it can neither stick on across calls nor\n // stay off during this call's nested compile. Tool wrapping is guarded for the same reason.\n insideCreateReactAgent = true;\n try {\n const { arguments: args } = message as OrchestrionChannelContext;\n const params = getFirstArgObject(args);\n if (params && Array.isArray(params.tools) && params.tools.length > 0) {\n wrapToolsWithSpans(params.tools, options, extractAgentNameFromParams(args) ?? undefined);\n }\n } catch (error) {\n DEBUG_BUILD && debug.error('[instrumentation:langgraph] failed to wrap createReactAgent tools', error);\n }\n });\n reactAgentChannel.end.subscribe(message => {\n insideCreateReactAgent = false;\n if (isInsideManualLangGraphInstrumentation()) {\n return;\n }\n const { arguments: args, result } = message as OrchestrionChannelContext;\n const agentName = extractAgentNameFromParams(args) ?? undefined;\n const compileOptions = agentName ? { name: agentName } : {};\n instrumentCompiledGraph(result, compileOptions, options, extractLLMFromParams(args), sentryHandler);\n });\n // Make sure a thrown `createReactAgent` doesn't leave the suppression flag stuck on.\n reactAgentChannel.error.subscribe(() => {\n insideCreateReactAgent = false;\n });\n}\n\nfunction getFirstArgObject(args: unknown[] | undefined): Record<string, unknown> | undefined {\n const first = (args ?? [])[0];\n\n return isObjectLike(first) ? first : undefined;\n}\n\n/**\n * Diagnostics-channel-based LangGraph integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/langgraph`'s `StateGraph.compile` and `createReactAgent`, so it requires\n * the Sentry runtime hook or bundler plugin.\n */\nexport const langGraphIntegration = defineIntegration(_langGraphIntegration);\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,mBAAmB;AAIzB,IAAI,yBAAyB;AAE7B,MAAM,0BAA0B,UAA4B,CAAC,MAAM;CACjE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAGZ,iCAAiC,QAAQ,sBAAsB,qBAAqB,CAAC,OAAO,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,oBAAoB,SAA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getEvaluationInputMessages(data.input));
47
47
  if (data?.output !== void 0) span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(data.output));
48
- if (call.endTime) span.end(call.endTime);
48
+ call.end?.();
49
49
  }
50
50
  export { recordClassifierEvaluations };
51
51
 
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-classifier.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/mastra-classifier.ts"],"sourcesContent":["import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport { isObjectLike } from '@sentry/core';\nimport type { ClassifierEvaluationCall } from '../ai/mastra/classifier-evaluation';\nimport { processClassifierEvaluationData, setStartingClassifierEvaluation } from '../ai/mastra/classifier-evaluation';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages } from '../ai/core/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { safeChannelCallback } from '../tracing-channel';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\n\n/**\n * Add the evaluated state, questions and answers of a `Classifier.evaluate()` call to the exporter's\n * `classifier_evaluation` span, which Mastra leaves without input or output.\n */\nexport function recordClassifierEvaluations(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_CLASSIFIER_EVALUATE);\n const calls = new WeakMap<object, ClassifierEvaluationCall>();\n\n channel.start.subscribe(message => {\n safeChannelCallback(() => {\n const call: ClassifierEvaluationCall = {};\n calls.set(message as object, call);\n setStartingClassifierEvaluation(call);\n });\n });\n // `evaluate()` has reached its first `await`, so Mastra has already started its span.\n channel.end.subscribe(() => {\n safeChannelCallback(() => setStartingClassifierEvaluation(undefined));\n });\n channel.asyncEnd.subscribe(message => {\n safeChannelCallback(() => {\n const call = calls.get(message as object);\n if (call) {\n finishClassifierEvaluation(call, message as OrchestrionChannelContext);\n }\n });\n });\n}\n\nfunction finishClassifierEvaluation(call: ClassifierEvaluationCall, message: OrchestrionChannelContext): void {\n call.settled = true;\n const { span, recordInputs, recordOutputs } = call;\n if (!span) {\n return;\n }\n\n const params = isObjectLike(message.arguments[0]) ? message.arguments[0] : {};\n // Questions given to the constructor take precedence over the ones passed to `evaluate()`, as in Mastra.\n const questions = (isObjectLike(message.self) ? message.self.questions : undefined) ?? params.questions;\n const data = processClassifierEvaluationData(call, {\n input: recordInputs ? { state: params.state, questions } : undefined,\n output: recordOutputs && isObjectLike(message.result) ? message.result.answers : undefined,\n });\n\n if (isObjectLike(data?.input)) {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(data.input));\n }\n if (data?.output !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(data.output));\n }\n\n if (call.endTime) {\n span.end(call.endTime);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,8BAAoC;CAClD,MAAM,UAAUA,eAA6D,SAAS,0BAA0B;CAChH,MAAM,wBAAQ,IAAI,QAA0C;CAE5D,QAAQ,MAAM,WAAU,YAAW;EACjC,0BAA0B;GACxB,MAAM,OAAiC,CAAC;GACxC,MAAM,IAAI,SAAmB,IAAI;GACjC,gCAAgC,IAAI;EACtC,CAAC;CACH,CAAC;CAED,QAAQ,IAAI,gBAAgB;EAC1B,0BAA0B,gCAAgC,KAAA,CAAS,CAAC;CACtE,CAAC;CACD,QAAQ,SAAS,WAAU,YAAW;EACpC,0BAA0B;GACxB,MAAM,OAAO,MAAM,IAAI,OAAiB;GACxC,IAAI,MACF,2BAA2B,MAAM,OAAoC;EAEzE,CAAC;CACH,CAAC;AACH;AAEA,SAAS,2BAA2B,MAAgC,SAA0C;CAC5G,KAAK,UAAU;CACf,MAAM,EAAE,MAAM,cAAc,kBAAkB;CAC9C,IAAI,CAAC,MACH;CAGF,MAAM,SAAS,aAAa,QAAQ,UAAU,EAAE,IAAI,QAAQ,UAAU,KAAK,CAAC;CAE5E,MAAM,aAAa,aAAa,QAAQ,IAAI,IAAI,QAAQ,KAAK,YAAY,KAAA,MAAc,OAAO;CAC9F,MAAM,OAAO,gCAAgC,MAAM;EACjD,OAAO,eAAe;GAAE,OAAO,OAAO;GAAO;EAAU,IAAI,KAAA;EAC3D,QAAQ,iBAAiB,aAAa,QAAQ,MAAM,IAAI,QAAQ,OAAO,UAAU,KAAA;CACnF,CAAC;CAED,IAAI,aAAa,MAAM,KAAK,GAC1B,KAAK,aAAa,uBAAuB,2BAA2B,KAAK,KAAK,CAAC;CAEjF,IAAI,MAAM,WAAW,KAAA,GACnB,KAAK,aAAa,wBAAwB,4BAA4B,KAAK,MAAM,CAAC;CAGpF,IAAI,KAAK,SACP,KAAK,IAAI,KAAK,OAAO;AAEzB"}
1
+ {"version":3,"file":"mastra-classifier.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/mastra-classifier.ts"],"sourcesContent":["import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport { isObjectLike } from '@sentry/core';\nimport type { ClassifierEvaluationCall } from '../ai/mastra/classifier-evaluation';\nimport { processClassifierEvaluationData, setStartingClassifierEvaluation } from '../ai/mastra/classifier-evaluation';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages } from '../ai/core/utils';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { safeChannelCallback } from '../tracing-channel';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\n\n/**\n * Add the evaluated state, questions and answers of a `Classifier.evaluate()` call to the exporter's\n * `classifier_evaluation` span, which Mastra leaves without input or output.\n */\nexport function recordClassifierEvaluations(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.MASTRA_CLASSIFIER_EVALUATE);\n const calls = new WeakMap<object, ClassifierEvaluationCall>();\n\n channel.start.subscribe(message => {\n safeChannelCallback(() => {\n const call: ClassifierEvaluationCall = {};\n calls.set(message as object, call);\n setStartingClassifierEvaluation(call);\n });\n });\n // `evaluate()` has reached its first `await`, so Mastra has already started its span.\n channel.end.subscribe(() => {\n safeChannelCallback(() => setStartingClassifierEvaluation(undefined));\n });\n channel.asyncEnd.subscribe(message => {\n safeChannelCallback(() => {\n const call = calls.get(message as object);\n if (call) {\n finishClassifierEvaluation(call, message as OrchestrionChannelContext);\n }\n });\n });\n}\n\nfunction finishClassifierEvaluation(call: ClassifierEvaluationCall, message: OrchestrionChannelContext): void {\n call.settled = true;\n const { span, recordInputs, recordOutputs } = call;\n if (!span) {\n return;\n }\n\n const params = isObjectLike(message.arguments[0]) ? message.arguments[0] : {};\n // Questions given to the constructor take precedence over the ones passed to `evaluate()`, as in Mastra.\n const questions = (isObjectLike(message.self) ? message.self.questions : undefined) ?? params.questions;\n const data = processClassifierEvaluationData(call, {\n input: recordInputs ? { state: params.state, questions } : undefined,\n output: recordOutputs && isObjectLike(message.result) ? message.result.answers : undefined,\n });\n\n if (isObjectLike(data?.input)) {\n span.setAttribute(GEN_AI_INPUT_MESSAGES, getEvaluationInputMessages(data.input));\n }\n if (data?.output !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(data.output));\n }\n\n call.end?.();\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,8BAAoC;CAClD,MAAM,UAAUA,eAA6D,SAAS,0BAA0B;CAChH,MAAM,wBAAQ,IAAI,QAA0C;CAE5D,QAAQ,MAAM,WAAU,YAAW;EACjC,0BAA0B;GACxB,MAAM,OAAiC,CAAC;GACxC,MAAM,IAAI,SAAmB,IAAI;GACjC,gCAAgC,IAAI;EACtC,CAAC;CACH,CAAC;CAED,QAAQ,IAAI,gBAAgB;EAC1B,0BAA0B,gCAAgC,KAAA,CAAS,CAAC;CACtE,CAAC;CACD,QAAQ,SAAS,WAAU,YAAW;EACpC,0BAA0B;GACxB,MAAM,OAAO,MAAM,IAAI,OAAiB;GACxC,IAAI,MACF,2BAA2B,MAAM,OAAoC;EAEzE,CAAC;CACH,CAAC;AACH;AAEA,SAAS,2BAA2B,MAAgC,SAA0C;CAC5G,KAAK,UAAU;CACf,MAAM,EAAE,MAAM,cAAc,kBAAkB;CAC9C,IAAI,CAAC,MACH;CAGF,MAAM,SAAS,aAAa,QAAQ,UAAU,EAAE,IAAI,QAAQ,UAAU,KAAK,CAAC;CAE5E,MAAM,aAAa,aAAa,QAAQ,IAAI,IAAI,QAAQ,KAAK,YAAY,KAAA,MAAc,OAAO;CAC9F,MAAM,OAAO,gCAAgC,MAAM;EACjD,OAAO,eAAe;GAAE,OAAO,OAAO;GAAO;EAAU,IAAI,KAAA;EAC3D,QAAQ,iBAAiB,aAAa,QAAQ,MAAM,IAAI,QAAQ,OAAO,UAAU,KAAA;CACnF,CAAC;CAED,IAAI,aAAa,MAAM,KAAK,GAC1B,KAAK,aAAa,uBAAuB,2BAA2B,KAAK,KAAK,CAAC;CAEjF,IAAI,MAAM,WAAW,KAAA,GACnB,KAAK,aAAa,wBAAwB,4BAA4B,KAAK,MAAM,CAAC;CAGpF,KAAK,MAAM;AACb"}
@@ -1,5 +1,6 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
- import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from "../ai/core/utils.js";
2
+ import { getGenAiSpanOp, markCancelledIfAborted, resolveGenAiCallRecording } from "../ai/core/utils.js";
3
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
3
4
  import { addRequestAttributes, extractRequestAttributes } from "../ai/mistral/index.js";
4
5
  import { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from "../ai/mistral/constants.js";
5
6
  import { instrumentEventStream } from "../ai/mistral/streaming.js";
@@ -52,9 +53,10 @@ function instrumentMistral(options) {
52
53
  for (const { channel, operation, streaming } of INSTRUMENTED_CHANNELS) bindTracingChannelToSpan(tracingChannel(channel), (data) => createGenAiSpan(data, operation, streaming, options), {
53
54
  beforeSpanEnd: (span, data) => {
54
55
  if ("error" in data) markCancelledIfAborted(span, getMistralRequestSignal(data.arguments?.[1]));
55
- addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);
56
+ addResponseAttributes(span, data.result, !!data._sentryRecordOutputs);
57
+ data._sentryOnSpanEnd?.("error" in data ? { error: data.error } : { response: data.result });
56
58
  },
57
- deferSpanEnd: ({ span, data }) => streaming && instrumentEventStream(data.result, span, resolveAIRecordingOptions(options).recordOutputs, getMistralRequestSignal(data.arguments?.[1]))
59
+ deferSpanEnd: ({ span, data }) => streaming && instrumentEventStream(data.result, span, !!data._sentryRecordOutputs, getMistralRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd)
58
60
  });
59
61
  }
60
62
  /**
@@ -65,7 +67,12 @@ function createGenAiSpan(data, operation, streaming, options) {
65
67
  if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) return;
66
68
  const args = data.arguments ?? [];
67
69
  const params = args[0];
68
- const { recordInputs } = resolveAIRecordingOptions(options);
70
+ const call = {
71
+ operation,
72
+ request: params
73
+ };
74
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
75
+ data._sentryRecordOutputs = recordOutputs;
69
76
  const attributes = extractRequestAttributes(args, operation, recordInputs, streaming);
70
77
  attributes[SENTRY_ORIGIN] = MISTRAL_ORIGIN;
71
78
  const span = startInactiveSpan({
@@ -74,6 +81,8 @@ function createGenAiSpan(data, operation, streaming, options) {
74
81
  attributes
75
82
  });
76
83
  if (recordInputs && params) addRequestAttributes(span, params, operation);
84
+ runGenAiSpanStart(options, span, call);
85
+ data._sentryOnSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
77
86
  return span;
78
87
  }
79
88
  /**