@sentry/core 10.50.0 → 10.52.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 (347) hide show
  1. package/build/cjs/client.js +33 -5
  2. package/build/cjs/client.js.map +1 -1
  3. package/build/cjs/envelope.js +4 -1
  4. package/build/cjs/envelope.js.map +1 -1
  5. package/build/cjs/fetch.js +7 -4
  6. package/build/cjs/fetch.js.map +1 -1
  7. package/build/cjs/index.js +37 -13
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/instrument/console.js +3 -1
  10. package/build/cjs/instrument/console.js.map +1 -1
  11. package/build/cjs/instrument/fetch.js +6 -2
  12. package/build/cjs/instrument/fetch.js.map +1 -1
  13. package/build/cjs/instrument/handlers.js +11 -1
  14. package/build/cjs/instrument/handlers.js.map +1 -1
  15. package/build/cjs/integrations/console.js +3 -1
  16. package/build/cjs/integrations/console.js.map +1 -1
  17. package/build/cjs/integrations/express/index.js +2 -4
  18. package/build/cjs/integrations/express/index.js.map +1 -1
  19. package/build/cjs/integrations/express/utils.js +0 -7
  20. package/build/cjs/integrations/express/utils.js.map +1 -1
  21. package/build/cjs/integrations/extraerrordata.js +2 -2
  22. package/build/cjs/integrations/extraerrordata.js.map +1 -1
  23. package/build/cjs/integrations/http/add-outgoing-request-breadcrumb.js +43 -0
  24. package/build/cjs/integrations/http/add-outgoing-request-breadcrumb.js.map +1 -0
  25. package/build/cjs/integrations/http/client-patch.js +113 -0
  26. package/build/cjs/integrations/http/client-patch.js.map +1 -0
  27. package/build/cjs/integrations/http/client-subscriptions.js +166 -0
  28. package/build/cjs/integrations/http/client-subscriptions.js.map +1 -0
  29. package/build/cjs/integrations/http/constants.js +10 -0
  30. package/build/cjs/integrations/http/constants.js.map +1 -0
  31. package/build/cjs/integrations/http/double-wrap-warning.js +29 -0
  32. package/build/cjs/integrations/http/double-wrap-warning.js.map +1 -0
  33. package/build/cjs/integrations/http/get-outgoing-span-data.js +88 -0
  34. package/build/cjs/integrations/http/get-outgoing-span-data.js.map +1 -0
  35. package/build/cjs/integrations/http/get-request-url.js +54 -0
  36. package/build/cjs/integrations/http/get-request-url.js.map +1 -0
  37. package/build/cjs/integrations/http/inject-trace-propagation-headers.js +81 -0
  38. package/build/cjs/integrations/http/inject-trace-propagation-headers.js.map +1 -0
  39. package/build/cjs/integrations/postgresjs.js +10 -1
  40. package/build/cjs/integrations/postgresjs.js.map +1 -1
  41. package/build/cjs/integrations/requestdata.js +92 -6
  42. package/build/cjs/integrations/requestdata.js.map +1 -1
  43. package/build/cjs/integrations/supabase.js +39 -12
  44. package/build/cjs/integrations/supabase.js.map +1 -1
  45. package/build/cjs/logs/console-integration.js +3 -1
  46. package/build/cjs/logs/console-integration.js.map +1 -1
  47. package/build/cjs/logs/envelope.js +12 -2
  48. package/build/cjs/logs/envelope.js.map +1 -1
  49. package/build/cjs/logs/internal.js +7 -1
  50. package/build/cjs/logs/internal.js.map +1 -1
  51. package/build/cjs/metrics/envelope.js +15 -2
  52. package/build/cjs/metrics/envelope.js.map +1 -1
  53. package/build/cjs/metrics/internal.js +7 -1
  54. package/build/cjs/metrics/internal.js.map +1 -1
  55. package/build/cjs/server-runtime-client.js +20 -2
  56. package/build/cjs/server-runtime-client.js.map +1 -1
  57. package/build/cjs/tracing/ai/gen-ai-attributes.js +6 -0
  58. package/build/cjs/tracing/ai/gen-ai-attributes.js.map +1 -1
  59. package/build/cjs/tracing/idleSpan.js +7 -1
  60. package/build/cjs/tracing/idleSpan.js.map +1 -1
  61. package/build/cjs/tracing/langchain/index.js +43 -8
  62. package/build/cjs/tracing/langchain/index.js.map +1 -1
  63. package/build/cjs/tracing/langchain/utils.js +44 -10
  64. package/build/cjs/tracing/langchain/utils.js.map +1 -1
  65. package/build/cjs/tracing/langgraph/index.js +105 -2
  66. package/build/cjs/tracing/langgraph/index.js.map +1 -1
  67. package/build/cjs/tracing/langgraph/utils.js +168 -0
  68. package/build/cjs/tracing/langgraph/utils.js.map +1 -1
  69. package/build/cjs/tracing/spans/captureSpan.js +169 -9
  70. package/build/cjs/tracing/spans/captureSpan.js.map +1 -1
  71. package/build/cjs/tracing/spans/envelope.js +13 -3
  72. package/build/cjs/tracing/spans/envelope.js.map +1 -1
  73. package/build/cjs/tracing/trace.js +2 -0
  74. package/build/cjs/tracing/trace.js.map +1 -1
  75. package/build/cjs/tracing/vercel-ai/constants.js +8 -0
  76. package/build/cjs/tracing/vercel-ai/constants.js.map +1 -1
  77. package/build/cjs/tracing/vercel-ai/index.js +93 -14
  78. package/build/cjs/tracing/vercel-ai/index.js.map +1 -1
  79. package/build/cjs/trpc.js +2 -3
  80. package/build/cjs/trpc.js.map +1 -1
  81. package/build/cjs/utils/baggage.js +73 -0
  82. package/build/cjs/utils/baggage.js.map +1 -1
  83. package/build/cjs/utils/chain-and-copy-promiselike.js +1 -0
  84. package/build/cjs/utils/chain-and-copy-promiselike.js.map +1 -1
  85. package/build/cjs/utils/get-default-export.js +32 -0
  86. package/build/cjs/utils/get-default-export.js.map +1 -0
  87. package/build/cjs/utils/isSentryRequestUrl.js +9 -1
  88. package/build/cjs/utils/isSentryRequestUrl.js.map +1 -1
  89. package/build/cjs/utils/normalizationHints.js +38 -0
  90. package/build/cjs/utils/normalizationHints.js.map +1 -0
  91. package/build/cjs/utils/normalize.js +7 -11
  92. package/build/cjs/utils/normalize.js.map +1 -1
  93. package/build/cjs/utils/object.js +1 -1
  94. package/build/cjs/utils/object.js.map +1 -1
  95. package/build/cjs/utils/request.js +192 -12
  96. package/build/cjs/utils/request.js.map +1 -1
  97. package/build/cjs/utils/should-ignore-span.js +27 -8
  98. package/build/cjs/utils/should-ignore-span.js.map +1 -1
  99. package/build/cjs/utils/spanUtils.js +1 -1
  100. package/build/cjs/utils/spanUtils.js.map +1 -1
  101. package/build/cjs/utils/version.js +1 -1
  102. package/build/esm/client.js +33 -5
  103. package/build/esm/client.js.map +1 -1
  104. package/build/esm/envelope.js +4 -1
  105. package/build/esm/envelope.js.map +1 -1
  106. package/build/esm/fetch.js +7 -4
  107. package/build/esm/fetch.js.map +1 -1
  108. package/build/esm/index.js +11 -5
  109. package/build/esm/index.js.map +1 -1
  110. package/build/esm/instrument/console.js +3 -1
  111. package/build/esm/instrument/console.js.map +1 -1
  112. package/build/esm/instrument/fetch.js +6 -2
  113. package/build/esm/instrument/fetch.js.map +1 -1
  114. package/build/esm/instrument/handlers.js +11 -1
  115. package/build/esm/instrument/handlers.js.map +1 -1
  116. package/build/esm/integrations/console.js +3 -1
  117. package/build/esm/integrations/console.js.map +1 -1
  118. package/build/esm/integrations/express/index.js +3 -5
  119. package/build/esm/integrations/express/index.js.map +1 -1
  120. package/build/esm/integrations/express/utils.js +1 -7
  121. package/build/esm/integrations/express/utils.js.map +1 -1
  122. package/build/esm/integrations/extraerrordata.js +2 -2
  123. package/build/esm/integrations/extraerrordata.js.map +1 -1
  124. package/build/esm/integrations/http/add-outgoing-request-breadcrumb.js +41 -0
  125. package/build/esm/integrations/http/add-outgoing-request-breadcrumb.js.map +1 -0
  126. package/build/esm/integrations/http/client-patch.js +111 -0
  127. package/build/esm/integrations/http/client-patch.js.map +1 -0
  128. package/build/esm/integrations/http/client-subscriptions.js +164 -0
  129. package/build/esm/integrations/http/client-subscriptions.js.map +1 -0
  130. package/build/esm/integrations/http/constants.js +6 -0
  131. package/build/esm/integrations/http/constants.js.map +1 -0
  132. package/build/esm/integrations/http/double-wrap-warning.js +26 -0
  133. package/build/esm/integrations/http/double-wrap-warning.js.map +1 -0
  134. package/build/esm/integrations/http/get-outgoing-span-data.js +85 -0
  135. package/build/esm/integrations/http/get-outgoing-span-data.js.map +1 -0
  136. package/build/esm/integrations/http/get-request-url.js +49 -0
  137. package/build/esm/integrations/http/get-request-url.js.map +1 -0
  138. package/build/esm/integrations/http/inject-trace-propagation-headers.js +79 -0
  139. package/build/esm/integrations/http/inject-trace-propagation-headers.js.map +1 -0
  140. package/build/esm/integrations/postgresjs.js +10 -1
  141. package/build/esm/integrations/postgresjs.js.map +1 -1
  142. package/build/esm/integrations/requestdata.js +92 -6
  143. package/build/esm/integrations/requestdata.js.map +1 -1
  144. package/build/esm/integrations/supabase.js +39 -12
  145. package/build/esm/integrations/supabase.js.map +1 -1
  146. package/build/esm/logs/console-integration.js +3 -1
  147. package/build/esm/logs/console-integration.js.map +1 -1
  148. package/build/esm/logs/envelope.js +12 -2
  149. package/build/esm/logs/envelope.js.map +1 -1
  150. package/build/esm/logs/internal.js +7 -1
  151. package/build/esm/logs/internal.js.map +1 -1
  152. package/build/esm/metrics/envelope.js +15 -2
  153. package/build/esm/metrics/envelope.js.map +1 -1
  154. package/build/esm/metrics/internal.js +7 -1
  155. package/build/esm/metrics/internal.js.map +1 -1
  156. package/build/esm/package.json +1 -1
  157. package/build/esm/server-runtime-client.js +20 -2
  158. package/build/esm/server-runtime-client.js.map +1 -1
  159. package/build/esm/tracing/ai/gen-ai-attributes.js +6 -1
  160. package/build/esm/tracing/ai/gen-ai-attributes.js.map +1 -1
  161. package/build/esm/tracing/idleSpan.js +7 -1
  162. package/build/esm/tracing/idleSpan.js.map +1 -1
  163. package/build/esm/tracing/langchain/index.js +45 -10
  164. package/build/esm/tracing/langchain/index.js.map +1 -1
  165. package/build/esm/tracing/langchain/utils.js +44 -12
  166. package/build/esm/tracing/langchain/utils.js.map +1 -1
  167. package/build/esm/tracing/langgraph/index.js +107 -5
  168. package/build/esm/tracing/langgraph/index.js.map +1 -1
  169. package/build/esm/tracing/langgraph/utils.js +166 -2
  170. package/build/esm/tracing/langgraph/utils.js.map +1 -1
  171. package/build/esm/tracing/spans/captureSpan.js +170 -11
  172. package/build/esm/tracing/spans/captureSpan.js.map +1 -1
  173. package/build/esm/tracing/spans/envelope.js +13 -3
  174. package/build/esm/tracing/spans/envelope.js.map +1 -1
  175. package/build/esm/tracing/trace.js +2 -1
  176. package/build/esm/tracing/trace.js.map +1 -1
  177. package/build/esm/tracing/vercel-ai/constants.js +8 -1
  178. package/build/esm/tracing/vercel-ai/constants.js.map +1 -1
  179. package/build/esm/tracing/vercel-ai/index.js +95 -17
  180. package/build/esm/tracing/vercel-ai/index.js.map +1 -1
  181. package/build/esm/trpc.js +2 -3
  182. package/build/esm/trpc.js.map +1 -1
  183. package/build/esm/utils/baggage.js +73 -1
  184. package/build/esm/utils/baggage.js.map +1 -1
  185. package/build/esm/utils/chain-and-copy-promiselike.js +1 -0
  186. package/build/esm/utils/chain-and-copy-promiselike.js.map +1 -1
  187. package/build/esm/utils/get-default-export.js +30 -0
  188. package/build/esm/utils/get-default-export.js.map +1 -0
  189. package/build/esm/utils/isSentryRequestUrl.js +9 -1
  190. package/build/esm/utils/isSentryRequestUrl.js.map +1 -1
  191. package/build/esm/utils/normalizationHints.js +33 -0
  192. package/build/esm/utils/normalizationHints.js.map +1 -0
  193. package/build/esm/utils/normalize.js +7 -11
  194. package/build/esm/utils/normalize.js.map +1 -1
  195. package/build/esm/utils/object.js +1 -1
  196. package/build/esm/utils/object.js.map +1 -1
  197. package/build/esm/utils/request.js +190 -13
  198. package/build/esm/utils/request.js.map +1 -1
  199. package/build/esm/utils/should-ignore-span.js +27 -8
  200. package/build/esm/utils/should-ignore-span.js.map +1 -1
  201. package/build/esm/utils/spanUtils.js +1 -1
  202. package/build/esm/utils/spanUtils.js.map +1 -1
  203. package/build/esm/utils/version.js +1 -1
  204. package/build/types/client.d.ts +12 -1
  205. package/build/types/client.d.ts.map +1 -1
  206. package/build/types/envelope.d.ts.map +1 -1
  207. package/build/types/fetch.d.ts.map +1 -1
  208. package/build/types/index.d.ts +17 -6
  209. package/build/types/index.d.ts.map +1 -1
  210. package/build/types/instrument/console.d.ts +2 -1
  211. package/build/types/instrument/console.d.ts.map +1 -1
  212. package/build/types/instrument/fetch.d.ts +4 -2
  213. package/build/types/instrument/fetch.d.ts.map +1 -1
  214. package/build/types/instrument/handlers.d.ts +2 -2
  215. package/build/types/instrument/handlers.d.ts.map +1 -1
  216. package/build/types/integrations/console.d.ts.map +1 -1
  217. package/build/types/integrations/express/index.d.ts.map +1 -1
  218. package/build/types/integrations/express/utils.d.ts +1 -5
  219. package/build/types/integrations/express/utils.d.ts.map +1 -1
  220. package/build/types/integrations/http/add-outgoing-request-breadcrumb.d.ts +6 -0
  221. package/build/types/integrations/http/add-outgoing-request-breadcrumb.d.ts.map +1 -0
  222. package/build/types/integrations/http/client-patch.d.ts +46 -0
  223. package/build/types/integrations/http/client-patch.d.ts.map +1 -0
  224. package/build/types/integrations/http/client-subscriptions.d.ts +21 -0
  225. package/build/types/integrations/http/client-subscriptions.d.ts.map +1 -0
  226. package/build/types/integrations/http/constants.d.ts +6 -0
  227. package/build/types/integrations/http/constants.d.ts.map +1 -0
  228. package/build/types/integrations/http/double-wrap-warning.d.ts +4 -0
  229. package/build/types/integrations/http/double-wrap-warning.d.ts.map +1 -0
  230. package/build/types/integrations/http/get-outgoing-span-data.d.ts +13 -0
  231. package/build/types/integrations/http/get-outgoing-span-data.d.ts.map +1 -0
  232. package/build/types/integrations/http/get-request-url.d.ts +10 -0
  233. package/build/types/integrations/http/get-request-url.d.ts.map +1 -0
  234. package/build/types/integrations/http/index.d.ts +4 -0
  235. package/build/types/integrations/http/index.d.ts.map +1 -0
  236. package/build/types/integrations/http/inject-trace-propagation-headers.d.ts +12 -0
  237. package/build/types/integrations/http/inject-trace-propagation-headers.d.ts.map +1 -0
  238. package/build/types/integrations/http/types.d.ts +249 -0
  239. package/build/types/integrations/http/types.d.ts.map +1 -0
  240. package/build/types/integrations/postgresjs.d.ts.map +1 -1
  241. package/build/types/integrations/requestdata.d.ts.map +1 -1
  242. package/build/types/integrations/supabase.d.ts.map +1 -1
  243. package/build/types/logs/console-integration.d.ts.map +1 -1
  244. package/build/types/logs/envelope.d.ts +5 -2
  245. package/build/types/logs/envelope.d.ts.map +1 -1
  246. package/build/types/logs/internal.d.ts.map +1 -1
  247. package/build/types/metrics/envelope.d.ts +5 -2
  248. package/build/types/metrics/envelope.d.ts.map +1 -1
  249. package/build/types/metrics/internal.d.ts.map +1 -1
  250. package/build/types/server-runtime-client.d.ts +5 -0
  251. package/build/types/server-runtime-client.d.ts.map +1 -1
  252. package/build/types/tracing/idleSpan.d.ts.map +1 -1
  253. package/build/types/tracing/index.d.ts +1 -1
  254. package/build/types/tracing/index.d.ts.map +1 -1
  255. package/build/types/tracing/langchain/index.d.ts.map +1 -1
  256. package/build/types/tracing/langchain/types.d.ts +8 -0
  257. package/build/types/tracing/langchain/types.d.ts.map +1 -1
  258. package/build/types/tracing/langchain/utils.d.ts +2 -0
  259. package/build/types/tracing/langchain/utils.d.ts.map +1 -1
  260. package/build/types/tracing/langgraph/index.d.ts +4 -0
  261. package/build/types/tracing/langgraph/index.d.ts.map +1 -1
  262. package/build/types/tracing/langgraph/utils.d.ts +18 -2
  263. package/build/types/tracing/langgraph/utils.d.ts.map +1 -1
  264. package/build/types/tracing/spans/captureSpan.d.ts +13 -3
  265. package/build/types/tracing/spans/captureSpan.d.ts.map +1 -1
  266. package/build/types/tracing/spans/envelope.d.ts.map +1 -1
  267. package/build/types/tracing/trace.d.ts +1 -0
  268. package/build/types/tracing/trace.d.ts.map +1 -1
  269. package/build/types/tracing/vercel-ai/constants.d.ts +1 -0
  270. package/build/types/tracing/vercel-ai/constants.d.ts.map +1 -1
  271. package/build/types/tracing/vercel-ai/index.d.ts +9 -0
  272. package/build/types/tracing/vercel-ai/index.d.ts.map +1 -1
  273. package/build/types/trpc.d.ts.map +1 -1
  274. package/build/types/types-hoist/feedback/config.d.ts +20 -0
  275. package/build/types/types-hoist/feedback/config.d.ts.map +1 -1
  276. package/build/types/types-hoist/feedback/index.d.ts +2 -2
  277. package/build/types/types-hoist/feedback/index.d.ts.map +1 -1
  278. package/build/types/types-hoist/feedback/sendFeedback.d.ts +3 -0
  279. package/build/types/types-hoist/feedback/sendFeedback.d.ts.map +1 -1
  280. package/build/types/types-hoist/log.d.ts +5 -0
  281. package/build/types/types-hoist/log.d.ts.map +1 -1
  282. package/build/types/types-hoist/metric.d.ts +5 -0
  283. package/build/types/types-hoist/metric.d.ts.map +1 -1
  284. package/build/types/types-hoist/options.d.ts +37 -2
  285. package/build/types/types-hoist/options.d.ts.map +1 -1
  286. package/build/types/types-hoist/span.d.ts +5 -0
  287. package/build/types/types-hoist/span.d.ts.map +1 -1
  288. package/build/types/types-hoist/webfetchapi.d.ts +2 -0
  289. package/build/types/types-hoist/webfetchapi.d.ts.map +1 -1
  290. package/build/types/utils/baggage.d.ts +13 -0
  291. package/build/types/utils/baggage.d.ts.map +1 -1
  292. package/build/types/utils/get-default-export.d.ts +22 -0
  293. package/build/types/utils/get-default-export.d.ts.map +1 -0
  294. package/build/types/utils/normalizationHints.d.ts +9 -0
  295. package/build/types/utils/normalizationHints.d.ts.map +1 -0
  296. package/build/types/utils/normalize.d.ts.map +1 -1
  297. package/build/types/utils/object.d.ts +1 -1
  298. package/build/types/utils/object.d.ts.map +1 -1
  299. package/build/types/utils/request.d.ts +30 -0
  300. package/build/types/utils/request.d.ts.map +1 -1
  301. package/build/types/utils/should-ignore-span.d.ts +3 -1
  302. package/build/types/utils/should-ignore-span.d.ts.map +1 -1
  303. package/build/types/utils/spanUtils.d.ts +1 -1
  304. package/build/types-ts3.8/client.d.ts +12 -1
  305. package/build/types-ts3.8/index.d.ts +17 -6
  306. package/build/types-ts3.8/instrument/console.d.ts +2 -1
  307. package/build/types-ts3.8/instrument/fetch.d.ts +4 -2
  308. package/build/types-ts3.8/instrument/handlers.d.ts +2 -2
  309. package/build/types-ts3.8/integrations/express/utils.d.ts +1 -5
  310. package/build/types-ts3.8/integrations/http/add-outgoing-request-breadcrumb.d.ts +6 -0
  311. package/build/types-ts3.8/integrations/http/client-patch.d.ts +46 -0
  312. package/build/types-ts3.8/integrations/http/client-subscriptions.d.ts +21 -0
  313. package/build/types-ts3.8/integrations/http/constants.d.ts +6 -0
  314. package/build/types-ts3.8/integrations/http/double-wrap-warning.d.ts +4 -0
  315. package/build/types-ts3.8/integrations/http/get-outgoing-span-data.d.ts +13 -0
  316. package/build/types-ts3.8/integrations/http/get-request-url.d.ts +10 -0
  317. package/build/types-ts3.8/integrations/http/index.d.ts +4 -0
  318. package/build/types-ts3.8/integrations/http/inject-trace-propagation-headers.d.ts +12 -0
  319. package/build/types-ts3.8/integrations/http/types.d.ts +252 -0
  320. package/build/types-ts3.8/logs/envelope.d.ts +5 -2
  321. package/build/types-ts3.8/metrics/envelope.d.ts +5 -2
  322. package/build/types-ts3.8/server-runtime-client.d.ts +5 -0
  323. package/build/types-ts3.8/tracing/index.d.ts +1 -1
  324. package/build/types-ts3.8/tracing/langchain/types.d.ts +8 -0
  325. package/build/types-ts3.8/tracing/langchain/utils.d.ts +2 -0
  326. package/build/types-ts3.8/tracing/langgraph/index.d.ts +4 -0
  327. package/build/types-ts3.8/tracing/langgraph/utils.d.ts +18 -2
  328. package/build/types-ts3.8/tracing/spans/captureSpan.d.ts +13 -3
  329. package/build/types-ts3.8/tracing/trace.d.ts +1 -0
  330. package/build/types-ts3.8/tracing/vercel-ai/constants.d.ts +1 -0
  331. package/build/types-ts3.8/tracing/vercel-ai/index.d.ts +9 -0
  332. package/build/types-ts3.8/types-hoist/feedback/config.d.ts +20 -0
  333. package/build/types-ts3.8/types-hoist/feedback/index.d.ts +2 -2
  334. package/build/types-ts3.8/types-hoist/feedback/sendFeedback.d.ts +3 -0
  335. package/build/types-ts3.8/types-hoist/log.d.ts +5 -0
  336. package/build/types-ts3.8/types-hoist/metric.d.ts +5 -0
  337. package/build/types-ts3.8/types-hoist/options.d.ts +37 -2
  338. package/build/types-ts3.8/types-hoist/span.d.ts +5 -0
  339. package/build/types-ts3.8/types-hoist/webfetchapi.d.ts +2 -0
  340. package/build/types-ts3.8/utils/baggage.d.ts +13 -0
  341. package/build/types-ts3.8/utils/get-default-export.d.ts +22 -0
  342. package/build/types-ts3.8/utils/normalizationHints.d.ts +9 -0
  343. package/build/types-ts3.8/utils/object.d.ts +1 -1
  344. package/build/types-ts3.8/utils/request.d.ts +30 -0
  345. package/build/types-ts3.8/utils/should-ignore-span.d.ts +3 -1
  346. package/build/types-ts3.8/utils/spanUtils.d.ts +1 -1
  347. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","sources":["../../../src/metrics/internal.ts"],"sourcesContent":["import { type RawAttributes, serializeAttributes } from '../attributes';\nimport { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope } from '../scope';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Metric, SerializedMetric } from '../types-hoist/metric';\nimport type { User } from '../types-hoist/user';\nimport { debug } from '../utils/debug-logger';\nimport { getCombinedScopeData } from '../utils/scopeData';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { getSequenceAttribute } from '../utils/timestampSequence';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { createMetricEnvelope } from './envelope';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n metricAttributes: Record<string, unknown>,\n key: string,\n value: unknown,\n setEvenIfPresent = true,\n): void {\n if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n metricAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void {\n const bufferMap = _getBufferMap();\n const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n if (metricBuffer === undefined) {\n bufferMap.set(client, [serializedMetric]);\n } else {\n if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n bufferMap.set(client, [serializedMetric]);\n } else {\n bufferMap.set(client, [...metricBuffer, serializedMetric]);\n }\n }\n}\n\n/**\n * Options for capturing a metric internally.\n */\nexport interface InternalCaptureMetricOptions {\n /**\n * The scope to capture the metric with.\n */\n scope?: Scope;\n\n /**\n * A function to capture the serialized metric.\n */\n captureSerializedMetric?: (client: Client, metric: SerializedMetric) => void;\n}\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric: Metric, client: Client, user: User): Metric {\n const { release, environment } = client.getOptions();\n\n const processedMetricAttributes = {\n ...beforeMetric.attributes,\n };\n\n // Add user attributes\n setMetricAttribute(processedMetricAttributes, 'user.id', user.id, false);\n setMetricAttribute(processedMetricAttributes, 'user.email', user.email, false);\n setMetricAttribute(processedMetricAttributes, 'user.name', user.username, false);\n\n // Add Sentry metadata\n setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n // Add SDK metadata\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n // Add replay metadata\n const replay = client.getIntegrationByName<\n Integration & {\n getReplayId: (onlyIfSampled?: boolean) => string;\n getRecordingMode: () => 'session' | 'buffer' | undefined;\n }\n >('Replay');\n\n const replayId = replay?.getReplayId(true);\n setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n return {\n ...beforeMetric,\n attributes: processedMetricAttributes,\n };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(\n metric: Metric,\n client: Client,\n currentScope: Scope,\n scopeAttributes: RawAttributes<Record<string, unknown>> | undefined,\n): SerializedMetric {\n // Get trace context\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n const span = _getSpanForScope(currentScope);\n const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n const spanId = span ? span.spanContext().spanId : undefined;\n\n const timestamp = timestampInSeconds();\n const sequenceAttr = getSequenceAttribute(timestamp);\n\n return {\n timestamp,\n trace_id: traceId ?? '',\n span_id: spanId,\n name: metric.name,\n type: metric.type,\n unit: metric.unit,\n value: metric.value,\n attributes: {\n ...serializeAttributes(scopeAttributes),\n ...serializeAttributes(metric.attributes, 'skip-undefined'),\n [sequenceAttr.key]: sequenceAttr.value,\n },\n };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void {\n const currentScope = options?.scope ?? getCurrentScope();\n const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture metric.');\n return;\n }\n\n const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n if (!metricsEnabled) {\n DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');\n return;\n }\n\n // Enrich metric with contextual attributes\n const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);\n const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);\n\n client.emit('processMetric', enrichedMetric);\n\n // todo(v11): Remove the experimental `beforeSendMetric`\n // eslint-disable-next-line deprecation/deprecation\n const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n if (!processedMetric) {\n DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n return;\n }\n\n const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);\n\n DEBUG_BUILD && debug.log('[Metric]', serializedMetric);\n\n captureSerializedMetric(client, serializedMetric);\n\n client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array<SerializedMetric>): void {\n const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n if (metricBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the metric buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushMetrics');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nexport function _INTERNAL_getMetricBuffer(client: Client): Array<SerializedMetric> | undefined {\n return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap(): WeakMap<Client, Array<SerializedMetric>> {\n // The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap<Client, Array<SerializedMetric>>());\n}\n"],"names":["_getTraceInfoFromScope","_getSpanForScope","timestampInSeconds","getSequenceAttribute","serializeAttributes","getCurrentScope","getClient","DEBUG_BUILD","debug","getCombinedScopeData","getIsolationScope","envelope","createMetricEnvelope","getGlobalSingleton"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,sBAAA,GAAyB,IAAI;;AAEnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB;AAC3B,EAAE,gBAAgB;AAClB,EAAE,GAAG;AACL,EAAE,KAAK;AACP,EAAE,gBAAA,GAAmB,IAAI;AACzB,EAAQ;AACR,EAAE,IAAI,KAAA,KAAU,gBAAA,IAAoB,EAAE,GAAA,IAAO,gBAAgB,CAAC,CAAC,EAAE;AACjE,IAAI,gBAAgB,CAAC,GAAG,CAAA,GAAI,KAAK;AACjC,EAAE;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,iCAAiC,CAAC,MAAM,EAAU,gBAAgB,EAA0B;AAC5G,EAAE,MAAM,SAAA,GAAY,aAAa,EAAE;AACnC,EAAE,MAAM,YAAA,GAAe,yBAAyB,CAAC,MAAM,CAAC;;AAExD,EAAE,IAAI,YAAA,KAAiB,SAAS,EAAE;AAClC,IAAI,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,gBAAgB,CAAC,CAAC;AAC7C,EAAE,OAAO;AACT,IAAI,IAAI,YAAY,CAAC,MAAA,IAAU,sBAAsB,EAAE;AACvD,MAAM,4BAA4B,CAAC,MAAM,EAAE,YAAY,CAAC;AACxD,MAAM,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,gBAAgB,CAAC,CAAC;AAC/C,IAAI,OAAO;AACX,MAAM,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,YAAY,EAAE,gBAAgB,CAAC,CAAC;AAChE,IAAI;AACJ,EAAE;AACF;;AAEA;AACA;AACA;;AAaA;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.js","sources":["../../../src/metrics/internal.ts"],"sourcesContent":["import { type RawAttributes, serializeAttributes } from '../attributes';\nimport { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope } from '../scope';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Metric, SerializedMetric } from '../types-hoist/metric';\nimport type { User } from '../types-hoist/user';\nimport { debug } from '../utils/debug-logger';\nimport { getCombinedScopeData } from '../utils/scopeData';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { getSequenceAttribute } from '../utils/timestampSequence';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { createMetricEnvelope } from './envelope';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n metricAttributes: Record<string, unknown>,\n key: string,\n value: unknown,\n setEvenIfPresent = true,\n): void {\n if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n metricAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void {\n const bufferMap = _getBufferMap();\n const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n if (metricBuffer === undefined) {\n bufferMap.set(client, [serializedMetric]);\n } else {\n if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n bufferMap.set(client, [serializedMetric]);\n } else {\n bufferMap.set(client, [...metricBuffer, serializedMetric]);\n }\n }\n}\n\n/**\n * Options for capturing a metric internally.\n */\nexport interface InternalCaptureMetricOptions {\n /**\n * The scope to capture the metric with.\n */\n scope?: Scope;\n\n /**\n * A function to capture the serialized metric.\n */\n captureSerializedMetric?: (client: Client, metric: SerializedMetric) => void;\n}\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric: Metric, client: Client, user: User): Metric {\n const { release, environment } = client.getOptions();\n\n const processedMetricAttributes = {\n ...beforeMetric.attributes,\n };\n\n // Add user attributes\n setMetricAttribute(processedMetricAttributes, 'user.id', user.id, false);\n setMetricAttribute(processedMetricAttributes, 'user.email', user.email, false);\n setMetricAttribute(processedMetricAttributes, 'user.name', user.username, false);\n\n // Add Sentry metadata\n setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n // Add SDK metadata\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n // Add replay metadata\n const replay = client.getIntegrationByName<\n Integration & {\n getReplayId: (onlyIfSampled?: boolean) => string;\n getRecordingMode: () => 'session' | 'buffer' | undefined;\n }\n >('Replay');\n\n const replayId = replay?.getReplayId(true);\n setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n return {\n ...beforeMetric,\n attributes: processedMetricAttributes,\n };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(\n metric: Metric,\n client: Client,\n currentScope: Scope,\n scopeAttributes: RawAttributes<Record<string, unknown>> | undefined,\n): SerializedMetric {\n // Get trace context\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n const span = _getSpanForScope(currentScope);\n const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n const spanId = span ? span.spanContext().spanId : undefined;\n\n const timestamp = timestampInSeconds();\n const sequenceAttr = getSequenceAttribute(timestamp);\n\n return {\n timestamp,\n trace_id: traceId ?? '',\n span_id: spanId,\n name: metric.name,\n type: metric.type,\n unit: metric.unit,\n value: metric.value,\n attributes: {\n ...serializeAttributes(scopeAttributes),\n ...serializeAttributes(metric.attributes, 'skip-undefined'),\n [sequenceAttr.key]: sequenceAttr.value,\n },\n };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void {\n const currentScope = options?.scope ?? getCurrentScope();\n const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture metric.');\n return;\n }\n\n const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n if (!metricsEnabled) {\n DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');\n return;\n }\n\n // Enrich metric with contextual attributes\n const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);\n const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);\n\n client.emit('processMetric', enrichedMetric);\n\n // todo(v11): Remove the experimental `beforeSendMetric`\n // eslint-disable-next-line deprecation/deprecation\n const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n if (!processedMetric) {\n DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n return;\n }\n\n const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);\n\n DEBUG_BUILD && debug.log('[Metric]', serializedMetric);\n\n captureSerializedMetric(client, serializedMetric);\n\n client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array<SerializedMetric>): void {\n const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n if (metricBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createMetricEnvelope(\n metricBuffer,\n clientOptions._metadata,\n clientOptions.tunnel,\n client.getDsn(),\n clientOptions.sendDefaultPii,\n );\n\n // Clear the metric buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushMetrics');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nexport function _INTERNAL_getMetricBuffer(client: Client): Array<SerializedMetric> | undefined {\n return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap(): WeakMap<Client, Array<SerializedMetric>> {\n // The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap<Client, Array<SerializedMetric>>());\n}\n"],"names":["_getTraceInfoFromScope","_getSpanForScope","timestampInSeconds","getSequenceAttribute","serializeAttributes","getCurrentScope","getClient","DEBUG_BUILD","debug","getCombinedScopeData","getIsolationScope","envelope","createMetricEnvelope","getGlobalSingleton"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,sBAAA,GAAyB,IAAI;;AAEnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB;AAC3B,EAAE,gBAAgB;AAClB,EAAE,GAAG;AACL,EAAE,KAAK;AACP,EAAE,gBAAA,GAAmB,IAAI;AACzB,EAAQ;AACR,EAAE,IAAI,KAAA,KAAU,gBAAA,IAAoB,EAAE,GAAA,IAAO,gBAAgB,CAAC,CAAC,EAAE;AACjE,IAAI,gBAAgB,CAAC,GAAG,CAAA,GAAI,KAAK;AACjC,EAAE;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,iCAAiC,CAAC,MAAM,EAAU,gBAAgB,EAA0B;AAC5G,EAAE,MAAM,SAAA,GAAY,aAAa,EAAE;AACnC,EAAE,MAAM,YAAA,GAAe,yBAAyB,CAAC,MAAM,CAAC;;AAExD,EAAE,IAAI,YAAA,KAAiB,SAAS,EAAE;AAClC,IAAI,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,gBAAgB,CAAC,CAAC;AAC7C,EAAE,OAAO;AACT,IAAI,IAAI,YAAY,CAAC,MAAA,IAAU,sBAAsB,EAAE;AACvD,MAAM,4BAA4B,CAAC,MAAM,EAAE,YAAY,CAAC;AACxD,MAAM,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,gBAAgB,CAAC,CAAC;AAC/C,IAAI,OAAO;AACX,MAAM,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,YAAY,EAAE,gBAAgB,CAAC,CAAC;AAChE,IAAI;AACJ,EAAE;AACF;;AAEA;AACA;AACA;;AAaA;AACA;AACA;AACA,SAAS,uBAAuB,CAAC,YAAY,EAAU,MAAM,EAAU,IAAI,EAAgB;AAC3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('./utils/trace-info.js');
20
20
  class ServerRuntimeClient
21
21
 
22
22
  extends client.Client {
23
+ __init() {this._disposeCallbacks = [];}
24
+
23
25
  /**
24
26
  * Creates a new Edge SDK instance.
25
27
  * @param options Configuration options for this SDK.
@@ -30,8 +32,7 @@ class ServerRuntimeClient
30
32
 
31
33
  userAgent.addUserAgentToTransportHeaders(options);
32
34
 
33
- super(options);
34
-
35
+ super(options);ServerRuntimeClient.prototype.__init.call(this);
35
36
  this._setUpMetricsProcessing();
36
37
  }
37
38
 
@@ -143,6 +144,13 @@ class ServerRuntimeClient
143
144
  return id;
144
145
  }
145
146
 
147
+ /**
148
+ * @inheritDoc
149
+ */
150
+ registerCleanup(callback) {
151
+ this._disposeCallbacks.push(callback);
152
+ }
153
+
146
154
  /**
147
155
  * Disposes of the client and releases all resources.
148
156
  *
@@ -157,6 +165,16 @@ class ServerRuntimeClient
157
165
  dispose() {
158
166
  debugBuild.DEBUG_BUILD && debugLogger.debug.log('Disposing client...');
159
167
 
168
+ // Run all registered cleanup callbacks
169
+ for (const callback of this._disposeCallbacks) {
170
+ try {
171
+ callback();
172
+ } catch {
173
+ // Ignore errors in cleanup callbacks
174
+ }
175
+ }
176
+ this._disposeCallbacks.length = 0;
177
+
160
178
  for (const hookName of Object.keys(this._hooks)) {
161
179
  this._hooks[hookName]?.clear();
162
180
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server-runtime-client.js","sources":["../../src/server-runtime-client.ts"],"sourcesContent":["import { createCheckInEnvelope } from './checkin';\nimport { Client } from './client';\nimport { getIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Scope } from './scope';\nimport { registerSpanErrorInstrumentation } from './tracing';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base';\nimport { addUserAgentToTransportHeaders } from './transports/userAgent';\nimport type { CheckIn, MonitorConfig, SerializedCheckIn } from './types-hoist/checkin';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { ClientOptions } from './types-hoist/options';\nimport type { ParameterizedString } from './types-hoist/parameterize';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { BaseTransportOptions, Transport } from './types-hoist/transport';\nimport { debug } from './utils/debug-logger';\nimport { eventFromMessage, eventFromUnknownInput } from './utils/eventbuilder';\nimport { uuid4 } from './utils/misc';\nimport { makePromiseBuffer } from './utils/promisebuffer';\nimport { resolvedSyncPromise } from './utils/syncpromise';\nimport { _getTraceInfoFromScope } from './utils/trace-info';\n\nexport interface ServerRuntimeClientOptions extends ClientOptions<BaseTransportOptions> {\n platform?: string;\n runtime?: { name: string; version?: string };\n serverName?: string;\n}\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nexport class ServerRuntimeClient<\n O extends ClientOptions & ServerRuntimeClientOptions = ServerRuntimeClientOptions,\n> extends Client<O> {\n /**\n * Creates a new Edge SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: O) {\n // Server clients always support tracing\n registerSpanErrorInstrumentation();\n\n addUserAgentToTransportHeaders(options);\n\n super(options);\n\n this._setUpMetricsProcessing();\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint);\n event.level = 'error';\n\n return resolvedSyncPromise(event);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return resolvedSyncPromise(\n eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n );\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {\n setCurrentRequestSessionErroredOrCrashed(hint);\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string {\n // If the event is of type Exception, then a request session should be captured\n const isException = !event.type && event.exception?.values && event.exception.values.length > 0;\n if (isException) {\n setCurrentRequestSessionErroredOrCrashed(hint);\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\n public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();\n if (!this._isEnabled()) {\n DEBUG_BUILD && debug.warn('SDK not enabled, will not capture check-in.');\n return id;\n }\n\n const options = this.getOptions();\n const { release, environment, tunnel } = options;\n\n const serializedCheckIn: SerializedCheckIn = {\n check_in_id: id,\n monitor_slug: checkIn.monitorSlug,\n status: checkIn.status,\n release,\n environment,\n };\n\n if ('duration' in checkIn) {\n serializedCheckIn.duration = checkIn.duration;\n }\n\n if (monitorConfig) {\n serializedCheckIn.monitor_config = {\n schedule: monitorConfig.schedule,\n checkin_margin: monitorConfig.checkinMargin,\n max_runtime: monitorConfig.maxRuntime,\n timezone: monitorConfig.timezone,\n failure_issue_threshold: monitorConfig.failureIssueThreshold,\n recovery_threshold: monitorConfig.recoveryThreshold,\n };\n }\n\n const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope);\n if (traceContext) {\n serializedCheckIn.contexts = {\n trace: traceContext,\n };\n }\n\n const envelope = createCheckInEnvelope(\n serializedCheckIn,\n dynamicSamplingContext,\n this.getSdkMetadata(),\n tunnel,\n this.getDsn(),\n );\n\n DEBUG_BUILD && debug.log('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n\n return id;\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all internal state to allow the client to be garbage collected.\n * It clears hooks, event processors, integrations, transport, and other internal references.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n *\n * Subclasses should override this method to clean up their own resources and call `super.dispose()`.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('Disposing client...');\n\n for (const hookName of Object.keys(this._hooks)) {\n this._hooks[hookName]?.clear();\n }\n\n this._hooks = {};\n this._eventProcessors.length = 0;\n this._integrations = {};\n this._outcomes = {};\n (this as unknown as { _transport?: Transport })._transport = undefined;\n this._promiseBuffer = makePromiseBuffer(DEFAULT_TRANSPORT_BUFFER_SIZE);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n if (this._options.platform) {\n event.platform = event.platform || this._options.platform;\n }\n\n if (this._options.runtime) {\n event.contexts = {\n ...event.contexts,\n runtime: event.contexts?.runtime || this._options.runtime,\n };\n }\n\n if (this._options.serverName) {\n event.server_name = event.server_name || this._options.serverName;\n }\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n\n /**\n * Process a server-side metric before it is captured.\n */\n private _setUpMetricsProcessing(): void {\n this.on('processMetric', metric => {\n if (this._options.serverName) {\n metric.attributes = {\n 'server.address': this._options.serverName,\n ...metric.attributes,\n };\n }\n });\n }\n}\n\nfunction setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void {\n const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;\n if (requestSession) {\n // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular\n // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the\n // original isolation scope that the http integration stored away.\n const isHandledException = eventHint?.mechanism?.handled ?? true;\n // A request session can go from \"errored\" -> \"crashed\" but not \"crashed\" -> \"errored\".\n // Crashed (unhandled exception) is worse than errored (handled exception).\n if (isHandledException && requestSession.status !== 'crashed') {\n requestSession.status = 'errored';\n } else if (!isHandledException) {\n requestSession.status = 'crashed';\n }\n }\n}\n"],"names":["Client","registerSpanErrorInstrumentation","addUserAgentToTransportHeaders","eventFromUnknownInput","resolvedSyncPromise","eventFromMessage","uuid4","DEBUG_BUILD","debug","_getTraceInfoFromScope","createCheckInEnvelope","makePromiseBuffer","DEFAULT_TRANSPORT_BUFFER_SIZE","getIsolationScope"],"mappings":";;;;;;;;;;;;;;;;AA2BA;AACA;AACA;AACO,MAAM;;AAEb,SAAUA,aAAM,CAAI;AACpB;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAAK;AACjC;AACA,IAAIC,uCAAgC,EAAE;;AAEtC,IAAIC,wCAA8B,CAAC,OAAO,CAAC;;AAE3C,IAAI,KAAK,CAAC,OAAO,CAAC;;AAElB,IAAI,IAAI,CAAC,uBAAuB,EAAE;AAClC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,kBAAkB,CAAC,SAAS,EAAW,IAAI,EAAkC;AACtF,IAAI,MAAM,KAAA,GAAQC,kCAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,SAAS,EAAE,IAAI,CAAC;AACzF,IAAI,KAAK,CAAC,KAAA,GAAQ,OAAO;;AAEzB,IAAI,OAAOC,+BAAmB,CAAC,KAAK,CAAC;AACrC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,gBAAgB;AACzB,IAAI,OAAO;AACX,IAAI,KAAK,GAAkB,MAAM;AACjC,IAAI,IAAI;AACR,IAAwB;AACxB,IAAI,OAAOA,+BAAmB;AAC9B,MAAMC,6BAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC;AACvG,KAAK;AACL,EAAE;;AAEF;AACA;AACA;AACA,GAAS,gBAAgB,CAAC,SAAS,EAAW,IAAI,EAAc,KAAK,EAAkB;AACvF,IAAI,wCAAwC,CAAC,IAAI,CAAC;AAClD,IAAI,OAAO,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAA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AAC1C,IAAI,IAAI,CAAC,EAAE,CAAC,eAAe,EAAE,UAAU;AACvC,MAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE;AACpC,QAAQ,MAAM,CAAC,UAAA,GAAa;AAC5B,UAAU,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU;AACpD,UAAU,GAAG,MAAM,CAAC,UAAU;AAC9B,SAAS;AACT,MAAM;AACN,IAAI,CAAC,CAAC;AACN,EAAE;AACF;;AAEA,SAAS,wCAAwC,CAAC,SAAS,EAAoB;AAC/E,EAAE,MAAM,cAAA,GAAiBC,+BAAiB,EAAE,CAAC,YAAY,EAAE,CAAC,qBAAqB,CAAC,cAAc;AAChG,EAAE,IAAI,cAAc,EAAE;AACtB;AACA;AACA;AACA,IAAI,MAAM,qBAAqB,SAAS,EAAE,SAAS,EAAE,OAAA,IAAW,IAAI;AACpE;AACA;AACA,IAAI,IAAI,kBAAA,IAAsB,cAAc,CAAC,MAAA,KAAW,SAAS,EAAE;AACnE,MAAM,cAAc,CAAC,MAAA,GAAS,SAAS;AACvC,IAAI,OAAO,IAAI,CAAC,kBAAkB,EAAE;AACpC,MAAM,cAAc,CAAC,MAAA,GAAS,SAAS;AACvC,IAAI;AACJ,EAAE;AACF;;;;"}
1
+ {"version":3,"file":"server-runtime-client.js","sources":["../../src/server-runtime-client.ts"],"sourcesContent":["import { createCheckInEnvelope } from './checkin';\nimport { Client } from './client';\nimport { getIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Scope } from './scope';\nimport { registerSpanErrorInstrumentation } from './tracing';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base';\nimport { addUserAgentToTransportHeaders } from './transports/userAgent';\nimport type { CheckIn, MonitorConfig, SerializedCheckIn } from './types-hoist/checkin';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { ClientOptions } from './types-hoist/options';\nimport type { ParameterizedString } from './types-hoist/parameterize';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { BaseTransportOptions, Transport } from './types-hoist/transport';\nimport { debug } from './utils/debug-logger';\nimport { eventFromMessage, eventFromUnknownInput } from './utils/eventbuilder';\nimport { uuid4 } from './utils/misc';\nimport { makePromiseBuffer } from './utils/promisebuffer';\nimport { resolvedSyncPromise } from './utils/syncpromise';\nimport { _getTraceInfoFromScope } from './utils/trace-info';\n\nexport interface ServerRuntimeClientOptions extends ClientOptions<BaseTransportOptions> {\n platform?: string;\n runtime?: { name: string; version?: string };\n serverName?: string;\n}\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nexport class ServerRuntimeClient<\n O extends ClientOptions & ServerRuntimeClientOptions = ServerRuntimeClientOptions,\n> extends Client<O> {\n private _disposeCallbacks: (() => void)[] = [];\n\n /**\n * Creates a new Edge SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: O) {\n // Server clients always support tracing\n registerSpanErrorInstrumentation();\n\n addUserAgentToTransportHeaders(options);\n\n super(options);\n\n this._setUpMetricsProcessing();\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint);\n event.level = 'error';\n\n return resolvedSyncPromise(event);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return resolvedSyncPromise(\n eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n );\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {\n setCurrentRequestSessionErroredOrCrashed(hint);\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string {\n // If the event is of type Exception, then a request session should be captured\n const isException = !event.type && event.exception?.values && event.exception.values.length > 0;\n if (isException) {\n setCurrentRequestSessionErroredOrCrashed(hint);\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\n public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();\n if (!this._isEnabled()) {\n DEBUG_BUILD && debug.warn('SDK not enabled, will not capture check-in.');\n return id;\n }\n\n const options = this.getOptions();\n const { release, environment, tunnel } = options;\n\n const serializedCheckIn: SerializedCheckIn = {\n check_in_id: id,\n monitor_slug: checkIn.monitorSlug,\n status: checkIn.status,\n release,\n environment,\n };\n\n if ('duration' in checkIn) {\n serializedCheckIn.duration = checkIn.duration;\n }\n\n if (monitorConfig) {\n serializedCheckIn.monitor_config = {\n schedule: monitorConfig.schedule,\n checkin_margin: monitorConfig.checkinMargin,\n max_runtime: monitorConfig.maxRuntime,\n timezone: monitorConfig.timezone,\n failure_issue_threshold: monitorConfig.failureIssueThreshold,\n recovery_threshold: monitorConfig.recoveryThreshold,\n };\n }\n\n const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope);\n if (traceContext) {\n serializedCheckIn.contexts = {\n trace: traceContext,\n };\n }\n\n const envelope = createCheckInEnvelope(\n serializedCheckIn,\n dynamicSamplingContext,\n this.getSdkMetadata(),\n tunnel,\n this.getDsn(),\n );\n\n DEBUG_BUILD && debug.log('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n\n return id;\n }\n\n /**\n * @inheritDoc\n */\n public override registerCleanup(callback: () => void): void {\n this._disposeCallbacks.push(callback);\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all internal state to allow the client to be garbage collected.\n * It clears hooks, event processors, integrations, transport, and other internal references.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n *\n * Subclasses should override this method to clean up their own resources and call `super.dispose()`.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('Disposing client...');\n\n // Run all registered cleanup callbacks\n for (const callback of this._disposeCallbacks) {\n try {\n callback();\n } catch {\n // Ignore errors in cleanup callbacks\n }\n }\n this._disposeCallbacks.length = 0;\n\n for (const hookName of Object.keys(this._hooks)) {\n this._hooks[hookName]?.clear();\n }\n\n this._hooks = {};\n this._eventProcessors.length = 0;\n this._integrations = {};\n this._outcomes = {};\n (this as unknown as { _transport?: Transport })._transport = undefined;\n this._promiseBuffer = makePromiseBuffer(DEFAULT_TRANSPORT_BUFFER_SIZE);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n if (this._options.platform) {\n event.platform = event.platform || this._options.platform;\n }\n\n if (this._options.runtime) {\n event.contexts = {\n ...event.contexts,\n runtime: event.contexts?.runtime || this._options.runtime,\n };\n }\n\n if (this._options.serverName) {\n event.server_name = event.server_name || this._options.serverName;\n }\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n\n /**\n * Process a server-side metric before it is captured.\n */\n private _setUpMetricsProcessing(): void {\n this.on('processMetric', metric => {\n if (this._options.serverName) {\n metric.attributes = {\n 'server.address': this._options.serverName,\n ...metric.attributes,\n };\n }\n });\n }\n}\n\nfunction setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void {\n const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;\n if (requestSession) {\n // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular\n // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the\n // original isolation scope that the http integration stored away.\n const isHandledException = eventHint?.mechanism?.handled ?? true;\n // A request session can go from \"errored\" -> \"crashed\" but not \"crashed\" -> \"errored\".\n // Crashed (unhandled exception) is worse than errored (handled exception).\n if (isHandledException && requestSession.status !== 'crashed') {\n requestSession.status = 'errored';\n } else if (!isHandledException) {\n requestSession.status = 'crashed';\n }\n }\n}\n"],"names":["Client","registerSpanErrorInstrumentation","addUserAgentToTransportHeaders","eventFromUnknownInput","resolvedSyncPromise","eventFromMessage","uuid4","DEBUG_BUILD","debug","_getTraceInfoFromScope","createCheckInEnvelope","makePromiseBuffer","DEFAULT_TRANSPORT_BUFFER_SIZE","getIsolationScope"],"mappings":";;;;;;;;;;;;;;;;AA2BA;AACA;AACA;AACO,MAAM;;AAEb,SAAUA,aAAM,CAAI;AACpB,GAAE,MAAA,GAAA,CAAA,IAAA,CAAQ,iBAAiB,GAAmB,GAAC;;AAE/C;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAAK;AACjC;AACA,IAAIC,uCAAgC,EAAE;;AAEtC,IAAIC,wCAA8B,CAAC,OAAO,CAAC;;AAE3C,IAAI,KAAK,CAAC,OAAO,CAAA,CAAA,mBAAA,CAAA,SAAA,CAAA,MAAA,CAAA,IAAA,CAAA,IAAA,CAAA;AAEjB,IAAI,IAAI,CAAC,uBAAuB,EAAE;AAClC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,kBAAkB,CAAC,SAAS,EAAW,IAAI,EAAkC;AACtF,IAAI,MAAM,KAAA,GAAQC,kCAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,SAAS,EAAE,IAAI,CAAC;AACzF,IAAI,KAAK,CAAC,KAAA,GAAQ,OAAO;;AAEzB,IAAI,OAAOC,+BAAmB,CAAC,KAAK,CAAC;AACrC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,gBAAgB;AACzB,IAAI,OAAO;AACX,IAAI,KAAK,GAAkB,MAAM;AACjC,IAAI,IAAI;AACR,IAAwB;AACxB,IAAI,OAAOA,+BAAmB;AAC9B,MAAMC,6BAAgB,CAAC,IAAI,CAAC,QAA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AAA,IAAsB,cAAc,CAAC,MAAA,KAAW,SAAS,EAAE;AACnE,MAAM,cAAc,CAAC,MAAA,GAAS,SAAS;AACvC,IAAI,OAAO,IAAI,CAAC,kBAAkB,EAAE;AACpC,MAAM,cAAc,CAAC,MAAA,GAAS,SAAS;AACvC,IAAI;AACJ,EAAE;AACF;;;;"}
@@ -214,6 +214,11 @@ const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';
214
214
  */
215
215
  const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';
216
216
 
217
+ /**
218
+ * The span operation name for executing a tool
219
+ */
220
+ const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';
221
+
217
222
  /**
218
223
  * The tool name for tool call spans
219
224
  */
@@ -249,6 +254,7 @@ exports.GEN_AI_AGENT_NAME_ATTRIBUTE = GEN_AI_AGENT_NAME_ATTRIBUTE;
249
254
  exports.GEN_AI_CONVERSATION_ID_ATTRIBUTE = GEN_AI_CONVERSATION_ID_ATTRIBUTE;
250
255
  exports.GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE;
251
256
  exports.GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE;
257
+ exports.GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE;
252
258
  exports.GEN_AI_INPUT_MESSAGES_ATTRIBUTE = GEN_AI_INPUT_MESSAGES_ATTRIBUTE;
253
259
  exports.GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE;
254
260
  exports.GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE;
@@ -1 +1 @@
1
- {"version":3,"file":"gen-ai-attributes.js","sources":["../../../../src/tracing/ai/gen-ai-attributes.ts"],"sourcesContent":["/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nexport const GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Stop sequences for the model request\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nexport const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nexport const GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * Original length of messages array, used to indicate truncations had occured\n */\nexport const GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = 'sentry.sdk_meta.gen_ai.input.messages.original_length';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_INPUT_MESSAGES_ATTRIBUTE = 'gen_ai.input.messages';\n\n/**\n * The model's response messages including text and tool calls\n * Only recorded when recordOutputs is enabled\n * Format: stringified array of message objects with role, parts, and finish_reason\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n */\nexport const GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE = 'gen_ai.output.messages';\n\n/**\n * The system instructions extracted from system messages\n * Only recorded when recordInputs is enabled\n * According to OpenTelemetry spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system-instructions\n */\nexport const GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = 'gen_ai.system_instructions';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nexport const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nexport const GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nexport const GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The conversation ID for linking messages across API calls\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n\n/**\n * The number of cache creation input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nexport const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n/**\n * The span operation name for generating content\n */\nexport const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content';\n\n/**\n * The embeddings input\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';\n\n/**\n * The span operation for embeddings\n */\nexport const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for reranking\n */\nexport const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';\n\n/**\n * The span operation name for executing a tool\n */\nexport const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';\n\n/**\n * The tool name for tool call spans\n */\nexport const GEN_AI_TOOL_NAME_ATTRIBUTE = 'gen_ai.tool.name';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n\n/**\n * The tool type (e.g., 'function')\n */\nexport const GEN_AI_TOOL_TYPE_ATTRIBUTE = 'gen_ai.tool.type';\n\n/**\n * The tool input/arguments\n */\nexport const GEN_AI_TOOL_INPUT_ATTRIBUTE = 'gen_ai.tool.input';\n\n/**\n * The tool output/result\n */\nexport const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';\n\n/**\n * The description of the tool being used\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description\n */\nexport const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,yCAAA,GAA4C;;AAEzD;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAO9C;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAErD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACO,MAAM,kDAAA,GAAqD;;AAElE;AACA;AACA;AACO,MAAM,8CAAA,GAAiD;;AAE9D;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAOvD;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;AAEjD;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAYrD;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"gen-ai-attributes.js","sources":["../../../../src/tracing/ai/gen-ai-attributes.ts"],"sourcesContent":["/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nexport const GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Stop sequences for the model request\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nexport const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nexport const GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * Original length of messages array, used to indicate truncations had occured\n */\nexport const GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = 'sentry.sdk_meta.gen_ai.input.messages.original_length';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_INPUT_MESSAGES_ATTRIBUTE = 'gen_ai.input.messages';\n\n/**\n * The model's response messages including text and tool calls\n * Only recorded when recordOutputs is enabled\n * Format: stringified array of message objects with role, parts, and finish_reason\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n */\nexport const GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE = 'gen_ai.output.messages';\n\n/**\n * The system instructions extracted from system messages\n * Only recorded when recordInputs is enabled\n * According to OpenTelemetry spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system-instructions\n */\nexport const GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = 'gen_ai.system_instructions';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nexport const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nexport const GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nexport const GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The conversation ID for linking messages across API calls\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n\n/**\n * The number of cache creation input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nexport const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n/**\n * The span operation name for generating content\n */\nexport const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content';\n\n/**\n * The embeddings input\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';\n\n/**\n * The span operation for embeddings\n */\nexport const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for reranking\n */\nexport const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';\n\n/**\n * The span operation name for executing a tool\n */\nexport const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';\n\n/**\n * The tool name for tool call spans\n */\nexport const GEN_AI_TOOL_NAME_ATTRIBUTE = 'gen_ai.tool.name';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n\n/**\n * The tool type (e.g., 'function')\n */\nexport const GEN_AI_TOOL_TYPE_ATTRIBUTE = 'gen_ai.tool.type';\n\n/**\n * The tool input/arguments\n */\nexport const GEN_AI_TOOL_INPUT_ATTRIBUTE = 'gen_ai.tool.input';\n\n/**\n * The tool output/result\n */\nexport const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';\n\n/**\n * The description of the tool being used\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description\n */\nexport const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,uBAA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ACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACO,MAAM,kDAAA,GAAqD;;AAElE;AACA;AACA;AACO,MAAM,8CAAA,GAAiD;;AAE9D;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAOvD;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;AAEjD;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAOrD;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAEvD;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -115,7 +115,13 @@ function startIdleSpan(startSpanOptions, options = {}) {
115
115
  // Ignored spans will get dropped later (in the client) but since we already adjust
116
116
  // the idle span end timestamp here, we can already take to-be-ignored spans out of
117
117
  // the calculation here.
118
- if (ignoreSpans && shouldIgnoreSpan.shouldIgnoreSpan(currentSpanJson, ignoreSpans)) {
118
+ if (
119
+ ignoreSpans &&
120
+ shouldIgnoreSpan.shouldIgnoreSpan(
121
+ { description: currentSpanJson.description, op: currentSpanJson.op, attributes: currentSpanJson.data },
122
+ ignoreSpans,
123
+ )
124
+ ) {
119
125
  return acc;
120
126
  }
121
127
  return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;
@@ -1 +1 @@
1
- {"version":3,"file":"idleSpan.js","sources":["../../../src/tracing/idleSpan.ts"],"sourcesContent":["import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span';\nimport { _setSpanForScope } from '../utils/spanOnScope';\nimport {\n getActiveSpan,\n getSpanDescendants,\n removeChildSpanFromSpan,\n spanTimeInputToSeconds,\n spanToJSON,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK } from './spanstatus';\nimport { startInactiveSpan } from './trace';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1_000,\n finalTimeout: 30_000,\n childSpanTimeout: 15_000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\nconst FINISH_REASON_CANCELLED = 'cancelled';\n\n// unused\nconst FINISH_REASON_DOCUMENT_HIDDEN = 'documentHidden';\n\n// unused in this file, but used in BrowserTracing\nconst FINISH_REASON_INTERRUPTED = 'interactionInterrupted';\n\ntype IdleSpanFinishReason =\n | typeof FINISH_REASON_CANCELLED\n | typeof FINISH_REASON_DOCUMENT_HIDDEN\n | typeof FINISH_REASON_EXTERNAL_FINISH\n | typeof FINISH_REASON_FINAL_TIMEOUT\n | typeof FINISH_REASON_HEARTBEAT_FAILED\n | typeof FINISH_REASON_IDLE_TIMEOUT\n | typeof FINISH_REASON_INTERRUPTED;\n\ninterface IdleSpanOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n */\n idleTimeout: number;\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n */\n finalTimeout: number;\n /**\n * The max. time a child span may run.\n * If the time since the last span was started exceeds this time, the idle span will finish.\n */\n childSpanTimeout?: number;\n /**\n * When set to `true`, will disable the idle timeout and child timeout\n * until the `idleSpanEnableAutoFinish` hook is emitted for the idle span.\n * The final timeout mechanism will not be affected by this option,\n * meaning the idle span will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n disableAutoFinish?: boolean;\n\n /** Allows to configure a hook that is called when the idle span is ended, before it is processed. */\n beforeSpanEnd?: (span: Span) => void;\n\n /**\n * If set to `true`, the idle span will be trimmed to the latest span end timestamp of its children.\n *\n * @default `true`.\n */\n trimIdleSpanEndTimestamp?: boolean;\n}\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nexport function startIdleSpan(startSpanOptions: StartSpanOptions, options: Partial<IdleSpanOptions> = {}): Span {\n // Activities store a list of active spans\n const activities = new Map<string, boolean>();\n\n // We should not use heartbeat if we finished a span\n let _finished = false;\n\n // Timer that tracks idleTimeout\n let _idleTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n // Timer that tracks maxSpanTime for child spans\n let _childSpanTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n // The reason why the span was finished\n let _finishReason: IdleSpanFinishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed: boolean = !options.disableAutoFinish;\n\n const _cleanupHooks: (() => void)[] = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n trimIdleSpanEndTimestamp = true,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n const dsc = {\n sample_rate: '0',\n sampled: 'false',\n ...getDynamicSamplingContextFromSpan(span),\n } satisfies Partial<DynamicSamplingContext>;\n freezeDscOnSpan(span, dsc);\n\n return span;\n }\n\n const scope = getCurrentScope();\n const previousActiveSpan = getActiveSpan();\n const span = _startIdleSpan(startSpanOptions);\n\n // We patch span.end to ensure we can run some things before the span is ended\n // eslint-disable-next-line @typescript-eslint/unbound-method\n span.end = new Proxy(span.end, {\n apply(target, thisArg, args: Parameters<Span['end']>) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\n }\n\n // If the span is non-recording, nothing more to do here...\n // This is the case if tracing is enabled but this specific span was not sampled\n if (thisArg instanceof SentryNonRecordingSpan) {\n return;\n }\n\n // Just ensuring that this keeps working, even if we ever have more arguments here\n const [definedEndTimestamp, ...rest] = args;\n const timestamp = definedEndTimestamp || timestampInSeconds();\n const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n // Ensure we end with the last span timestamp, if possible\n const spans = getSpanDescendants(span).filter(child => child !== span);\n\n const spanJson = spanToJSON(span);\n\n // If we have no spans, we just end, nothing else to do here\n // Likewise, if users explicitly ended the span, we simply end the span without timestamp adjustment\n if (!spans.length || !trimIdleSpanEndTimestamp) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const ignoreSpans = client.getOptions().ignoreSpans;\n\n const latestSpanEndTimestamp = spans?.reduce((acc: number | undefined, current) => {\n const currentSpanJson = spanToJSON(current);\n if (!currentSpanJson.timestamp) {\n return acc;\n }\n // Ignored spans will get dropped later (in the client) but since we already adjust\n // the idle span end timestamp here, we can already take to-be-ignored spans out of\n // the calculation here.\n if (ignoreSpans && shouldIgnoreSpan(currentSpanJson, ignoreSpans)) {\n return acc;\n }\n return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;\n }, undefined);\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanJson.start_timestamp;\n\n // The final endTimestamp should:\n // * Never be before the span start timestamp\n // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n // * Otherwise be the passed end timestamp\n // Final timestamp can never be after finalTimeout\n const endTimestamp = Math.min(\n spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n );\n\n onIdleSpanEnded(endTimestamp);\n return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n },\n });\n\n /**\n * Cancels the existing idle timeout, if there is one.\n */\n function _cancelIdleTimeout(): void {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = undefined;\n }\n }\n\n /**\n * Cancels the existing child span timeout, if there is one.\n */\n function _cancelChildSpanTimeout(): void {\n if (_childSpanTimeoutID) {\n clearTimeout(_childSpanTimeoutID);\n _childSpanTimeoutID = undefined;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n function _restartIdleTimeout(endTimestamp?: number): void {\n _cancelIdleTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && activities.size === 0 && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n span.end(endTimestamp);\n }\n }, idleTimeout);\n }\n\n /**\n * Restarts child span timeout, if there is none running it will start one.\n */\n function _restartChildSpanTimeout(endTimestamp?: number): void {\n _cancelChildSpanTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n span.end(endTimestamp);\n }\n }, childSpanTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n function _pushActivity(spanId: string): void {\n _cancelIdleTimeout();\n activities.set(spanId, true);\n\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n function _popActivity(spanId: string): void {\n if (activities.has(spanId)) {\n activities.delete(spanId);\n }\n\n if (activities.size === 0) {\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n _cancelChildSpanTimeout();\n }\n }\n\n function onIdleSpanEnded(endTimestamp: number): void {\n _finished = true;\n activities.clear();\n\n _cleanupHooks.forEach(cleanup => cleanup());\n\n _setSpanForScope(scope, previousActiveSpan);\n\n const spanJSON = spanToJSON(span);\n\n const { start_timestamp: startTimestamp } = spanJSON;\n // This should never happen, but to make TS happy...\n if (!startTimestamp) {\n return;\n }\n\n const attributes = spanJSON.data;\n if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n }\n\n // Set span status to 'ok' if it hasn't been explicitly set to an error status\n const currentStatus = spanJSON.status;\n if (!currentStatus || currentStatus === 'unknown') {\n span.setStatus({ code: SPAN_STATUS_OK });\n }\n\n debug.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n const childSpans = getSpanDescendants(span).filter(child => child !== span);\n\n let discardedSpans = 0;\n childSpans.forEach(childSpan => {\n // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n if (childSpan.isRecording()) {\n childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n childSpan.end(endTimestamp);\n DEBUG_BUILD &&\n debug.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n }\n\n const childSpanJSON = spanToJSON(childSpan);\n const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n if (!spanStartedBeforeIdleSpanEnd) {\n debug.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n debug.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n }\n }\n\n if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n removeChildSpanFromSpan(span, childSpan);\n discardedSpans++;\n }\n });\n\n if (discardedSpans > 0) {\n span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n }\n }\n\n _cleanupHooks.push(\n client.on('spanStart', startedSpan => {\n // If we already finished the idle span,\n // or if this is the idle span itself being started,\n // or if the started span has already been closed,\n // we don't care about it for activity\n if (\n _finished ||\n startedSpan === span ||\n !!spanToJSON(startedSpan).timestamp ||\n (startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan())\n ) {\n return;\n }\n\n const allSpans = getSpanDescendants(span);\n\n // If the span that was just started is a child of the idle span, we should track it\n if (allSpans.includes(startedSpan)) {\n _pushActivity(startedSpan.spanContext().spanId);\n }\n }),\n );\n\n _cleanupHooks.push(\n client.on('spanEnd', endedSpan => {\n if (_finished) {\n return;\n }\n\n _popActivity(endedSpan.spanContext().spanId);\n }),\n );\n\n _cleanupHooks.push(\n client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish => {\n if (spanToAllowAutoFinish === span) {\n _autoFinishAllowed = true;\n _restartIdleTimeout();\n\n if (activities.size) {\n _restartChildSpanTimeout();\n }\n }\n }),\n );\n\n // We only start the initial idle timeout if we are not delaying the auto finish\n if (!options.disableAutoFinish) {\n _restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!_finished) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n span.end();\n }\n }, finalTimeout);\n\n return span;\n}\n\nfunction _startIdleSpan(options: StartSpanOptions): Span {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && debug.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n"],"names":["getClient","hasSpansEnabled","SentryNonRecordingSpan","getDynamicSamplingContextFromSpan","freezeDscOnSpan","getCurrentScope","getActiveSpan","timestampInSeconds","spanTimeInputToSeconds","getSpanDescendants","spanToJSON","shouldIgnoreSpan","_setSpanForScope","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","SPAN_STATUS_OK","debug","SPAN_STATUS_ERROR","DEBUG_BUILD","removeChildSpanFromSpan","SentrySpan","startInactiveSpan"],"mappings":";;;;;;;;;;;;;;;;;AAwBO,MAAM,mBAAmB;AAChC,EAAE,WAAW,EAAE,IAAK;AACpB,EAAE,YAAY,EAAE,KAAM;AACtB,EAAE,gBAAgB,EAAE,KAAM;AAC1B;;AAEA,MAAM,8BAAA,GAAiC,iBAAiB;AACxD,MAAM,0BAAA,GAA6B,aAAa;AAChD,MAAM,2BAAA,GAA8B,cAAc;AAClD,MAAM,6BAAA,GAAgC,gBAAgB;;AAwDtD;AACA;AACA;AACA;AACO,SAAS,aAAa,CAAC,gBAAgB,EAAoB,OAAO,GAA6B,EAAE,EAAQ;AAChH;AACA,EAAE,MAAM,UAAA,GAAa,IAAI,GAAG,EAAmB;;AAE/C;AACA,EAAE,IAAI,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BAAiB,CAAC,OAAO,CAAC;;AAEzC,EAAER,4BAAgB,CAACP,6BAAe,EAAE,EAAE,IAAI,CAAC;;AAE3C,EAAEY,0BAAeF,iBAAK,CAAC,GAAG,CAAC,wCAAwC,CAAC;;AAEpE,EAAE,OAAO,IAAI;AACb;;;;;"}
1
+ {"version":3,"file":"idleSpan.js","sources":["../../../src/tracing/idleSpan.ts"],"sourcesContent":["import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span';\nimport { _setSpanForScope } from '../utils/spanOnScope';\nimport {\n getActiveSpan,\n getSpanDescendants,\n removeChildSpanFromSpan,\n spanTimeInputToSeconds,\n spanToJSON,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK } from './spanstatus';\nimport { startInactiveSpan } from './trace';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1_000,\n finalTimeout: 30_000,\n childSpanTimeout: 15_000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\nconst FINISH_REASON_CANCELLED = 'cancelled';\n\n// unused\nconst FINISH_REASON_DOCUMENT_HIDDEN = 'documentHidden';\n\n// unused in this file, but used in BrowserTracing\nconst FINISH_REASON_INTERRUPTED = 'interactionInterrupted';\n\ntype IdleSpanFinishReason =\n | typeof FINISH_REASON_CANCELLED\n | typeof FINISH_REASON_DOCUMENT_HIDDEN\n | typeof FINISH_REASON_EXTERNAL_FINISH\n | typeof FINISH_REASON_FINAL_TIMEOUT\n | typeof FINISH_REASON_HEARTBEAT_FAILED\n | typeof FINISH_REASON_IDLE_TIMEOUT\n | typeof FINISH_REASON_INTERRUPTED;\n\ninterface IdleSpanOptions {\n /**\n * The time that has to pass without any span being created.\n * If this time is exceeded, the idle span will finish.\n */\n idleTimeout: number;\n /**\n * The max. time an idle span may run.\n * If this time is exceeded, the idle span will finish no matter what.\n */\n finalTimeout: number;\n /**\n * The max. time a child span may run.\n * If the time since the last span was started exceeds this time, the idle span will finish.\n */\n childSpanTimeout?: number;\n /**\n * When set to `true`, will disable the idle timeout and child timeout\n * until the `idleSpanEnableAutoFinish` hook is emitted for the idle span.\n * The final timeout mechanism will not be affected by this option,\n * meaning the idle span will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n disableAutoFinish?: boolean;\n\n /** Allows to configure a hook that is called when the idle span is ended, before it is processed. */\n beforeSpanEnd?: (span: Span) => void;\n\n /**\n * If set to `true`, the idle span will be trimmed to the latest span end timestamp of its children.\n *\n * @default `true`.\n */\n trimIdleSpanEndTimestamp?: boolean;\n}\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nexport function startIdleSpan(startSpanOptions: StartSpanOptions, options: Partial<IdleSpanOptions> = {}): Span {\n // Activities store a list of active spans\n const activities = new Map<string, boolean>();\n\n // We should not use heartbeat if we finished a span\n let _finished = false;\n\n // Timer that tracks idleTimeout\n let _idleTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n // Timer that tracks maxSpanTime for child spans\n let _childSpanTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n // The reason why the span was finished\n let _finishReason: IdleSpanFinishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed: boolean = !options.disableAutoFinish;\n\n const _cleanupHooks: (() => void)[] = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n trimIdleSpanEndTimestamp = true,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n const dsc = {\n sample_rate: '0',\n sampled: 'false',\n ...getDynamicSamplingContextFromSpan(span),\n } satisfies Partial<DynamicSamplingContext>;\n freezeDscOnSpan(span, dsc);\n\n return span;\n }\n\n const scope = getCurrentScope();\n const previousActiveSpan = getActiveSpan();\n const span = _startIdleSpan(startSpanOptions);\n\n // We patch span.end to ensure we can run some things before the span is ended\n // eslint-disable-next-line @typescript-eslint/unbound-method\n span.end = new Proxy(span.end, {\n apply(target, thisArg, args: Parameters<Span['end']>) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\n }\n\n // If the span is non-recording, nothing more to do here...\n // This is the case if tracing is enabled but this specific span was not sampled\n if (thisArg instanceof SentryNonRecordingSpan) {\n return;\n }\n\n // Just ensuring that this keeps working, even if we ever have more arguments here\n const [definedEndTimestamp, ...rest] = args;\n const timestamp = definedEndTimestamp || timestampInSeconds();\n const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n // Ensure we end with the last span timestamp, if possible\n const spans = getSpanDescendants(span).filter(child => child !== span);\n\n const spanJson = spanToJSON(span);\n\n // If we have no spans, we just end, nothing else to do here\n // Likewise, if users explicitly ended the span, we simply end the span without timestamp adjustment\n if (!spans.length || !trimIdleSpanEndTimestamp) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const ignoreSpans = client.getOptions().ignoreSpans;\n\n const latestSpanEndTimestamp = spans?.reduce((acc: number | undefined, current) => {\n const currentSpanJson = spanToJSON(current);\n if (!currentSpanJson.timestamp) {\n return acc;\n }\n // Ignored spans will get dropped later (in the client) but since we already adjust\n // the idle span end timestamp here, we can already take to-be-ignored spans out of\n // the calculation here.\n if (\n ignoreSpans &&\n shouldIgnoreSpan(\n { description: currentSpanJson.description, op: currentSpanJson.op, attributes: currentSpanJson.data },\n ignoreSpans,\n )\n ) {\n return acc;\n }\n return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;\n }, undefined);\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanJson.start_timestamp;\n\n // The final endTimestamp should:\n // * Never be before the span start timestamp\n // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n // * Otherwise be the passed end timestamp\n // Final timestamp can never be after finalTimeout\n const endTimestamp = Math.min(\n spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n );\n\n onIdleSpanEnded(endTimestamp);\n return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n },\n });\n\n /**\n * Cancels the existing idle timeout, if there is one.\n */\n function _cancelIdleTimeout(): void {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = undefined;\n }\n }\n\n /**\n * Cancels the existing child span timeout, if there is one.\n */\n function _cancelChildSpanTimeout(): void {\n if (_childSpanTimeoutID) {\n clearTimeout(_childSpanTimeoutID);\n _childSpanTimeoutID = undefined;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n function _restartIdleTimeout(endTimestamp?: number): void {\n _cancelIdleTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && activities.size === 0 && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n span.end(endTimestamp);\n }\n }, idleTimeout);\n }\n\n /**\n * Restarts child span timeout, if there is none running it will start one.\n */\n function _restartChildSpanTimeout(endTimestamp?: number): void {\n _cancelChildSpanTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n span.end(endTimestamp);\n }\n }, childSpanTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n function _pushActivity(spanId: string): void {\n _cancelIdleTimeout();\n activities.set(spanId, true);\n\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n function _popActivity(spanId: string): void {\n if (activities.has(spanId)) {\n activities.delete(spanId);\n }\n\n if (activities.size === 0) {\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n _cancelChildSpanTimeout();\n }\n }\n\n function onIdleSpanEnded(endTimestamp: number): void {\n _finished = true;\n activities.clear();\n\n _cleanupHooks.forEach(cleanup => cleanup());\n\n _setSpanForScope(scope, previousActiveSpan);\n\n const spanJSON = spanToJSON(span);\n\n const { start_timestamp: startTimestamp } = spanJSON;\n // This should never happen, but to make TS happy...\n if (!startTimestamp) {\n return;\n }\n\n const attributes = spanJSON.data;\n if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n }\n\n // Set span status to 'ok' if it hasn't been explicitly set to an error status\n const currentStatus = spanJSON.status;\n if (!currentStatus || currentStatus === 'unknown') {\n span.setStatus({ code: SPAN_STATUS_OK });\n }\n\n debug.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n const childSpans = getSpanDescendants(span).filter(child => child !== span);\n\n let discardedSpans = 0;\n childSpans.forEach(childSpan => {\n // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n if (childSpan.isRecording()) {\n childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n childSpan.end(endTimestamp);\n DEBUG_BUILD &&\n debug.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n }\n\n const childSpanJSON = spanToJSON(childSpan);\n const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n if (!spanStartedBeforeIdleSpanEnd) {\n debug.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n debug.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n }\n }\n\n if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n removeChildSpanFromSpan(span, childSpan);\n discardedSpans++;\n }\n });\n\n if (discardedSpans > 0) {\n span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n }\n }\n\n _cleanupHooks.push(\n client.on('spanStart', startedSpan => {\n // If we already finished the idle span,\n // or if this is the idle span itself being started,\n // or if the started span has already been closed,\n // we don't care about it for activity\n if (\n _finished ||\n startedSpan === span ||\n !!spanToJSON(startedSpan).timestamp ||\n (startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan())\n ) {\n return;\n }\n\n const allSpans = getSpanDescendants(span);\n\n // If the span that was just started is a child of the idle span, we should track it\n if (allSpans.includes(startedSpan)) {\n _pushActivity(startedSpan.spanContext().spanId);\n }\n }),\n );\n\n _cleanupHooks.push(\n client.on('spanEnd', endedSpan => {\n if (_finished) {\n return;\n }\n\n _popActivity(endedSpan.spanContext().spanId);\n }),\n );\n\n _cleanupHooks.push(\n client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish => {\n if (spanToAllowAutoFinish === span) {\n _autoFinishAllowed = true;\n _restartIdleTimeout();\n\n if (activities.size) {\n _restartChildSpanTimeout();\n }\n }\n }),\n );\n\n // We only start the initial idle timeout if we are not delaying the auto finish\n if (!options.disableAutoFinish) {\n _restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!_finished) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n span.end();\n }\n }, finalTimeout);\n\n return span;\n}\n\nfunction _startIdleSpan(options: StartSpanOptions): Span {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && debug.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n"],"names":["getClient","hasSpansEnabled","SentryNonRecordingSpan","getDynamicSamplingContextFromSpan","freezeDscOnSpan","getCurrentScope","getActiveSpan","timestampInSeconds","spanTimeInputToSeconds","getSpanDescendants","spanToJSON","shouldIgnoreSpan","_setSpanForScope","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","SPAN_STATUS_OK","debug","SPAN_STATUS_ERROR","DEBUG_BUILD","removeChildSpanFromSpan","SentrySpan","startInactiveSpan"],"mappings":";;;;;;;;;;;;;;;;;AAwBO,MAAM,mBAAmB;AAChC,EAAE,WAAW,EAAE,IAAK;AACpB,EAAE,YAAY,EAAE,KAAM;AACtB,EAAE,gBAAgB,EAAE,KAAM;AAC1B;;AAEA,MAAM,8BAAA,GAAiC,iBAA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zB,EAAE;;AAEF,EAAE,UAAU,CAAC,MAAM;AACnB,IAAI,IAAI,CAAC,SAAS,EAAE;AACpB,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAEO,4BAAiB,EAAE,OAAO,EAAE,mBAAA,EAAqB,CAAC;AAC/E,MAAM,aAAA,GAAgB,2BAA2B;AACjD,MAAM,IAAI,CAAC,GAAG,EAAE;AAChB,IAAI;AACJ,EAAE,CAAC,EAAE,YAAY,CAAC;;AAElB,EAAE,OAAO,IAAI;AACb;;AAEA,SAAS,cAAc,CAAC,OAAO,EAA0B;AACzD,EAAE,MAAM,IAAA,GAAOI,uBAAiB,CAAC,OAAO,CAAC;;AAEzC,EAAER,4BAAgB,CAACP,6BAAe,EAAE,EAAE,IAAI,CAAC;;AAE3C,EAAEY,0BAAeF,iBAAK,CAAC,GAAG,CAAC,wCAAwC,CAAC;;AAEpE,EAAE,OAAO,IAAI;AACb;;;;;"}
@@ -9,6 +9,8 @@ const utils = require('../ai/utils.js');
9
9
  const constants = require('./constants.js');
10
10
  const utils$1 = require('./utils.js');
11
11
 
12
+ /* eslint-disable max-lines */
13
+
12
14
  /**
13
15
  * Creates a Sentry callback handler for LangChain
14
16
  * Returns a plain object that LangChain will call via duck-typing
@@ -85,6 +87,7 @@ function createLangChainCallbackHandler(options = {}) {
85
87
  name: `${operationName} ${modelName}`,
86
88
  op: 'gen_ai.chat',
87
89
  attributes: {
90
+ ...utils$1.getAgentNameFromMetadata(metadata),
88
91
  ...attributes,
89
92
  [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat',
90
93
  },
@@ -102,7 +105,7 @@ function createLangChainCallbackHandler(options = {}) {
102
105
  messages,
103
106
  runId,
104
107
  _parentRunId,
105
- _extraParams,
108
+ extraParams,
106
109
  tags,
107
110
  metadata,
108
111
  _runName,
@@ -116,6 +119,12 @@ function createLangChainCallbackHandler(options = {}) {
116
119
  invocationParams,
117
120
  metadata,
118
121
  );
122
+
123
+ const toolDefsJson = utils$1.extractToolDefinitions(extraParams);
124
+ if (toolDefsJson) {
125
+ attributes[genAiAttributes.GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = toolDefsJson;
126
+ }
127
+
119
128
  const modelName = attributes[genAiAttributes.GEN_AI_REQUEST_MODEL_ATTRIBUTE];
120
129
  const operationName = attributes[genAiAttributes.GEN_AI_OPERATION_NAME_ATTRIBUTE];
121
130
 
@@ -124,6 +133,7 @@ function createLangChainCallbackHandler(options = {}) {
124
133
  name: `${operationName} ${modelName}`,
125
134
  op: 'gen_ai.chat',
126
135
  attributes: {
136
+ ...utils$1.getAgentNameFromMetadata(metadata),
127
137
  ...attributes,
128
138
  [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat',
129
139
  },
@@ -176,17 +186,23 @@ function createLangChainCallbackHandler(options = {}) {
176
186
  runId,
177
187
  _parentRunId,
178
188
  _tags,
179
- _metadata,
189
+ metadata,
180
190
  _runType,
181
191
  runName,
182
192
  ) {
193
+ // Skip chain spans when inside an agent context (createReactAgent).
194
+ // The agent already creates an invoke_agent span; internal chain steps
195
+ // (ChannelWrite, Branch, prompt, etc.) are noise.
196
+ if (metadata?.__sentry_langgraph__) {
197
+ return;
198
+ }
199
+
183
200
  const chainName = runName || chain.name || 'unknown_chain';
184
201
  const attributes = {
185
202
  [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',
186
203
  'langchain.chain.name': chainName,
187
204
  };
188
205
 
189
- // Add inputs if recordInputs is enabled
190
206
  if (recordInputs) {
191
207
  attributes['langchain.chain.inputs'] = JSON.stringify(inputs);
192
208
  }
@@ -238,14 +254,30 @@ function createLangChainCallbackHandler(options = {}) {
238
254
  },
239
255
 
240
256
  // Tool Start Handler
241
- handleToolStart(tool, input, runId, _parentRunId) {
242
- const toolName = tool.name || 'unknown_tool';
257
+ handleToolStart(
258
+ tool,
259
+ input,
260
+ runId,
261
+ _parentRunId,
262
+ _tags,
263
+ metadata,
264
+ runName,
265
+ ) {
266
+ // Skip tool spans when inside an agent context (createReactAgent).
267
+ // Tool spans are created by wrapToolsWithSpans with richer attributes.
268
+ if (metadata?.__sentry_langgraph__) {
269
+ return;
270
+ }
271
+
272
+ // runName is set to tool.name by LangChain's StructuredTool.call()
273
+ const toolName = runName || tool.name || 'unknown_tool';
243
274
  const attributes = {
275
+ ...utils$1.getAgentNameFromMetadata(metadata),
244
276
  [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: constants.LANGCHAIN_ORIGIN,
277
+ [genAiAttributes.GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'execute_tool',
245
278
  [genAiAttributes.GEN_AI_TOOL_NAME_ATTRIBUTE]: toolName,
246
279
  };
247
280
 
248
- // Add input if recordInputs is enabled
249
281
  if (recordInputs) {
250
282
  attributes[genAiAttributes.GEN_AI_TOOL_INPUT_ATTRIBUTE] = input;
251
283
  }
@@ -270,10 +302,13 @@ function createLangChainCallbackHandler(options = {}) {
270
302
  handleToolEnd(output, runId) {
271
303
  const span = spanMap.get(runId);
272
304
  if (span?.isRecording()) {
273
- // Add output if recordOutputs is enabled
274
305
  if (recordOutputs) {
306
+ // LangChain tools may return ToolMessage objects — extract the content
307
+ const outputObj = output ;
308
+ const content =
309
+ outputObj && typeof outputObj === 'object' && 'content' in outputObj ? outputObj.content : output;
275
310
  span.setAttributes({
276
- [genAiAttributes.GEN_AI_TOOL_OUTPUT_ATTRIBUTE]: JSON.stringify(output),
311
+ [genAiAttributes.GEN_AI_TOOL_OUTPUT_ATTRIBUTE]: typeof content === 'string' ? content : JSON.stringify(content),
277
312
  });
278
313
  }
279
314
  exitSpan(runId);