@sentry/cloudflare 11.0.0-alpha.0 → 11.0.0-alpha.2

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 (345) hide show
  1. package/build/cjs/dev/baseSdk.js +20 -8
  2. package/build/cjs/dev/baseSdk.js.map +1 -1
  3. package/build/cjs/dev/client.js +116 -24
  4. package/build/cjs/dev/client.js.map +1 -1
  5. package/build/cjs/dev/clientCache.js +15 -0
  6. package/build/cjs/dev/clientCache.js.map +1 -0
  7. package/build/cjs/dev/defineCloudflareOptions.js.map +1 -1
  8. package/build/cjs/dev/durableobject.js +24 -8
  9. package/build/cjs/dev/durableobject.js.map +1 -1
  10. package/build/cjs/dev/flush.js +6 -4
  11. package/build/cjs/dev/flush.js.map +1 -1
  12. package/build/cjs/dev/index.js +4 -3
  13. package/build/cjs/dev/index.js.map +1 -1
  14. package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js +4 -4
  15. package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  16. package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js +8 -16
  17. package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  18. package/build/cjs/dev/instrumentations/worker/instrumentD1.js +5 -1
  19. package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  20. package/build/cjs/dev/instrumentations/worker/instrumentEmail.js +4 -2
  21. package/build/cjs/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
  22. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js +5 -5
  23. package/build/cjs/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  24. package/build/cjs/dev/instrumentations/worker/instrumentFetch.js +8 -8
  25. package/build/cjs/dev/instrumentations/worker/instrumentFetch.js.map +1 -1
  26. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js +4 -2
  27. package/build/cjs/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  28. package/build/cjs/dev/instrumentations/worker/instrumentR2.js +21 -18
  29. package/build/cjs/dev/instrumentations/worker/instrumentR2.js.map +1 -1
  30. package/build/cjs/dev/instrumentations/worker/instrumentRateLimit.js +6 -1
  31. package/build/cjs/dev/instrumentations/worker/instrumentRateLimit.js.map +1 -1
  32. package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js +4 -2
  33. package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
  34. package/build/cjs/dev/instrumentations/worker/instrumentTail.js +2 -0
  35. package/build/cjs/dev/instrumentations/worker/instrumentTail.js.map +1 -1
  36. package/build/cjs/dev/integrations/fetch.js +1 -11
  37. package/build/cjs/dev/integrations/fetch.js.map +1 -1
  38. package/build/cjs/dev/opentelemetry/tracer.js +2 -40
  39. package/build/cjs/dev/opentelemetry/tracer.js.map +1 -1
  40. package/build/cjs/dev/pages-plugin.js +2 -2
  41. package/build/cjs/dev/pages-plugin.js.map +1 -1
  42. package/build/cjs/dev/request.js +2 -123
  43. package/build/cjs/dev/request.js.map +1 -1
  44. package/build/cjs/dev/sdk.js +12 -6
  45. package/build/cjs/dev/sdk.js.map +1 -1
  46. package/build/cjs/dev/transport.js +1 -1
  47. package/build/cjs/dev/transport.js.map +1 -1
  48. package/build/cjs/dev/utils/invocationContext.js +41 -0
  49. package/build/cjs/dev/utils/invocationContext.js.map +1 -0
  50. package/build/cjs/dev/utils/invocationScope.js +7 -2
  51. package/build/cjs/dev/utils/invocationScope.js.map +1 -1
  52. package/build/cjs/dev/utils/rpcPropagation.js +15 -0
  53. package/build/cjs/dev/utils/rpcPropagation.js.map +1 -0
  54. package/build/cjs/dev/vite/autoInstrument.js +2 -1
  55. package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
  56. package/build/cjs/dev/vite/index.js +1 -1
  57. package/build/cjs/dev/vite/index.js.map +1 -1
  58. package/build/cjs/dev/vite/transform.js +30 -5
  59. package/build/cjs/dev/vite/transform.js.map +1 -1
  60. package/build/cjs/dev/vite/wranglerConfig.js +21 -1
  61. package/build/cjs/dev/vite/wranglerConfig.js.map +1 -1
  62. package/build/cjs/dev/withSentry.js.map +1 -1
  63. package/build/cjs/dev/workflows.js +45 -33
  64. package/build/cjs/dev/workflows.js.map +1 -1
  65. package/build/cjs/dev/wrapMethodWithSentry.js +51 -15
  66. package/build/cjs/dev/wrapMethodWithSentry.js.map +1 -1
  67. package/build/cjs/dev/wrapRequestHandlerWithInit.js +133 -0
  68. package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -0
  69. package/build/cjs/prod/baseSdk.js +20 -8
  70. package/build/cjs/prod/baseSdk.js.map +1 -1
  71. package/build/cjs/prod/client.js +116 -24
  72. package/build/cjs/prod/client.js.map +1 -1
  73. package/build/cjs/prod/clientCache.js +15 -0
  74. package/build/cjs/prod/clientCache.js.map +1 -0
  75. package/build/cjs/prod/defineCloudflareOptions.js.map +1 -1
  76. package/build/cjs/prod/durableobject.js +24 -8
  77. package/build/cjs/prod/durableobject.js.map +1 -1
  78. package/build/cjs/prod/flush.js +6 -4
  79. package/build/cjs/prod/flush.js.map +1 -1
  80. package/build/cjs/prod/index.js +4 -3
  81. package/build/cjs/prod/index.js.map +1 -1
  82. package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js +4 -4
  83. package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  84. package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js +8 -16
  85. package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  86. package/build/cjs/prod/instrumentations/worker/instrumentD1.js +5 -1
  87. package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  88. package/build/cjs/prod/instrumentations/worker/instrumentEmail.js +4 -2
  89. package/build/cjs/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
  90. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js +5 -5
  91. package/build/cjs/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  92. package/build/cjs/prod/instrumentations/worker/instrumentFetch.js +8 -8
  93. package/build/cjs/prod/instrumentations/worker/instrumentFetch.js.map +1 -1
  94. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js +4 -2
  95. package/build/cjs/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  96. package/build/cjs/prod/instrumentations/worker/instrumentR2.js +21 -18
  97. package/build/cjs/prod/instrumentations/worker/instrumentR2.js.map +1 -1
  98. package/build/cjs/prod/instrumentations/worker/instrumentRateLimit.js +6 -1
  99. package/build/cjs/prod/instrumentations/worker/instrumentRateLimit.js.map +1 -1
  100. package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js +4 -2
  101. package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
  102. package/build/cjs/prod/instrumentations/worker/instrumentTail.js +2 -0
  103. package/build/cjs/prod/instrumentations/worker/instrumentTail.js.map +1 -1
  104. package/build/cjs/prod/integrations/fetch.js +1 -11
  105. package/build/cjs/prod/integrations/fetch.js.map +1 -1
  106. package/build/cjs/prod/opentelemetry/tracer.js +2 -40
  107. package/build/cjs/prod/opentelemetry/tracer.js.map +1 -1
  108. package/build/cjs/prod/pages-plugin.js +2 -2
  109. package/build/cjs/prod/pages-plugin.js.map +1 -1
  110. package/build/cjs/prod/request.js +2 -123
  111. package/build/cjs/prod/request.js.map +1 -1
  112. package/build/cjs/prod/sdk.js +12 -6
  113. package/build/cjs/prod/sdk.js.map +1 -1
  114. package/build/cjs/prod/transport.js +1 -1
  115. package/build/cjs/prod/transport.js.map +1 -1
  116. package/build/cjs/prod/utils/invocationContext.js +41 -0
  117. package/build/cjs/prod/utils/invocationContext.js.map +1 -0
  118. package/build/cjs/prod/utils/invocationScope.js +7 -2
  119. package/build/cjs/prod/utils/invocationScope.js.map +1 -1
  120. package/build/cjs/prod/utils/rpcPropagation.js +15 -0
  121. package/build/cjs/prod/utils/rpcPropagation.js.map +1 -0
  122. package/build/cjs/prod/vite/autoInstrument.js +2 -1
  123. package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
  124. package/build/cjs/prod/vite/index.js +1 -1
  125. package/build/cjs/prod/vite/index.js.map +1 -1
  126. package/build/cjs/prod/vite/transform.js +30 -5
  127. package/build/cjs/prod/vite/transform.js.map +1 -1
  128. package/build/cjs/prod/vite/wranglerConfig.js +21 -1
  129. package/build/cjs/prod/vite/wranglerConfig.js.map +1 -1
  130. package/build/cjs/prod/withSentry.js.map +1 -1
  131. package/build/cjs/prod/workflows.js +45 -33
  132. package/build/cjs/prod/workflows.js.map +1 -1
  133. package/build/cjs/prod/wrapMethodWithSentry.js +51 -15
  134. package/build/cjs/prod/wrapMethodWithSentry.js.map +1 -1
  135. package/build/cjs/prod/wrapRequestHandlerWithInit.js +133 -0
  136. package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -0
  137. package/build/esm/dev/baseSdk.js +21 -9
  138. package/build/esm/dev/baseSdk.js.map +1 -1
  139. package/build/esm/dev/client.js +117 -25
  140. package/build/esm/dev/client.js.map +1 -1
  141. package/build/esm/dev/clientCache.js +12 -0
  142. package/build/esm/dev/clientCache.js.map +1 -0
  143. package/build/esm/dev/defineCloudflareOptions.js.map +1 -1
  144. package/build/esm/dev/durableobject.js +23 -7
  145. package/build/esm/dev/durableobject.js.map +1 -1
  146. package/build/esm/dev/flush.js +6 -4
  147. package/build/esm/dev/flush.js.map +1 -1
  148. package/build/esm/dev/index.js +3 -4
  149. package/build/esm/dev/index.js.map +1 -1
  150. package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js +4 -4
  151. package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  152. package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js +8 -16
  153. package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  154. package/build/esm/dev/instrumentations/worker/instrumentD1.js +6 -2
  155. package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  156. package/build/esm/dev/instrumentations/worker/instrumentEmail.js +7 -5
  157. package/build/esm/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
  158. package/build/esm/dev/instrumentations/worker/instrumentEnv.js +5 -5
  159. package/build/esm/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
  160. package/build/esm/dev/instrumentations/worker/instrumentFetch.js +1 -1
  161. package/build/esm/dev/instrumentations/worker/instrumentFetch.js.map +1 -1
  162. package/build/esm/dev/instrumentations/worker/instrumentQueue.js +7 -5
  163. package/build/esm/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
  164. package/build/esm/dev/instrumentations/worker/instrumentR2.js +22 -19
  165. package/build/esm/dev/instrumentations/worker/instrumentR2.js.map +1 -1
  166. package/build/esm/dev/instrumentations/worker/instrumentRateLimit.js +6 -1
  167. package/build/esm/dev/instrumentations/worker/instrumentRateLimit.js.map +1 -1
  168. package/build/esm/dev/instrumentations/worker/instrumentScheduled.js +7 -5
  169. package/build/esm/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
  170. package/build/esm/dev/instrumentations/worker/instrumentTail.js +2 -0
  171. package/build/esm/dev/instrumentations/worker/instrumentTail.js.map +1 -1
  172. package/build/esm/dev/integrations/fetch.js +2 -12
  173. package/build/esm/dev/integrations/fetch.js.map +1 -1
  174. package/build/esm/dev/opentelemetry/tracer.js +2 -40
  175. package/build/esm/dev/opentelemetry/tracer.js.map +1 -1
  176. package/build/esm/dev/package.json +1 -1
  177. package/build/esm/dev/pages-plugin.js +1 -1
  178. package/build/esm/dev/pages-plugin.js.map +1 -1
  179. package/build/esm/dev/request.js +2 -122
  180. package/build/esm/dev/request.js.map +1 -1
  181. package/build/esm/dev/sdk.js +12 -7
  182. package/build/esm/dev/sdk.js.map +1 -1
  183. package/build/esm/dev/transport.js +1 -1
  184. package/build/esm/dev/transport.js.map +1 -1
  185. package/build/esm/dev/utils/invocationContext.js +37 -0
  186. package/build/esm/dev/utils/invocationContext.js.map +1 -0
  187. package/build/esm/dev/utils/invocationScope.js +7 -2
  188. package/build/esm/dev/utils/invocationScope.js.map +1 -1
  189. package/build/esm/dev/utils/rpcPropagation.js +13 -0
  190. package/build/esm/dev/utils/rpcPropagation.js.map +1 -0
  191. package/build/esm/dev/utils/traceLinks.js +1 -1
  192. package/build/esm/dev/vite/autoInstrument.js +2 -1
  193. package/build/esm/dev/vite/autoInstrument.js.map +1 -1
  194. package/build/esm/dev/vite/index.js +1 -1
  195. package/build/esm/dev/vite/index.js.map +1 -1
  196. package/build/esm/dev/vite/transform.js +30 -5
  197. package/build/esm/dev/vite/transform.js.map +1 -1
  198. package/build/esm/dev/vite/wranglerConfig.js +21 -2
  199. package/build/esm/dev/vite/wranglerConfig.js.map +1 -1
  200. package/build/esm/dev/withSentry.js.map +1 -1
  201. package/build/esm/dev/workflows.js +48 -36
  202. package/build/esm/dev/workflows.js.map +1 -1
  203. package/build/esm/dev/wrapMethodWithSentry.js +53 -17
  204. package/build/esm/dev/wrapMethodWithSentry.js.map +1 -1
  205. package/build/esm/dev/wrapRequestHandlerWithInit.js +131 -0
  206. package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -0
  207. package/build/esm/prod/baseSdk.js +21 -9
  208. package/build/esm/prod/baseSdk.js.map +1 -1
  209. package/build/esm/prod/client.js +117 -25
  210. package/build/esm/prod/client.js.map +1 -1
  211. package/build/esm/prod/clientCache.js +12 -0
  212. package/build/esm/prod/clientCache.js.map +1 -0
  213. package/build/esm/prod/defineCloudflareOptions.js.map +1 -1
  214. package/build/esm/prod/durableobject.js +23 -7
  215. package/build/esm/prod/durableobject.js.map +1 -1
  216. package/build/esm/prod/flush.js +6 -4
  217. package/build/esm/prod/flush.js.map +1 -1
  218. package/build/esm/prod/index.js +3 -4
  219. package/build/esm/prod/index.js.map +1 -1
  220. package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js +4 -4
  221. package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
  222. package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js +8 -16
  223. package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  224. package/build/esm/prod/instrumentations/worker/instrumentD1.js +6 -2
  225. package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  226. package/build/esm/prod/instrumentations/worker/instrumentEmail.js +7 -5
  227. package/build/esm/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
  228. package/build/esm/prod/instrumentations/worker/instrumentEnv.js +5 -5
  229. package/build/esm/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
  230. package/build/esm/prod/instrumentations/worker/instrumentFetch.js +1 -1
  231. package/build/esm/prod/instrumentations/worker/instrumentFetch.js.map +1 -1
  232. package/build/esm/prod/instrumentations/worker/instrumentQueue.js +7 -5
  233. package/build/esm/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
  234. package/build/esm/prod/instrumentations/worker/instrumentR2.js +22 -19
  235. package/build/esm/prod/instrumentations/worker/instrumentR2.js.map +1 -1
  236. package/build/esm/prod/instrumentations/worker/instrumentRateLimit.js +6 -1
  237. package/build/esm/prod/instrumentations/worker/instrumentRateLimit.js.map +1 -1
  238. package/build/esm/prod/instrumentations/worker/instrumentScheduled.js +7 -5
  239. package/build/esm/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
  240. package/build/esm/prod/instrumentations/worker/instrumentTail.js +2 -0
  241. package/build/esm/prod/instrumentations/worker/instrumentTail.js.map +1 -1
  242. package/build/esm/prod/integrations/fetch.js +2 -12
  243. package/build/esm/prod/integrations/fetch.js.map +1 -1
  244. package/build/esm/prod/opentelemetry/tracer.js +2 -40
  245. package/build/esm/prod/opentelemetry/tracer.js.map +1 -1
  246. package/build/esm/prod/package.json +1 -1
  247. package/build/esm/prod/pages-plugin.js +1 -1
  248. package/build/esm/prod/pages-plugin.js.map +1 -1
  249. package/build/esm/prod/request.js +2 -122
  250. package/build/esm/prod/request.js.map +1 -1
  251. package/build/esm/prod/sdk.js +12 -7
  252. package/build/esm/prod/sdk.js.map +1 -1
  253. package/build/esm/prod/transport.js +1 -1
  254. package/build/esm/prod/transport.js.map +1 -1
  255. package/build/esm/prod/utils/invocationContext.js +37 -0
  256. package/build/esm/prod/utils/invocationContext.js.map +1 -0
  257. package/build/esm/prod/utils/invocationScope.js +7 -2
  258. package/build/esm/prod/utils/invocationScope.js.map +1 -1
  259. package/build/esm/prod/utils/rpcPropagation.js +13 -0
  260. package/build/esm/prod/utils/rpcPropagation.js.map +1 -0
  261. package/build/esm/prod/utils/traceLinks.js +1 -1
  262. package/build/esm/prod/vite/autoInstrument.js +2 -1
  263. package/build/esm/prod/vite/autoInstrument.js.map +1 -1
  264. package/build/esm/prod/vite/index.js +1 -1
  265. package/build/esm/prod/vite/index.js.map +1 -1
  266. package/build/esm/prod/vite/transform.js +30 -5
  267. package/build/esm/prod/vite/transform.js.map +1 -1
  268. package/build/esm/prod/vite/wranglerConfig.js +21 -2
  269. package/build/esm/prod/vite/wranglerConfig.js.map +1 -1
  270. package/build/esm/prod/withSentry.js.map +1 -1
  271. package/build/esm/prod/workflows.js +48 -36
  272. package/build/esm/prod/workflows.js.map +1 -1
  273. package/build/esm/prod/wrapMethodWithSentry.js +53 -17
  274. package/build/esm/prod/wrapMethodWithSentry.js.map +1 -1
  275. package/build/esm/prod/wrapRequestHandlerWithInit.js +131 -0
  276. package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -0
  277. package/build/types/baseSdk.d.ts +8 -0
  278. package/build/types/baseSdk.d.ts.map +1 -1
  279. package/build/types/client.d.ts +94 -21
  280. package/build/types/client.d.ts.map +1 -1
  281. package/build/types/clientCache.d.ts +8 -0
  282. package/build/types/clientCache.d.ts.map +1 -0
  283. package/build/types/defineCloudflareOptions.d.ts +3 -2
  284. package/build/types/defineCloudflareOptions.d.ts.map +1 -1
  285. package/build/types/durableobject.d.ts +5 -7
  286. package/build/types/durableobject.d.ts.map +1 -1
  287. package/build/types/flush.d.ts +2 -0
  288. package/build/types/flush.d.ts.map +1 -1
  289. package/build/types/index.d.ts +3 -4
  290. package/build/types/index.d.ts.map +1 -1
  291. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts +2 -1
  292. package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts.map +1 -1
  293. package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts +2 -3
  294. package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts.map +1 -1
  295. package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -1
  296. package/build/types/instrumentations/worker/instrumentEmail.d.ts.map +1 -1
  297. package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
  298. package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
  299. package/build/types/instrumentations/worker/instrumentR2.d.ts.map +1 -1
  300. package/build/types/instrumentations/worker/instrumentRateLimit.d.ts.map +1 -1
  301. package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
  302. package/build/types/instrumentations/worker/instrumentTail.d.ts.map +1 -1
  303. package/build/types/integrations/fetch.d.ts.map +1 -1
  304. package/build/types/opentelemetry/tracer.d.ts.map +1 -1
  305. package/build/types/pages-plugin.d.ts +3 -1
  306. package/build/types/pages-plugin.d.ts.map +1 -1
  307. package/build/types/request.d.ts +5 -31
  308. package/build/types/request.d.ts.map +1 -1
  309. package/build/types/sdk.d.ts +13 -4
  310. package/build/types/sdk.d.ts.map +1 -1
  311. package/build/types/transport.d.ts.map +1 -1
  312. package/build/types/types.d.ts +28 -0
  313. package/build/types/types.d.ts.map +1 -1
  314. package/build/types/utils/invocationContext.d.ts +58 -0
  315. package/build/types/utils/invocationContext.d.ts.map +1 -0
  316. package/build/types/utils/invocationScope.d.ts +2 -1
  317. package/build/types/utils/invocationScope.d.ts.map +1 -1
  318. package/build/types/utils/rpcPropagation.d.ts +10 -0
  319. package/build/types/utils/rpcPropagation.d.ts.map +1 -0
  320. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  321. package/build/types/vite/index.d.ts +24 -20
  322. package/build/types/vite/index.d.ts.map +1 -1
  323. package/build/types/vite/transform.d.ts +3 -0
  324. package/build/types/vite/transform.d.ts.map +1 -1
  325. package/build/types/vite/wranglerConfig.d.ts +13 -0
  326. package/build/types/vite/wranglerConfig.d.ts.map +1 -1
  327. package/build/types/withSentry.d.ts +2 -3
  328. package/build/types/withSentry.d.ts.map +1 -1
  329. package/build/types/workflows.d.ts +3 -3
  330. package/build/types/workflows.d.ts.map +1 -1
  331. package/build/types/wrapMethodWithSentry.d.ts +6 -1
  332. package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
  333. package/build/types/wrapRequestHandlerWithInit.d.ts +31 -0
  334. package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -0
  335. package/package.json +6 -4
  336. package/build/cjs/dev/integrations/tracing/vercelai.js +0 -18
  337. package/build/cjs/dev/integrations/tracing/vercelai.js.map +0 -1
  338. package/build/cjs/prod/integrations/tracing/vercelai.js +0 -18
  339. package/build/cjs/prod/integrations/tracing/vercelai.js.map +0 -1
  340. package/build/esm/dev/integrations/tracing/vercelai.js +0 -16
  341. package/build/esm/dev/integrations/tracing/vercelai.js.map +0 -1
  342. package/build/esm/prod/integrations/tracing/vercelai.js +0 -16
  343. package/build/esm/prod/integrations/tracing/vercelai.js.map +0 -1
  344. package/build/types/integrations/tracing/vercelai.d.ts +0 -40
  345. package/build/types/integrations/tracing/vercelai.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"withSentry.js","sources":["../../../src/withSentry.ts"],"sourcesContent":["import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from './client';\nimport { instrumentExportedHandlerEmail } from './instrumentations/worker/instrumentEmail';\nimport { instrumentExportedHandlerFetch } from './instrumentations/worker/instrumentFetch';\nimport { instrumentExportedHandlerQueue } from './instrumentations/worker/instrumentQueue';\nimport { instrumentExportedHandlerScheduled } from './instrumentations/worker/instrumentScheduled';\nimport { instrumentExportedHandlerTail } from './instrumentations/worker/instrumentTail';\nimport { isCloudflareClass } from './utils/isCloudflareClass';\nimport type { AnyExportedHandler, DefaultEnv, ResolveEnv } from './types';\nimport {\n instrumentWorkerEntrypoint,\n type WorkerEntrypointConstructor,\n} from './instrumentations/instrumentWorkerEntrypoint';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\nexport function withSentry<\n Env = DefaultEnv,\n QueueHandlerMessage = unknown,\n CfHostMetadata = unknown,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends AnyExportedHandler | WorkerEntrypointConstructor<any, any> =\n | ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>\n | WorkerEntrypointConstructor<Env>,\n>(optionsCallback: (env: ResolveEnv<T, Env>) => CloudflareOptions | undefined, handler: T): T {\n if (isCloudflareClass(handler, 'WorkerEntrypoint')) {\n // oxlint-disable-next-line typescript/no-explicit-any\n return instrumentWorkerEntrypoint(optionsCallback as any, handler);\n }\n\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerFetch(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerScheduled(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerEmail(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerQueue(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerTail(handler, optionsCallback as any);\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":[],"mappings":";;;;;;;;;AAyBO,SAAS,UAAA,CAQd,iBAA6E,OAAA,EAAe;AAC5F,EAAA,IAAI,iBAAA,CAAkB,OAAA,EAAS,kBAAkB,CAAA,EAAG;AAElD,IAAA,OAAO,0BAAA,CAA2B,iBAAwB,OAAO,CAAA;AAAA,EACnE;AAEA,EAAA,wCAAA,EAAyC;AAEzC,EAAA,IAAI;AAEF,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,kCAAA,CAAmC,SAAS,eAAsB,CAAA;AAElE,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,6BAAA,CAA8B,SAAS,eAAsB,CAAA;AAAA,EAE/D,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
1
+ {"version":3,"file":"withSentry.js","sources":["../../../src/withSentry.ts"],"sourcesContent":["import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport { instrumentExportedHandlerEmail } from './instrumentations/worker/instrumentEmail';\nimport { instrumentExportedHandlerFetch } from './instrumentations/worker/instrumentFetch';\nimport { instrumentExportedHandlerQueue } from './instrumentations/worker/instrumentQueue';\nimport { instrumentExportedHandlerScheduled } from './instrumentations/worker/instrumentScheduled';\nimport { instrumentExportedHandlerTail } from './instrumentations/worker/instrumentTail';\nimport { isCloudflareClass } from './utils/isCloudflareClass';\nimport type { AnyExportedHandler, DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport {\n instrumentWorkerEntrypoint,\n type WorkerEntrypointConstructor,\n} from './instrumentations/instrumentWorkerEntrypoint';\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\nexport function withSentry<\n Env = DefaultEnv,\n QueueHandlerMessage = unknown,\n CfHostMetadata = unknown,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends AnyExportedHandler | WorkerEntrypointConstructor<any, any> =\n | ExportedHandler<Env, QueueHandlerMessage, CfHostMetadata>\n | WorkerEntrypointConstructor<Env>,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<T, Env>) => StrictCloudflareOptions<O> | undefined, handler: T): T {\n if (isCloudflareClass(handler, 'WorkerEntrypoint')) {\n // oxlint-disable-next-line typescript/no-explicit-any\n return instrumentWorkerEntrypoint(optionsCallback as any, handler);\n }\n\n setAsyncLocalStorageAsyncContextStrategy();\n\n try {\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerFetch(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerScheduled(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerEmail(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerQueue(handler, optionsCallback as any);\n // oxlint-disable-next-line typescript/no-explicit-any\n instrumentExportedHandlerTail(handler, optionsCallback as any);\n // This is here because Miniflare sometimes cannot get instrumented\n } catch {\n // Do not console anything here, we don't want to spam the console with errors\n }\n\n return handler;\n}\n"],"names":[],"mappings":";;;;;;;;;AAwBO,SAAS,UAAA,CASd,iBAAsF,OAAA,EAAe;AACrG,EAAA,IAAI,iBAAA,CAAkB,OAAA,EAAS,kBAAkB,CAAA,EAAG;AAElD,IAAA,OAAO,0BAAA,CAA2B,iBAAwB,OAAO,CAAA;AAAA,EACnE;AAEA,EAAA,wCAAA,EAAyC;AAEzC,EAAA,IAAI;AAEF,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,kCAAA,CAAmC,SAAS,eAAsB,CAAA;AAElE,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,8BAAA,CAA+B,SAAS,eAAsB,CAAA;AAE9D,IAAA,6BAAA,CAA8B,SAAS,eAAsB,CAAA;AAAA,EAE/D,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
@@ -1,12 +1,13 @@
1
- import { CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';
2
- import { GENERAL_FUNCTION_SPAN_OP } from '@sentry/conventions/op';
3
- import { withIsolationScope, withScope, getCurrentScope, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, captureException, flush } from '@sentry/core';
1
+ import { SENTRY_SEGMENT_NAME_SOURCE, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';
2
+ import { FUNCTION } from '@sentry/conventions/op';
3
+ import { withScope, getCurrentScope, withIsolationScope, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, captureException, flush } from '@sentry/core';
4
4
  import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';
5
5
  import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
6
6
  import { instrumentEnv } from './instrumentations/worker/instrumentEnv.js';
7
7
  import { addCloudResourceContext } from './scope-utils.js';
8
8
  import { init } from './sdk.js';
9
9
  import { instrumentContext } from './utils/instrumentContext.js';
10
+ import { withInvocationIsolationScope } from './utils/invocationScope.js';
10
11
 
11
12
  const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
12
13
  async function deterministicTraceIdFromInstanceId(instanceId) {
@@ -22,11 +23,12 @@ async function propagationContextFromInstanceId(instanceId) {
22
23
  };
23
24
  }
24
25
  class WrappedWorkflowStep {
25
- constructor(_instanceId, _options, _step, _waitUntil) {
26
+ constructor(_instanceId, _options, _step, _waitUntil, _isolationScope) {
26
27
  this._instanceId = _instanceId;
27
28
  this._options = _options;
28
29
  this._step = _step;
29
30
  this._waitUntil = _waitUntil;
31
+ this._isolationScope = _isolationScope;
30
32
  }
31
33
  async do(name, configOrCallback, callbackOrRollback, maybeRollback) {
32
34
  const scopeForStep = getCurrentScope();
@@ -40,39 +42,49 @@ class WrappedWorkflowStep {
40
42
  const retryLimit = stepContext?.config?.retries?.limit;
41
43
  const hasStepContext = typeof attempt === "number" && typeof retryLimit === "number";
42
44
  const isFinalAttempt = !hasStepContext || attempt > retryLimit;
43
- return startSpan(
44
- {
45
- name,
46
- scope: scopeForStep,
47
- attributes: {
48
- [SENTRY_OP]: GENERAL_FUNCTION_SPAN_OP,
49
- [CODE_FUNCTION_NAME]: name,
50
- "workflow.step.name": name,
51
- "cloudflare.workflow.timeout": config?.timeout,
52
- "cloudflare.workflow.retries.backoff": config?.retries?.backoff,
53
- // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.
54
- "cloudflare.workflow.retries.delay": typeof config?.retries?.delay === "function" ? void 0 : config?.retries?.delay,
55
- "cloudflare.workflow.retries.limit": config?.retries?.limit,
56
- "cloudflare.workflow.attempt": attempt,
57
- [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.faas.cloudflare.workflow",
58
- [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "task"
45
+ return withIsolationScope(this._isolationScope, () => {
46
+ const stepResult = startSpan(
47
+ {
48
+ name,
49
+ scope: scopeForStep,
50
+ attributes: {
51
+ [SENTRY_OP]: FUNCTION,
52
+ [CODE_FUNCTION_NAME]: name,
53
+ "workflow.step.name": name,
54
+ "cloudflare.workflow.timeout": config?.timeout,
55
+ "cloudflare.workflow.retries.backoff": config?.retries?.backoff,
56
+ // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.
57
+ "cloudflare.workflow.retries.delay": typeof config?.retries?.delay === "function" ? void 0 : config?.retries?.delay,
58
+ "cloudflare.workflow.retries.limit": config?.retries?.limit,
59
+ "cloudflare.workflow.attempt": attempt,
60
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.faas.cloudflare.workflow",
61
+ [SENTRY_SEGMENT_NAME_SOURCE]: "task"
62
+ }
63
+ },
64
+ async (span) => {
65
+ try {
66
+ const result = await userCallback(...args);
67
+ span.setStatus({ code: 1 });
68
+ return result;
69
+ } catch (error) {
70
+ if (isFinalAttempt) {
71
+ captureException(error, { mechanism: { handled: true, type: "auto.faas.cloudflare.workflow" } });
72
+ }
73
+ throw error;
74
+ }
59
75
  }
60
- },
61
- async (span) => {
62
- try {
63
- const result = await userCallback(...args);
64
- span.setStatus({ code: 1 });
76
+ );
77
+ return stepResult.then(
78
+ (result) => {
79
+ this._waitUntil(flush(2e3));
65
80
  return result;
66
- } catch (error) {
67
- if (isFinalAttempt) {
68
- captureException(error, { mechanism: { handled: true, type: "auto.faas.cloudflare.workflow" } });
69
- }
70
- throw error;
71
- } finally {
81
+ },
82
+ (error) => {
72
83
  this._waitUntil(flush(2e3));
84
+ throw error;
73
85
  }
74
- }
75
- );
86
+ );
87
+ });
76
88
  };
77
89
  if (config) {
78
90
  return rollbackOptions ? this._step.do(name, config, instrumentedCallback, rollbackOptions) : this._step.do(name, config, instrumentedCallback);
@@ -104,7 +116,7 @@ function instrumentWorkflowWithSentry(optionsCallback, WorkFlowClass) {
104
116
  if (prop === "run") {
105
117
  return async function(event, step) {
106
118
  setAsyncLocalStorageAsyncContextStrategy();
107
- return withIsolationScope(async (isolationScope) => {
119
+ return withInvocationIsolationScope(async (isolationScope) => {
108
120
  const waitUntil = getOriginalWaitUntil(context).bind(context);
109
121
  const client = init({ ...options, ctx: context, enableDedupe: false });
110
122
  isolationScope.setClient(client);
@@ -116,13 +128,13 @@ function instrumentWorkflowWithSentry(optionsCallback, WorkFlowClass) {
116
128
  return await obj.run.call(
117
129
  obj,
118
130
  event,
119
- new WrappedWorkflowStep(event.instanceId, options, step, waitUntil)
131
+ new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope)
120
132
  );
121
133
  } finally {
122
134
  waitUntil(flushAndDispose(client));
123
135
  }
124
136
  });
125
- });
137
+ }, context);
126
138
  };
127
139
  }
128
140
  return Reflect.get(obj, prop, receiver);
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import { CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';\nimport { GENERAL_FUNCTION_SPAN_OP } from '@sentry/conventions/op';\nimport type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv } from './types';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n return startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: GENERAL_FUNCTION_SPAN_OP,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n } finally {\n this._waitUntil(flush(2000));\n }\n },\n );\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: ResolveEnv<C, E>) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;AAkCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CACxC,IAAA,CAAK,EAAE,CAAA;AAEd;AAEA,eAAe,iCAAiC,UAAA,EAAiD;AAC/F,EAAA,MAAM,OAAA,GAAU,UAAA,CAAW,IAAA,CAAK,UAAU,CAAA,GACtC,UAAA,C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AM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown).\n return stepResult.then(\n result => {\n this._waitUntil(flush(2000));\n return result;\n },\n error => {\n this._waitUntil(flush(2000));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAkCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA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;AAE/B,gBAAA,uBAAA,CAAwB,cAAc,CAAA;AAEtC,gBAAA,OAAO,SAAA,CAAU,OAAM,KAAA,KAAS;AAC9B,kBAAA,MAAM,kBAAA,GAAqB,MAAM,gCAAA,CAAiC,KAAA,CAAM,UAAU,CAAA;AAClF,kBAAA,KAAA,CAAM,sBAAsB,kBAAkB,CAAA;AAE9C,kBAAA,IAAI;AACF,oBAAA,OAAO,MAAM,IAAI,GAAA,CAAI,IAAA;AAAA,sBACnB,GAAA;AAAA,sBACA,KAAA;AAAA,sBACA,IAAI,mBAAA,CAAoB,KAAA,CAAM,YAAY,OAAA,EAAS,IAAA,EAAM,WAAW,cAAc;AAAA,qBACpF;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAU,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,GAAG,OAAO,CAAA;AAAA,YACZ,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
@@ -1,10 +1,11 @@
1
- import { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_OP, continueTrace, startNewTrace, captureException, startSpan, isObjectLike, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
1
+ import { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_OP, continueTrace, startNewTrace, isObjectLike, captureException, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
2
2
  import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
3
3
  import { ensureInstrumented } from './instrument.js';
4
4
  import { init } from './sdk.js';
5
+ import { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext.js';
5
6
  import { withInvocationIsolationScope } from './utils/invocationScope.js';
6
7
  import { extractRpcMeta } from './utils/rpcMeta.js';
7
- import { getStoredSpanContext, buildSpanLinks, storeSpanContext } from './utils/traceLinks.js';
8
+ import { storeSpanContext, getStoredSpanContext, buildSpanLinks } from './utils/traceLinks.js';
8
9
 
9
10
  function resolveOriginalStorage(context, thisArg) {
10
11
  if (isObjectLike(thisArg) && "ctx" in thisArg) {
@@ -31,9 +32,11 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
31
32
  args = extracted.args;
32
33
  rpcMeta = extracted.rpcMeta;
33
34
  }
35
+ const spanName = typeof wrapperOptions.spanName === "function" ? wrapperOptions.spanName(rpcMeta) : wrapperOptions.spanName;
34
36
  const wrappedFunction = (scope) => {
35
37
  const context = wrapperOptions.context;
36
- const waitUntil = context ? getOriginalWaitUntil(context)?.bind(context) : void 0;
38
+ const invocationState = getInvocationState();
39
+ const waitUntil = invocationState ? getInvocationWaitUntil(invocationState) : context ? getOriginalWaitUntil(context)?.bind(context) : void 0;
37
40
  const storage = resolveOriginalStorage(context, thisArg);
38
41
  let scopeClient = scope.getClient();
39
42
  if (startNewTrace$1 || !scopeClient?.getTransport()) {
@@ -45,7 +48,7 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
45
48
  scopeClient = client;
46
49
  }
47
50
  const clientToDispose = scopeClient;
48
- const methodName = wrapperOptions.spanName || "unknown";
51
+ const methodName = spanName || "unknown";
49
52
  const teardown = async () => {
50
53
  if (startNewTrace$1 && storage) {
51
54
  storeSpanContext(storage, methodName);
@@ -56,17 +59,23 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
56
59
  waitUntil?.(teardown());
57
60
  return res;
58
61
  };
59
- const onRejected = (e) => {
62
+ const captureAndRethrow = (e) => {
60
63
  captureException(e, {
61
64
  mechanism: {
62
65
  type: origin,
63
66
  handled: false
64
67
  }
65
68
  });
66
- waitUntil?.(teardown());
67
69
  throw e;
68
70
  };
69
- if (!wrapperOptions.spanName) {
71
+ const onRejected = (e) => {
72
+ try {
73
+ return captureAndRethrow(e);
74
+ } finally {
75
+ waitUntil?.(teardown());
76
+ }
77
+ };
78
+ if (!spanName) {
70
79
  try {
71
80
  if (callback) {
72
81
  callback(...args);
@@ -101,27 +110,54 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
101
110
  try {
102
111
  const result = Reflect.apply(target, thisArg, args);
103
112
  if (isThenable(result)) {
104
- return result.then(onFulfilled, onRejected);
105
- } else {
106
- return onFulfilled(result);
113
+ return result.then(void 0, captureAndRethrow);
107
114
  }
115
+ return result;
108
116
  } catch (e) {
109
- return onRejected(e);
117
+ return captureAndRethrow(e);
110
118
  }
111
119
  });
112
120
  };
121
+ const runWithTeardown = (run) => {
122
+ let out;
123
+ try {
124
+ out = run();
125
+ } catch (e) {
126
+ waitUntil?.(teardown());
127
+ throw e;
128
+ }
129
+ if (isThenable(out)) {
130
+ return out.then(
131
+ (res) => {
132
+ waitUntil?.(teardown());
133
+ return res;
134
+ },
135
+ (e) => {
136
+ waitUntil?.(teardown());
137
+ throw e;
138
+ }
139
+ );
140
+ }
141
+ waitUntil?.(teardown());
142
+ return out;
143
+ };
113
144
  if (rpcMeta) {
114
- return continueTrace(
115
- { sentryTrace: rpcMeta["sentry-trace"] || "", baggage: rpcMeta.baggage || "" },
116
- executeSpan
145
+ return runWithTeardown(
146
+ () => continueTrace(
147
+ { sentryTrace: rpcMeta["sentry-trace"] || "", baggage: rpcMeta.baggage || "" },
148
+ executeSpan
149
+ )
117
150
  );
118
151
  }
119
152
  if (startNewTrace$1) {
120
- return startNewTrace(() => executeSpan());
153
+ return runWithTeardown(() => startNewTrace(() => executeSpan()));
121
154
  }
122
- return executeSpan();
155
+ return runWithTeardown(executeSpan);
123
156
  };
124
- return withInvocationIsolationScope(wrappedFunction);
157
+ return withInvocationIsolationScope(
158
+ wrappedFunction,
159
+ wrapperOptions.context
160
+ );
125
161
  }
126
162
  }),
127
163
  noMark
@@ -1 +1 @@
1
- {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\nexport interface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n const waitUntil = context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Check if client exists AND is still usable (transport not disposed)\n // This handles the case where a previous handler disposed the client\n // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)\n // For startNewTrace, always create a fresh client\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = wrapperOptions.spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const onRejected = (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n };\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n });\n };\n\n if (rpcMeta) {\n return continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n );\n }\n\n if (startNewTrace) {\n return startNewTraceCore(() => executeSpan());\n }\n\n return executeSpan();\n };\n\n return withInvocationIsolationScope(wrappedFunction);\n },\n }),\n noMark,\n );\n}\n"],"names":["startNewTrace","startNewTraceCore"],"mappings":";;;;;;;;AAgCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAI,YAAA,CAAa,OAAO,CAAA,IAAK,KAAA,IAAS,OAAA,EAAS;AAC7C,IAAA,MAAM,QAAS,OAAA,CAAoD,GAAA;AACnE,IAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B,MAAA,OAAO,KAAA,CAAM,eAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,IAAW,iBAAA,IAAqB,OAAA,IAAW,OAAA,CAAQ,eAAA,EAAiB;AACtE,IAAA,OAAO,OAAA,CAAQ,eAAA;AAAA,EACjB;AAEA,EAAA,OAAO,MAAA;AACT;AAuCO,SAAS,oBAAA,CACd,cAAA,EACA,OAAA,EACA,QAAA,EACA,MAAA,EACG;AACH,EAAA,OAAO,kBAAA;AAAA,IACL,OAAA;AAAA,IACA,CAAA,QAAA,KACE,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,MAClB,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,OAAA,EAAwB;AAC7C,QAAA,MAAM,iBAAEA,eAAA,EAAe,MAAA,EAAO,GAAI,cAAA;AAKlC,QAAA,IAAI,IAAA,GAAO,OAAA;AACX,QAAA,IAAI,OAAA;AAEJ,QAAA,IAAI,cAAA,CAAe,WAAW,KAAA,EAAO;AACnC,UAAA,MAAM,SAAA,GAAY,eAAe,OAAO,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A;AAAA,oBACA,GAAG,aAAA,CAAc,OAAO,IAAI,aAAA,CAAc,MAAM,IAAI,WAAW,CAAA;AAAA,mBACjE;AAAA,gBACF;AAAA,cACF;AAEA,cAAA,IAAI;AACF,gBAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,IAAI,CAAA;AAElD,gBAAA,IAAI,UAAA,CAAW,MAAM,CAAA,EAAG;AACtB,kBAAA,OAAO,MAAA,CAAO,IAAA,CAAK,WAAA,EAAa,UAAU,CAAA;AAAA,gBAC5C,CAAA,MAAO;AACL,kBAAA,OAAO,YAAY,MAAM,CAAA;AAAA,gBAC3B;AAAA,cACF,SAAS,CAAA,EAAG;AACV,gBAAA,OAAO,WAAW,CAAC,CAAA;AAAA,cACrB;AAAA,YACF,CAAC,CAAA;AAAA,UACH,CAAA;AAEA,UAAA,IAAI,OAAA,EAAS;AACX,YAAA,OAAO,aAAA;AAAA,cACL,EAAE,aAAa,OAAA,CAAQ,cAAc,KAAK,EAAA,EAAI,OAAA,EAAS,OAAA,CAAQ,OAAA,IAAW,EAAA,EAAG;AAAA,cAC7E;AAAA,aACF;AAAA,UACF;AAEA,UAAA,IAAIA,eAAA,EAAe;AACjB,YAAA,OAAOC,aAAA,CAAkB,MAAM,WAAA,EAAa,CAAA;AAAA,UAC9C;AAEA,UAAA,OAAO,WAAA,EAAY;AAAA,QACrB,CAAA;AAEA,QAAA,OAAO,6BAA6B,eAAe,CAAA;AAAA,MACrD;AAAA,KACD,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\nexport interface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n /**\n * The span name, or a resolver called with the RPC metadata of the current call.\n * Returning `undefined` skips the span and only captures errors.\n */\n spanName?: string | ((rpcMeta: SerializedTraceData | undefined) => string | undefined);\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n const spanName =\n typeof wrapperOptions.spanName === 'function' ? wrapperOptions.spanName(rpcMeta) : wrapperOptions.spanName;\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n // Resolved once per invocation and cached on its state: reading `ctx.waitUntil`\n // on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Re-init when the scope has no usable client (a previous handler disposed it, e.g.\n // DO alarm handlers) or for `startNewTrace`, so the client points at this\n // invocation's context. With `cacheClient: true` `init()` returns the isolate's\n // cached client and only creates (and caches) a fresh one when nothing is cached yet;\n // `cacheClient: false` creates one per invocation.\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const captureAndRethrow = (e: unknown): never => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n throw e;\n };\n\n const onRejected = (e: unknown) => {\n try {\n return captureAndRethrow(e);\n } finally {\n waitUntil?.(teardown());\n }\n };\n\n if (!spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(undefined, captureAndRethrow);\n }\n return result;\n } catch (e) {\n return captureAndRethrow(e);\n }\n });\n };\n\n // The boundary flush (teardown) must run after the method span has ended, so the\n // span is in the buffer when that flush drains it. Running it inside the span\n // callback (before `startSpan` ends the span) would leave the span for the eager\n // path and cost a second flush per invocation.\n const runWithTeardown = (run: () => unknown): unknown => {\n let out: unknown;\n try {\n out = run();\n } catch (e) {\n // Synchronous throw: `startSpan` already ended the span and rethrew.\n waitUntil?.(teardown());\n throw e;\n }\n if (isThenable(out)) {\n return out.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n waitUntil?.(teardown());\n throw e;\n },\n );\n }\n waitUntil?.(teardown());\n return out;\n };\n\n if (rpcMeta) {\n return runWithTeardown(() =>\n continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n ),\n );\n }\n\n if (startNewTrace) {\n return runWithTeardown(() => startNewTraceCore(() => executeSpan()));\n }\n\n return runWithTeardown(executeSpan);\n };\n\n return withInvocationIsolationScope(\n wrappedFunction,\n wrapperOptions.context as ExecutionContextCompat | undefined,\n );\n },\n }),\n noMark,\n );\n}\n"],"names":["startNewTrace","startNewTraceCore"],"mappings":";;;;;;;;;AAiCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAI,YAAA,CAAa,OAAO,CAAA,IAAK,KAAA,IAAS,OAAA,EAAS;AAC7C,IAAA,MAAM,QAAS,OAAA,CAAoD,GAAA;AACnE,IAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B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EAAa,CAAC,CAAA;AAAA,UACrE;AAEA,UAAA,OAAO,gBAAgB,WAAW,CAAA;AAAA,QACpC,CAAA;AAEA,QAAA,OAAO,4BAAA;AAAA,UACL,eAAA;AAAA,UACA,cAAA,CAAe;AAAA,SACjB;AAAA,MACF;AAAA,KACD,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
@@ -0,0 +1,131 @@
1
+ import { SENTRY_SEGMENT_NAME_SOURCE, NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/conventions/attributes';
2
+ import { parseStringToURLObject, getHttpSpanDetailsFromUrlObject, hasSpanStreamingEnabled, HTTP_SPAN_NAME_FALLBACK, httpHeadersToSpanAttributes, winterCGHeadersToDict, SEMANTIC_ATTRIBUTE_SENTRY_OP, captureException, continueTrace, startSpanManual, setHttpStatus } from '@sentry/core';
3
+ import { captureIncomingRequestBody } from './integrations/httpServer.js';
4
+ import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
5
+ import { addCloudResourceContext, addRequest, addCultureContext } from './scope-utils.js';
6
+ import { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext.js';
7
+ import { withInvocationIsolationScope } from './utils/invocationScope.js';
8
+ import { classifyResponseStreaming } from './utils/streaming.js';
9
+
10
+ function getRequestErrorMechanismType(context) {
11
+ return context && "storage" in context ? "auto.faas.cloudflare.durable_object" : "auto.http.cloudflare";
12
+ }
13
+ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
14
+ return withInvocationIsolationScope(async (isolationScope) => {
15
+ const { options, request, captureErrors = true } = wrapperOptions;
16
+ const context = wrapperOptions.context;
17
+ const invocationState = getInvocationState();
18
+ const waitUntil = invocationState ? getInvocationWaitUntil(invocationState) : context ? getOriginalWaitUntil(context).bind(context) : void 0;
19
+ const errorMechanismType = getRequestErrorMechanismType(context);
20
+ const client = initSdk({ ...options, ctx: context });
21
+ isolationScope.setClient(client);
22
+ const urlObject = parseStringToURLObject(request.url);
23
+ const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(
24
+ urlObject,
25
+ "server",
26
+ "auto.http.cloudflare",
27
+ request,
28
+ void 0,
29
+ client
30
+ );
31
+ const name = attributes[SENTRY_SEGMENT_NAME_SOURCE] === "route" || !client || !hasSpanStreamingEnabled(client) ? rawName : request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;
32
+ const contentLength = request.headers.get("content-length");
33
+ if (contentLength) {
34
+ attributes["http.request.body.size"] = parseInt(contentLength, 10);
35
+ }
36
+ const userAgentHeader = request.headers.get("user-agent");
37
+ if (userAgentHeader) {
38
+ attributes["user_agent.original"] = userAgentHeader;
39
+ }
40
+ if (client) {
41
+ Object.assign(
42
+ attributes,
43
+ httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers), client.getDataCollectionOptions())
44
+ );
45
+ }
46
+ attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = "http.server";
47
+ addCloudResourceContext(isolationScope);
48
+ addRequest(isolationScope, request);
49
+ if (request.cf) {
50
+ addCultureContext(isolationScope, request.cf);
51
+ if (typeof request.cf.httpProtocol === "string") {
52
+ const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split("/");
53
+ attributes[NETWORK_PROTOCOL_NAME] = protocolName;
54
+ attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;
55
+ }
56
+ }
57
+ if (request.method === "OPTIONS" || request.method === "HEAD") {
58
+ try {
59
+ return await handler();
60
+ } catch (e) {
61
+ if (captureErrors) {
62
+ captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
63
+ }
64
+ throw e;
65
+ } finally {
66
+ waitUntil?.(flushAndDispose(client));
67
+ }
68
+ }
69
+ if (client) {
70
+ await captureIncomingRequestBody(client, request);
71
+ }
72
+ return continueTrace(
73
+ { sentryTrace: request.headers.get("sentry-trace") || "", baggage: request.headers.get("baggage") },
74
+ () => {
75
+ return startSpanManual({ name, attributes }, async (span) => {
76
+ let res;
77
+ try {
78
+ res = await handler();
79
+ setHttpStatus(span, res.status);
80
+ } catch (e) {
81
+ span.end();
82
+ if (captureErrors) {
83
+ captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
84
+ }
85
+ waitUntil?.(flushAndDispose(client));
86
+ throw e;
87
+ }
88
+ const classification = classifyResponseStreaming(res);
89
+ if (classification.isStreaming && res.body) {
90
+ try {
91
+ let ended = false;
92
+ const endSpanOnce = () => {
93
+ if (ended) return;
94
+ ended = true;
95
+ span.end();
96
+ waitUntil?.(flushAndDispose(client));
97
+ };
98
+ const transform = new TransformStream({
99
+ flush() {
100
+ endSpanOnce();
101
+ },
102
+ cancel() {
103
+ endSpanOnce();
104
+ }
105
+ });
106
+ return new Response(res.body.pipeThrough(transform), {
107
+ status: res.status,
108
+ statusText: res.statusText,
109
+ headers: res.headers
110
+ });
111
+ } catch {
112
+ span.end();
113
+ waitUntil?.(flushAndDispose(client));
114
+ return res;
115
+ }
116
+ }
117
+ span.end();
118
+ if (res.status === 101) {
119
+ waitUntil?.(client?.flush(2e3));
120
+ } else {
121
+ waitUntil?.(flushAndDispose(client));
122
+ }
123
+ return res;
124
+ });
125
+ }
126
+ );
127
+ }, wrapperOptions.context);
128
+ }
129
+
130
+ export { wrapRequestHandlerWithInit };
131
+ //# sourceMappingURL=wrapRequestHandlerWithInit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrapRequestHandlerWithInit.js","sources":["../../../src/wrapRequestHandlerWithInit.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_SEGMENT_NAME_SOURCE,\n} from '@sentry/conventions/attributes';\nimport {\n captureException,\n continueTrace,\n getHttpSpanDetailsFromUrlObject,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n} from '@sentry/core';\nimport { captureIncomingRequestBody } from './integrations/httpServer';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { classifyResponseStreaming } from './utils/streaming';\n\nfunction getRequestErrorMechanismType(context: ExecutionContextCompat | undefined): string {\n // Durable Object fetch handlers use DO state as context (see instrumentDurableObjectWithSentry)\n return context && 'storage' in context ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';\n}\n\nexport interface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContextCompat | undefined;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\ntype InitSdk = (options: CloudflareOptions) => CloudflareClient | undefined;\n\n/**\n * Same as {@link wrapRequestHandler}, but with the SDK initialization injected.\n *\n * Wrappers that are only reachable from the main entry point — where `nodejs_compat` is a\n * requirement anyway — pass `init` from `sdk.ts` to get the full default integrations.\n *\n * @internal\n */\nexport function wrapRequestHandlerWithInit(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n initSdk: InitSdk,\n): Promise<Response> {\n return withInvocationIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // The un-instrumented waitUntil, so flushAndDispose cannot deadlock on the flush\n // lock's own wrapper. Resolved once per invocation and cached on its state; reading\n // `ctx.waitUntil` on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context).bind(context)\n : undefined;\n const errorMechanismType = getRequestErrorMechanismType(context);\n\n const client = initSdk({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n 'auto.http.cloudflare',\n request,\n undefined,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !client || !hasSpanStreamingEnabled(client)\n ? rawName\n : request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n if (client) {\n Object.assign(\n attributes,\n httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers), client.getDataCollectionOptions()),\n );\n }\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split('/');\n attributes[NETWORK_PROTOCOL_NAME] = protocolName;\n attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;\n }\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n throw e;\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n if (client) {\n await captureIncomingRequestBody(client, request);\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n waitUntil?.(flushAndDispose(client));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n try {\n let ended = false;\n\n const endSpanOnce = (): void => {\n if (ended) return;\n\n ended = true;\n span.end();\n waitUntil?.(flushAndDispose(client));\n };\n\n const transform = new TransformStream({\n flush() {\n // Source stream completed normally.\n endSpanOnce();\n },\n cancel() {\n // Client disconnected (or downstream cancelled). The `cancel`\n // is being called while the response is still considered\n // active, so this is a safe place to end the span.\n endSpanOnce();\n },\n });\n\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch {\n span.end();\n waitUntil?.(flushAndDispose(client));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n\n // Don't dispose for protocol upgrades (101 Switching Protocols) - the connection stays alive.\n // This includes WebSocket upgrades where webSocketMessage/webSocketClose handlers\n // will still be called and may need the client to capture errors.\n if (res.status === 101) {\n waitUntil?.(client?.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n return res;\n });\n },\n );\n }, wr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3B;;;;"}
@@ -17,6 +17,14 @@ export declare function getBaseDefaultIntegrations(options: CloudflareOptions):
17
17
  * Node.js-only code. `request.ts` — which backs both `wrapRequestHandler` and the
18
18
  * `@sentry/cloudflare/request` entry point, and therefore has to work on runtimes without the
19
19
  * `nodejs_compat` compatibility flag — creates its client from here instead of from `sdk.ts`.
20
+ *
21
+ * The client is cached and reused across invocations within the same isolate,
22
+ * unless `cacheClient: false` is passed. This avoids the
23
+ * per-invocation cost of constructing a new client, and it is what makes
24
+ * Durable Object telemetry reliable: a per-invocation client is disposed at
25
+ * the end of the handler, and in a Durable Object there is no `waitUntil`
26
+ * boundary that reliably extends execution, so spans/events that end after
27
+ * disposal would otherwise be lost.
20
28
  */
21
29
  export declare function initWithDefaultIntegrations(options: CloudflareOptions, getDefaultIntegrationsImpl: (options: CloudflareOptions) => Integration[]): CloudflareClient | undefined;
22
30
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"baseSdk.d.ts","sourceRoot":"","sources":["../../src/baseSdk.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAchD,OAAO,KAAK,EAA2B,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AA0B5C;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iBAAiB,GAAG,WAAW,EAAE,CAqBpF;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,iBAAiB,EAC1B,0BAA0B,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,WAAW,EAAE,GACxE,gBAAgB,GAAG,SAAS,CAmD9B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,GAAG,SAAS,CAEpF"}
1
+ {"version":3,"file":"baseSdk.d.ts","sourceRoot":"","sources":["../../src/baseSdk.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAehD,OAAO,KAAK,EAA2B,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AA0B5C;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iBAAiB,GAAG,WAAW,EAAE,CAqBpF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,iBAAiB,EAC1B,0BAA0B,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,WAAW,EAAE,GACxE,gBAAgB,GAAG,SAAS,CAiE9B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,GAAG,SAAS,CAEpF"}