autotel 3.5.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (591) hide show
  1. package/dist/attribute-redacting-processor-DtTS9xxh.d.cts +175 -0
  2. package/dist/attribute-redacting-processor-DtTS9xxh.d.cts.map +1 -0
  3. package/dist/attribute-redacting-processor-DtTS9xxh.d.ts +175 -0
  4. package/dist/attribute-redacting-processor-DtTS9xxh.d.ts.map +1 -0
  5. package/dist/attribute-redacting-processor.cjs +374 -33
  6. package/dist/attribute-redacting-processor.cjs.map +1 -1
  7. package/dist/attribute-redacting-processor.d.cts +2 -207
  8. package/dist/attribute-redacting-processor.d.ts +2 -207
  9. package/dist/attribute-redacting-processor.js +368 -2
  10. package/dist/attribute-redacting-processor.js.map +1 -1
  11. package/dist/attributes-D3etyRVc.cjs +713 -0
  12. package/dist/attributes-D3etyRVc.cjs.map +1 -0
  13. package/dist/attributes-ksn4HVbd.js +600 -0
  14. package/dist/attributes-ksn4HVbd.js.map +1 -0
  15. package/dist/attributes.cjs +21 -85
  16. package/dist/attributes.d.cts +2 -20
  17. package/dist/attributes.d.ts +2 -20
  18. package/dist/attributes.js +3 -5
  19. package/dist/auto.cjs +50 -28
  20. package/dist/auto.cjs.map +1 -1
  21. package/dist/auto.d.cts +1 -2
  22. package/dist/auto.d.ts +1 -2
  23. package/dist/auto.js +49 -23
  24. package/dist/auto.js.map +1 -1
  25. package/dist/business-baggage.cjs +357 -13
  26. package/dist/business-baggage.cjs.map +1 -1
  27. package/dist/business-baggage.d.cts +106 -139
  28. package/dist/business-baggage.d.cts.map +1 -0
  29. package/dist/business-baggage.d.ts +106 -139
  30. package/dist/business-baggage.d.ts.map +1 -0
  31. package/dist/business-baggage.js +357 -2
  32. package/dist/business-baggage.js.map +1 -1
  33. package/dist/canonical-log-line-processor--RlFDHhm.cjs +377 -0
  34. package/dist/canonical-log-line-processor--RlFDHhm.cjs.map +1 -0
  35. package/dist/canonical-log-line-processor-BcRuAdRk.d.ts +147 -0
  36. package/dist/canonical-log-line-processor-BcRuAdRk.d.ts.map +1 -0
  37. package/dist/canonical-log-line-processor-DbBQT5vY.js +366 -0
  38. package/dist/canonical-log-line-processor-DbBQT5vY.js.map +1 -0
  39. package/dist/canonical-log-line-processor-xvjMgtpF.d.cts +147 -0
  40. package/dist/canonical-log-line-processor-xvjMgtpF.d.cts.map +1 -0
  41. package/dist/config.cjs +118 -22
  42. package/dist/config.cjs.map +1 -1
  43. package/dist/config.d.cts +33 -45
  44. package/dist/config.d.cts.map +1 -0
  45. package/dist/config.d.ts +33 -45
  46. package/dist/config.d.ts.map +1 -0
  47. package/dist/config.js +116 -3
  48. package/dist/config.js.map +1 -1
  49. package/dist/correlated-events-Bzh5y-UB.js +28 -0
  50. package/dist/correlated-events-Bzh5y-UB.js.map +1 -0
  51. package/dist/correlated-events-kSwLo3mi.cjs +34 -0
  52. package/dist/correlated-events-kSwLo3mi.cjs.map +1 -0
  53. package/dist/correlation-id.cjs +11 -53
  54. package/dist/correlation-id.d.cts +6 -5
  55. package/dist/correlation-id.d.cts.map +1 -0
  56. package/dist/correlation-id.d.ts +6 -5
  57. package/dist/correlation-id.d.ts.map +1 -0
  58. package/dist/correlation-id.js +3 -16
  59. package/dist/db.cjs +244 -209
  60. package/dist/db.cjs.map +1 -1
  61. package/dist/db.d.cts +28 -26
  62. package/dist/db.d.cts.map +1 -0
  63. package/dist/db.d.ts +28 -26
  64. package/dist/db.d.ts.map +1 -0
  65. package/dist/db.js +243 -207
  66. package/dist/db.js.map +1 -1
  67. package/dist/decorators.cjs +39 -65
  68. package/dist/decorators.cjs.map +1 -1
  69. package/dist/decorators.d.cts +10 -37
  70. package/dist/decorators.d.cts.map +1 -0
  71. package/dist/decorators.d.ts +10 -37
  72. package/dist/decorators.d.ts.map +1 -0
  73. package/dist/decorators.js +38 -63
  74. package/dist/decorators.js.map +1 -1
  75. package/dist/define-event-CreknLm3.d.ts +25 -0
  76. package/dist/define-event-CreknLm3.d.ts.map +1 -0
  77. package/dist/define-event-HZRizPwz.d.cts +25 -0
  78. package/dist/define-event-HZRizPwz.d.cts.map +1 -0
  79. package/dist/drain-pipeline.cjs +111 -9
  80. package/dist/drain-pipeline.cjs.map +1 -1
  81. package/dist/drain-pipeline.d.cts +27 -32
  82. package/dist/drain-pipeline.d.cts.map +1 -0
  83. package/dist/drain-pipeline.d.ts +27 -32
  84. package/dist/drain-pipeline.d.ts.map +1 -0
  85. package/dist/drain-pipeline.js +111 -2
  86. package/dist/drain-pipeline.js.map +1 -1
  87. package/dist/enrichers.cjs +59 -66
  88. package/dist/enrichers.cjs.map +1 -1
  89. package/dist/enrichers.d.cts +15 -13
  90. package/dist/enrichers.d.cts.map +1 -0
  91. package/dist/enrichers.d.ts +15 -13
  92. package/dist/enrichers.d.ts.map +1 -0
  93. package/dist/enrichers.js +58 -65
  94. package/dist/enrichers.js.map +1 -1
  95. package/dist/event-Dlqr4ZNL.cjs +778 -0
  96. package/dist/event-Dlqr4ZNL.cjs.map +1 -0
  97. package/dist/event-_58ryBjh.js +761 -0
  98. package/dist/event-_58ryBjh.js.map +1 -0
  99. package/dist/event-subscriber-D1XLkPzi.d.cts +223 -0
  100. package/dist/event-subscriber-D1XLkPzi.d.cts.map +1 -0
  101. package/dist/event-subscriber-D1XLkPzi.d.ts +223 -0
  102. package/dist/event-subscriber-D1XLkPzi.d.ts.map +1 -0
  103. package/dist/event-subscriber.cjs +0 -6
  104. package/dist/event-subscriber.d.cts +2 -221
  105. package/dist/event-subscriber.d.ts +2 -221
  106. package/dist/event-subscriber.js +1 -3
  107. package/dist/event-testing-BqRnI0z4.d.cts +106 -0
  108. package/dist/event-testing-BqRnI0z4.d.cts.map +1 -0
  109. package/dist/event-testing-CfFs3to2.d.ts +106 -0
  110. package/dist/event-testing-CfFs3to2.d.ts.map +1 -0
  111. package/dist/event-testing.cjs +93 -17
  112. package/dist/event-testing.cjs.map +1 -1
  113. package/dist/event-testing.d.cts +2 -110
  114. package/dist/event-testing.d.ts +2 -110
  115. package/dist/event-testing.js +91 -2
  116. package/dist/event-testing.js.map +1 -1
  117. package/dist/event.cjs +5 -36
  118. package/dist/event.d.cts +295 -340
  119. package/dist/event.d.cts.map +1 -0
  120. package/dist/event.d.ts +295 -340
  121. package/dist/event.d.ts.map +1 -0
  122. package/dist/event.js +3 -20
  123. package/dist/exporters.cjs +12 -16
  124. package/dist/exporters.d.cts +86 -111
  125. package/dist/exporters.d.cts.map +1 -0
  126. package/dist/exporters.d.ts +86 -111
  127. package/dist/exporters.d.ts.map +1 -0
  128. package/dist/exporters.js +4 -4
  129. package/dist/filtering-span-processor-B8R8B7Uk.d.cts +59 -0
  130. package/dist/filtering-span-processor-B8R8B7Uk.d.cts.map +1 -0
  131. package/dist/filtering-span-processor-B8R8B7Uk.d.ts +59 -0
  132. package/dist/filtering-span-processor-B8R8B7Uk.d.ts.map +1 -0
  133. package/dist/filtering-span-processor.cjs +49 -9
  134. package/dist/filtering-span-processor.cjs.map +1 -1
  135. package/dist/filtering-span-processor.d.cts +2 -80
  136. package/dist/filtering-span-processor.d.ts +2 -80
  137. package/dist/filtering-span-processor.js +49 -2
  138. package/dist/filtering-span-processor.js.map +1 -1
  139. package/dist/functional-BGkT8J-h.js +1265 -0
  140. package/dist/functional-BGkT8J-h.js.map +1 -0
  141. package/dist/functional-C4CzoVrX.cjs +1312 -0
  142. package/dist/functional-C4CzoVrX.cjs.map +1 -0
  143. package/dist/functional.cjs +11 -56
  144. package/dist/functional.d.cts +96 -97
  145. package/dist/functional.d.cts.map +1 -0
  146. package/dist/functional.d.ts +96 -97
  147. package/dist/functional.d.ts.map +1 -0
  148. package/dist/functional.js +3 -19
  149. package/dist/http.cjs +276 -175
  150. package/dist/http.cjs.map +1 -1
  151. package/dist/http.d.cts +17 -37
  152. package/dist/http.d.cts.map +1 -0
  153. package/dist/http.d.ts +17 -37
  154. package/dist/http.d.ts.map +1 -0
  155. package/dist/http.js +275 -173
  156. package/dist/http.js.map +1 -1
  157. package/dist/index-CX0aG1Uh.d.ts +708 -0
  158. package/dist/index-CX0aG1Uh.d.ts.map +1 -0
  159. package/dist/index-DIWZFKUS.d.cts +708 -0
  160. package/dist/index-DIWZFKUS.d.cts.map +1 -0
  161. package/dist/index.cjs +1050 -1184
  162. package/dist/index.cjs.map +1 -1
  163. package/dist/index.d.cts +401 -570
  164. package/dist/index.d.cts.map +1 -0
  165. package/dist/index.d.ts +401 -570
  166. package/dist/index.d.ts.map +1 -0
  167. package/dist/index.js +913 -725
  168. package/dist/index.js.map +1 -1
  169. package/dist/init-CNp-ee80.d.cts +1157 -0
  170. package/dist/init-CNp-ee80.d.cts.map +1 -0
  171. package/dist/init-Ch6t7MNI.js +1015 -0
  172. package/dist/init-Ch6t7MNI.js.map +1 -0
  173. package/dist/init-DJQOdVlN.d.ts +1157 -0
  174. package/dist/init-DJQOdVlN.d.ts.map +1 -0
  175. package/dist/init-DvapOXCc.cjs +1092 -0
  176. package/dist/init-DvapOXCc.cjs.map +1 -0
  177. package/dist/instrumentation.cjs +159 -185
  178. package/dist/instrumentation.cjs.map +1 -1
  179. package/dist/instrumentation.d.cts +42 -40
  180. package/dist/instrumentation.d.cts.map +1 -0
  181. package/dist/instrumentation.d.ts +42 -40
  182. package/dist/instrumentation.d.ts.map +1 -0
  183. package/dist/instrumentation.js +158 -183
  184. package/dist/instrumentation.js.map +1 -1
  185. package/dist/logger-BauSUhUv.d.cts +313 -0
  186. package/dist/logger-BauSUhUv.d.cts.map +1 -0
  187. package/dist/logger-BauSUhUv.d.ts +313 -0
  188. package/dist/logger-BauSUhUv.d.ts.map +1 -0
  189. package/dist/logger.cjs +225 -25
  190. package/dist/logger.cjs.map +1 -1
  191. package/dist/logger.d.cts +2 -348
  192. package/dist/logger.d.ts +2 -348
  193. package/dist/logger.js +204 -4
  194. package/dist/logger.js.map +1 -1
  195. package/dist/messaging-adapters.cjs +292 -187
  196. package/dist/messaging-adapters.cjs.map +1 -1
  197. package/dist/messaging-adapters.d.cts +28 -66
  198. package/dist/messaging-adapters.d.cts.map +1 -0
  199. package/dist/messaging-adapters.d.ts +28 -66
  200. package/dist/messaging-adapters.d.ts.map +1 -0
  201. package/dist/messaging-adapters.js +291 -185
  202. package/dist/messaging-adapters.js.map +1 -1
  203. package/dist/messaging-testing.cjs +306 -372
  204. package/dist/messaging-testing.cjs.map +1 -1
  205. package/dist/messaging-testing.d.cts +194 -223
  206. package/dist/messaging-testing.d.cts.map +1 -0
  207. package/dist/messaging-testing.d.ts +194 -223
  208. package/dist/messaging-testing.d.ts.map +1 -0
  209. package/dist/messaging-testing.js +305 -371
  210. package/dist/messaging-testing.js.map +1 -1
  211. package/dist/messaging.cjs +757 -35
  212. package/dist/messaging.cjs.map +1 -1
  213. package/dist/messaging.d.cts +603 -644
  214. package/dist/messaging.d.cts.map +1 -0
  215. package/dist/messaging.d.ts +603 -644
  216. package/dist/messaging.d.ts.map +1 -0
  217. package/dist/messaging.js +756 -20
  218. package/dist/messaging.js.map +1 -1
  219. package/dist/metric-helpers.cjs +27 -27
  220. package/dist/metric-helpers.cjs.map +1 -1
  221. package/dist/metric-helpers.d.cts +4 -2
  222. package/dist/metric-helpers.d.cts.map +1 -0
  223. package/dist/metric-helpers.d.ts +4 -2
  224. package/dist/metric-helpers.d.ts.map +1 -0
  225. package/dist/metric-helpers.js +24 -4
  226. package/dist/metric-helpers.js.map +1 -1
  227. package/dist/metric-testing-DXdK3-Q3.d.ts +106 -0
  228. package/dist/metric-testing-DXdK3-Q3.d.ts.map +1 -0
  229. package/dist/metric-testing-MxvzChDp.d.cts +106 -0
  230. package/dist/metric-testing-MxvzChDp.d.cts.map +1 -0
  231. package/dist/metric-testing.cjs +93 -17
  232. package/dist/metric-testing.cjs.map +1 -1
  233. package/dist/metric-testing.d.cts +2 -110
  234. package/dist/metric-testing.d.ts +2 -110
  235. package/dist/metric-testing.js +91 -2
  236. package/dist/metric-testing.js.map +1 -1
  237. package/dist/metric.cjs +306 -22
  238. package/dist/metric.cjs.map +1 -1
  239. package/dist/metric.d.cts +170 -198
  240. package/dist/metric.d.cts.map +1 -0
  241. package/dist/metric.d.ts +170 -198
  242. package/dist/metric.d.ts.map +1 -0
  243. package/dist/metric.js +277 -7
  244. package/dist/metric.js.map +1 -1
  245. package/dist/node-require-DF5QBX6z.cjs +99 -0
  246. package/dist/node-require-DF5QBX6z.cjs.map +1 -0
  247. package/dist/node-require-Db1oDpLj.js +88 -0
  248. package/dist/node-require-Db1oDpLj.js.map +1 -0
  249. package/dist/operation-context-C-2hmmtP.js +59 -0
  250. package/dist/operation-context-C-2hmmtP.js.map +1 -0
  251. package/dist/operation-context-n4_obUwq.cjs +70 -0
  252. package/dist/operation-context-n4_obUwq.cjs.map +1 -0
  253. package/dist/parse-error.cjs +55 -9
  254. package/dist/parse-error.cjs.map +1 -1
  255. package/dist/parse-error.d.cts +12 -10
  256. package/dist/parse-error.d.cts.map +1 -0
  257. package/dist/parse-error.d.ts +12 -10
  258. package/dist/parse-error.d.ts.map +1 -0
  259. package/dist/parse-error.js +55 -2
  260. package/dist/parse-error.js.map +1 -1
  261. package/dist/pretty-console-exporter-CMzlrRNg.cjs +232 -0
  262. package/dist/pretty-console-exporter-CMzlrRNg.cjs.map +1 -0
  263. package/dist/pretty-console-exporter-DqKl_q9z.js +227 -0
  264. package/dist/pretty-console-exporter-DqKl_q9z.js.map +1 -0
  265. package/dist/processors.cjs +13 -17
  266. package/dist/processors.d.cts +3 -171
  267. package/dist/processors.d.ts +3 -171
  268. package/dist/processors.js +4 -4
  269. package/dist/register.cjs +35 -6
  270. package/dist/register.cjs.map +1 -1
  271. package/dist/register.d.cts +1 -2
  272. package/dist/register.d.ts +1 -2
  273. package/dist/register.js +36 -3
  274. package/dist/register.js.map +1 -1
  275. package/dist/registry-DfXA3R1L.js +184 -0
  276. package/dist/registry-DfXA3R1L.js.map +1 -0
  277. package/dist/registry-JZg2J3RZ.cjs +334 -0
  278. package/dist/registry-JZg2J3RZ.cjs.map +1 -0
  279. package/dist/sampling-CR0Va1VB.d.ts +351 -0
  280. package/dist/sampling-CR0Va1VB.d.ts.map +1 -0
  281. package/dist/sampling-DfYhDJij.d.cts +351 -0
  282. package/dist/sampling-DfYhDJij.d.cts.map +1 -0
  283. package/dist/sampling.cjs +452 -60
  284. package/dist/sampling.cjs.map +1 -1
  285. package/dist/sampling.d.cts +2 -379
  286. package/dist/sampling.d.ts +2 -379
  287. package/dist/sampling.js +441 -5
  288. package/dist/sampling.js.map +1 -1
  289. package/dist/security-schema.cjs +65 -46
  290. package/dist/security-schema.cjs.map +1 -1
  291. package/dist/security-schema.d.cts +23 -26
  292. package/dist/security-schema.d.cts.map +1 -0
  293. package/dist/security-schema.d.ts +23 -26
  294. package/dist/security-schema.d.ts.map +1 -0
  295. package/dist/security-schema.js +64 -45
  296. package/dist/security-schema.js.map +1 -1
  297. package/dist/semantic-conventions-FhSxv-bK.d.cts +32 -0
  298. package/dist/semantic-conventions-FhSxv-bK.d.cts.map +1 -0
  299. package/dist/semantic-conventions-FhSxv-bK.d.ts +32 -0
  300. package/dist/semantic-conventions-FhSxv-bK.d.ts.map +1 -0
  301. package/dist/semantic-conventions.cjs +15 -26
  302. package/dist/semantic-conventions.cjs.map +1 -1
  303. package/dist/semantic-conventions.d.cts +2 -29
  304. package/dist/semantic-conventions.d.ts +2 -29
  305. package/dist/semantic-conventions.js +12 -3
  306. package/dist/semantic-conventions.js.map +1 -1
  307. package/dist/semantic-helpers.cjs +440 -38
  308. package/dist/semantic-helpers.cjs.map +1 -1
  309. package/dist/semantic-helpers.d.cts +38 -45
  310. package/dist/semantic-helpers.d.cts.map +1 -0
  311. package/dist/semantic-helpers.d.ts +38 -45
  312. package/dist/semantic-helpers.d.ts.map +1 -0
  313. package/dist/semantic-helpers.js +438 -19
  314. package/dist/semantic-helpers.js.map +1 -1
  315. package/dist/span-name-normalizer-8ZOGJuwv.d.cts +70 -0
  316. package/dist/span-name-normalizer-8ZOGJuwv.d.cts.map +1 -0
  317. package/dist/span-name-normalizer-8ZOGJuwv.d.ts +70 -0
  318. package/dist/span-name-normalizer-8ZOGJuwv.d.ts.map +1 -0
  319. package/dist/span-name-normalizer.cjs +95 -17
  320. package/dist/span-name-normalizer.cjs.map +1 -1
  321. package/dist/span-name-normalizer.d.cts +2 -94
  322. package/dist/span-name-normalizer.d.ts +2 -94
  323. package/dist/span-name-normalizer.js +93 -2
  324. package/dist/span-name-normalizer.js.map +1 -1
  325. package/dist/stable-hash-BNTMrmdB.cjs +28 -0
  326. package/dist/stable-hash-BNTMrmdB.cjs.map +1 -0
  327. package/dist/stable-hash-Cg5cT34Q.js +23 -0
  328. package/dist/stable-hash-Cg5cT34Q.js.map +1 -0
  329. package/dist/structured-error-9--cxBay.js +143 -0
  330. package/dist/structured-error-9--cxBay.js.map +1 -0
  331. package/dist/structured-error-CHg7DoIQ.cjs +178 -0
  332. package/dist/structured-error-CHg7DoIQ.cjs.map +1 -0
  333. package/dist/tail-sampling-processor.cjs +26 -13
  334. package/dist/tail-sampling-processor.cjs.map +1 -1
  335. package/dist/tail-sampling-processor.d.cts +11 -23
  336. package/dist/tail-sampling-processor.d.cts.map +1 -0
  337. package/dist/tail-sampling-processor.d.ts +11 -23
  338. package/dist/tail-sampling-processor.d.ts.map +1 -0
  339. package/dist/tail-sampling-processor.js +27 -6
  340. package/dist/tail-sampling-processor.js.map +1 -1
  341. package/dist/test-span-collector.cjs +70 -72
  342. package/dist/test-span-collector.cjs.map +1 -1
  343. package/dist/test-span-collector.d.cts +25 -43
  344. package/dist/test-span-collector.d.cts.map +1 -0
  345. package/dist/test-span-collector.d.ts +25 -43
  346. package/dist/test-span-collector.d.ts.map +1 -0
  347. package/dist/test-span-collector.js +69 -70
  348. package/dist/test-span-collector.js.map +1 -1
  349. package/dist/testing.cjs +389 -278
  350. package/dist/testing.cjs.map +1 -1
  351. package/dist/testing.d.cts +39 -62
  352. package/dist/testing.d.cts.map +1 -0
  353. package/dist/testing.d.ts +39 -62
  354. package/dist/testing.d.ts.map +1 -0
  355. package/dist/testing.js +386 -265
  356. package/dist/testing.js.map +1 -1
  357. package/dist/trace-context-Cijqoi6e.d.cts +212 -0
  358. package/dist/trace-context-Cijqoi6e.d.cts.map +1 -0
  359. package/dist/trace-context-Cijqoi6e.d.ts +212 -0
  360. package/dist/trace-context-Cijqoi6e.d.ts.map +1 -0
  361. package/dist/trace-helpers.cjs +634 -54
  362. package/dist/trace-helpers.cjs.map +1 -1
  363. package/dist/trace-helpers.d.cts +17 -49
  364. package/dist/trace-helpers.d.cts.map +1 -0
  365. package/dist/trace-helpers.d.ts +17 -49
  366. package/dist/trace-helpers.d.ts.map +1 -0
  367. package/dist/trace-helpers.js +624 -3
  368. package/dist/trace-helpers.js.map +1 -1
  369. package/dist/tracer-provider.cjs +227 -16
  370. package/dist/tracer-provider.cjs.map +1 -1
  371. package/dist/tracer-provider.d.cts +5 -4
  372. package/dist/tracer-provider.d.cts.map +1 -0
  373. package/dist/tracer-provider.d.ts +5 -4
  374. package/dist/tracer-provider.d.ts.map +1 -0
  375. package/dist/tracer-provider.js +227 -2
  376. package/dist/tracer-provider.js.map +1 -1
  377. package/dist/track-3HY4NGV-.cjs +1212 -0
  378. package/dist/track-3HY4NGV-.cjs.map +1 -0
  379. package/dist/track-nsKVy-pj.js +1111 -0
  380. package/dist/track-nsKVy-pj.js.map +1 -0
  381. package/dist/validate.cjs +201 -0
  382. package/dist/validate.cjs.map +1 -0
  383. package/dist/validate.d.cts +105 -0
  384. package/dist/validate.d.cts.map +1 -0
  385. package/dist/validate.d.ts +105 -0
  386. package/dist/validate.d.ts.map +1 -0
  387. package/dist/validate.js +197 -0
  388. package/dist/validate.js.map +1 -0
  389. package/dist/validation-attributes.cjs +45 -0
  390. package/dist/validation-attributes.cjs.map +1 -0
  391. package/dist/validation-attributes.d.cts +33 -0
  392. package/dist/validation-attributes.d.cts.map +1 -0
  393. package/dist/validation-attributes.d.ts +33 -0
  394. package/dist/validation-attributes.d.ts.map +1 -0
  395. package/dist/validation-attributes.js +41 -0
  396. package/dist/validation-attributes.js.map +1 -0
  397. package/dist/webhook.cjs +286 -255
  398. package/dist/webhook.cjs.map +1 -1
  399. package/dist/webhook.d.cts +157 -192
  400. package/dist/webhook.d.cts.map +1 -0
  401. package/dist/webhook.d.ts +157 -192
  402. package/dist/webhook.d.ts.map +1 -0
  403. package/dist/webhook.js +285 -253
  404. package/dist/webhook.js.map +1 -1
  405. package/dist/workflow-distributed.cjs +498 -411
  406. package/dist/workflow-distributed.cjs.map +1 -1
  407. package/dist/workflow-distributed.d.cts +163 -173
  408. package/dist/workflow-distributed.d.cts.map +1 -0
  409. package/dist/workflow-distributed.d.ts +163 -173
  410. package/dist/workflow-distributed.d.ts.map +1 -0
  411. package/dist/workflow-distributed.js +497 -409
  412. package/dist/workflow-distributed.js.map +1 -1
  413. package/dist/workflow.cjs +405 -39
  414. package/dist/workflow.cjs.map +1 -1
  415. package/dist/workflow.d.cts +78 -131
  416. package/dist/workflow.d.cts.map +1 -0
  417. package/dist/workflow.d.ts +78 -131
  418. package/dist/workflow.d.ts.map +1 -0
  419. package/dist/workflow.js +403 -20
  420. package/dist/workflow.js.map +1 -1
  421. package/dist/yaml-config-B3dQ82GR.cjs +272 -0
  422. package/dist/yaml-config-B3dQ82GR.cjs.map +1 -0
  423. package/dist/yaml-config.cjs +5 -24
  424. package/dist/yaml-config.d.cts +30 -64
  425. package/dist/yaml-config.d.cts.map +1 -0
  426. package/dist/yaml-config.d.ts +30 -64
  427. package/dist/yaml-config.d.ts.map +1 -0
  428. package/dist/yaml-config.js +226 -7
  429. package/dist/yaml-config.js.map +1 -1
  430. package/package.json +14 -4
  431. package/src/define-event.ts +2 -21
  432. package/src/index.ts +3 -0
  433. package/src/request-logger.test.ts +53 -1
  434. package/src/request-logger.ts +58 -0
  435. package/src/stable-hash.ts +27 -0
  436. package/src/validate.test.ts +287 -0
  437. package/src/validate.ts +307 -0
  438. package/src/validation-attributes.ts +43 -0
  439. package/dist/attributes.cjs.map +0 -1
  440. package/dist/attributes.js.map +0 -1
  441. package/dist/chunk-2ZKEORFN.cjs +0 -14
  442. package/dist/chunk-2ZKEORFN.cjs.map +0 -1
  443. package/dist/chunk-3QXBFGKP.js +0 -344
  444. package/dist/chunk-3QXBFGKP.js.map +0 -1
  445. package/dist/chunk-454CH4OV.js +0 -744
  446. package/dist/chunk-454CH4OV.js.map +0 -1
  447. package/dist/chunk-4A53YIAX.js +0 -180
  448. package/dist/chunk-4A53YIAX.js.map +0 -1
  449. package/dist/chunk-4IFSYQVX.js +0 -337
  450. package/dist/chunk-4IFSYQVX.js.map +0 -1
  451. package/dist/chunk-4P6ZOARG.cjs +0 -33
  452. package/dist/chunk-4P6ZOARG.cjs.map +0 -1
  453. package/dist/chunk-55ER2KD5.js +0 -228
  454. package/dist/chunk-55ER2KD5.js.map +0 -1
  455. package/dist/chunk-5ZN622AO.js +0 -73
  456. package/dist/chunk-5ZN622AO.js.map +0 -1
  457. package/dist/chunk-6S5RUKU3.cjs +0 -347
  458. package/dist/chunk-6S5RUKU3.cjs.map +0 -1
  459. package/dist/chunk-6UQRVUN3.js +0 -222
  460. package/dist/chunk-6UQRVUN3.js.map +0 -1
  461. package/dist/chunk-7552UTQW.js +0 -11
  462. package/dist/chunk-7552UTQW.js.map +0 -1
  463. package/dist/chunk-7EQ4G4SI.cjs +0 -146
  464. package/dist/chunk-7EQ4G4SI.cjs.map +0 -1
  465. package/dist/chunk-7SAWIN74.js +0 -285
  466. package/dist/chunk-7SAWIN74.js.map +0 -1
  467. package/dist/chunk-A4E5AQFK.js +0 -30
  468. package/dist/chunk-A4E5AQFK.js.map +0 -1
  469. package/dist/chunk-AC5GNZKB.cjs +0 -344
  470. package/dist/chunk-AC5GNZKB.cjs.map +0 -1
  471. package/dist/chunk-ALPYR2GC.js +0 -1061
  472. package/dist/chunk-ALPYR2GC.js.map +0 -1
  473. package/dist/chunk-BZHG5IZ4.js +0 -73
  474. package/dist/chunk-BZHG5IZ4.js.map +0 -1
  475. package/dist/chunk-CEAQK2QY.cjs +0 -32
  476. package/dist/chunk-CEAQK2QY.cjs.map +0 -1
  477. package/dist/chunk-CMHVQR6P.js +0 -170
  478. package/dist/chunk-CMHVQR6P.js.map +0 -1
  479. package/dist/chunk-CU6IDACR.cjs +0 -224
  480. package/dist/chunk-CU6IDACR.cjs.map +0 -1
  481. package/dist/chunk-DPSA4QLA.js +0 -344
  482. package/dist/chunk-DPSA4QLA.js.map +0 -1
  483. package/dist/chunk-DQEHQNQE.js +0 -795
  484. package/dist/chunk-DQEHQNQE.js.map +0 -1
  485. package/dist/chunk-ESLWRGAG.cjs +0 -92
  486. package/dist/chunk-ESLWRGAG.cjs.map +0 -1
  487. package/dist/chunk-ESMHTKLJ.cjs +0 -206
  488. package/dist/chunk-ESMHTKLJ.cjs.map +0 -1
  489. package/dist/chunk-FGNDN2FD.cjs +0 -1242
  490. package/dist/chunk-FGNDN2FD.cjs.map +0 -1
  491. package/dist/chunk-FU6R566Y.cjs +0 -236
  492. package/dist/chunk-FU6R566Y.cjs.map +0 -1
  493. package/dist/chunk-GBFTC7Q7.cjs +0 -837
  494. package/dist/chunk-GBFTC7Q7.cjs.map +0 -1
  495. package/dist/chunk-GYR5K654.js +0 -91
  496. package/dist/chunk-GYR5K654.js.map +0 -1
  497. package/dist/chunk-HA2WBOGQ.js +0 -57
  498. package/dist/chunk-HA2WBOGQ.js.map +0 -1
  499. package/dist/chunk-HT5JQKN2.js +0 -118
  500. package/dist/chunk-HT5JQKN2.js.map +0 -1
  501. package/dist/chunk-INJD3G4K.cjs +0 -340
  502. package/dist/chunk-INJD3G4K.cjs.map +0 -1
  503. package/dist/chunk-IOYFAFHJ.cjs +0 -95
  504. package/dist/chunk-IOYFAFHJ.cjs.map +0 -1
  505. package/dist/chunk-J5QENANM.js +0 -87
  506. package/dist/chunk-J5QENANM.js.map +0 -1
  507. package/dist/chunk-J7VGRIAJ.js +0 -64
  508. package/dist/chunk-J7VGRIAJ.js.map +0 -1
  509. package/dist/chunk-KFOHQK7X.js +0 -144
  510. package/dist/chunk-KFOHQK7X.js.map +0 -1
  511. package/dist/chunk-KIL5CUN6.js +0 -31
  512. package/dist/chunk-KIL5CUN6.js.map +0 -1
  513. package/dist/chunk-LITNXTTT.js +0 -3
  514. package/dist/chunk-LITNXTTT.js.map +0 -1
  515. package/dist/chunk-M3LFHHTN.cjs +0 -764
  516. package/dist/chunk-M3LFHHTN.cjs.map +0 -1
  517. package/dist/chunk-NEIB3TLD.cjs +0 -360
  518. package/dist/chunk-NEIB3TLD.cjs.map +0 -1
  519. package/dist/chunk-NVAI5CCN.cjs +0 -39
  520. package/dist/chunk-NVAI5CCN.cjs.map +0 -1
  521. package/dist/chunk-NVGPMGI4.js +0 -95
  522. package/dist/chunk-NVGPMGI4.js.map +0 -1
  523. package/dist/chunk-NZ72VDNY.cjs +0 -4
  524. package/dist/chunk-NZ72VDNY.cjs.map +0 -1
  525. package/dist/chunk-O4JZUCUE.js +0 -1174
  526. package/dist/chunk-O4JZUCUE.js.map +0 -1
  527. package/dist/chunk-O7JOKRN2.js +0 -833
  528. package/dist/chunk-O7JOKRN2.js.map +0 -1
  529. package/dist/chunk-OPPXYVEZ.cjs +0 -131
  530. package/dist/chunk-OPPXYVEZ.cjs.map +0 -1
  531. package/dist/chunk-Q4EULJQY.js +0 -35
  532. package/dist/chunk-Q4EULJQY.js.map +0 -1
  533. package/dist/chunk-QWW3E3JM.cjs +0 -178
  534. package/dist/chunk-QWW3E3JM.cjs.map +0 -1
  535. package/dist/chunk-R7QYGZUP.cjs +0 -1075
  536. package/dist/chunk-R7QYGZUP.cjs.map +0 -1
  537. package/dist/chunk-RUPKBKUF.js +0 -352
  538. package/dist/chunk-RUPKBKUF.js.map +0 -1
  539. package/dist/chunk-SEO6NAQT.js +0 -14
  540. package/dist/chunk-SEO6NAQT.js.map +0 -1
  541. package/dist/chunk-T4B5LB6E.cjs +0 -66
  542. package/dist/chunk-T4B5LB6E.cjs.map +0 -1
  543. package/dist/chunk-TC5ZPWM4.cjs +0 -289
  544. package/dist/chunk-TC5ZPWM4.cjs.map +0 -1
  545. package/dist/chunk-TQ5UWA7S.js +0 -26
  546. package/dist/chunk-TQ5UWA7S.js.map +0 -1
  547. package/dist/chunk-URHPSJW2.js +0 -339
  548. package/dist/chunk-URHPSJW2.js.map +0 -1
  549. package/dist/chunk-UY3UYPBZ.cjs +0 -77
  550. package/dist/chunk-UY3UYPBZ.cjs.map +0 -1
  551. package/dist/chunk-VG2ABKJX.cjs +0 -100
  552. package/dist/chunk-VG2ABKJX.cjs.map +0 -1
  553. package/dist/chunk-VH77IPJN.cjs +0 -358
  554. package/dist/chunk-VH77IPJN.cjs.map +0 -1
  555. package/dist/chunk-VQTCQKHQ.cjs +0 -17
  556. package/dist/chunk-VQTCQKHQ.cjs.map +0 -1
  557. package/dist/chunk-WGWSHJ2N.js +0 -38
  558. package/dist/chunk-WGWSHJ2N.js.map +0 -1
  559. package/dist/chunk-WJH6IYU2.cjs +0 -32
  560. package/dist/chunk-WJH6IYU2.cjs.map +0 -1
  561. package/dist/chunk-YREV3LGG.cjs +0 -61
  562. package/dist/chunk-YREV3LGG.cjs.map +0 -1
  563. package/dist/chunk-YTXEZ4SD.cjs +0 -77
  564. package/dist/chunk-YTXEZ4SD.cjs.map +0 -1
  565. package/dist/chunk-YWCESU4Y.js +0 -1233
  566. package/dist/chunk-YWCESU4Y.js.map +0 -1
  567. package/dist/chunk-Z6HRSM2Y.cjs +0 -799
  568. package/dist/chunk-Z6HRSM2Y.cjs.map +0 -1
  569. package/dist/chunk-Z7PW3KHL.cjs +0 -1198
  570. package/dist/chunk-Z7PW3KHL.cjs.map +0 -1
  571. package/dist/chunk-ZNMBW67B.cjs +0 -40
  572. package/dist/chunk-ZNMBW67B.cjs.map +0 -1
  573. package/dist/correlation-id.cjs.map +0 -1
  574. package/dist/correlation-id.js.map +0 -1
  575. package/dist/event-subscriber.cjs.map +0 -1
  576. package/dist/event-subscriber.js.map +0 -1
  577. package/dist/event.cjs.map +0 -1
  578. package/dist/event.js.map +0 -1
  579. package/dist/exporters.cjs.map +0 -1
  580. package/dist/exporters.js.map +0 -1
  581. package/dist/functional.cjs.map +0 -1
  582. package/dist/functional.js.map +0 -1
  583. package/dist/init-DIowiiCh.d.ts +0 -1167
  584. package/dist/init-j-A1zI16.d.cts +0 -1167
  585. package/dist/processors.cjs.map +0 -1
  586. package/dist/processors.js.map +0 -1
  587. package/dist/trace-context-DbGKd1Rn.d.cts +0 -213
  588. package/dist/trace-context-DbGKd1Rn.d.ts +0 -213
  589. package/dist/utils-BahBCFtJ.d.cts +0 -712
  590. package/dist/utils-CLKwaUlG.d.ts +0 -712
  591. package/dist/yaml-config.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,787 +1,975 @@
1
- export { parseError } from './chunk-J7VGRIAJ.js';
2
- export { createDrainPipeline } from './chunk-KFOHQK7X.js';
3
- export { getCurrentWorkflowContext, isInWorkflow, traceStep, traceWorkflow } from './chunk-URHPSJW2.js';
4
- export { attrs, autoRedactPII, dbClient, httpClient, httpServer, identify, mergeAttrs, mergeServiceResource, request, safeSetAttributes, setDevice, setError, setException, setSession, setUser, validateAttribute } from './chunk-454CH4OV.js';
5
- export { httpRequestHeaderAttribute, httpResponseHeaderAttribute } from './chunk-7552UTQW.js';
6
- export { HTTPAttributes, ServiceAttributes, URLAttributes } from './chunk-4A53YIAX.js';
7
- export { traceConsumer, traceProducer } from './chunk-DQEHQNQE.js';
8
- import { emitCorrelatedEvent } from './chunk-KIL5CUN6.js';
9
- export { BusinessBaggage, createSafeBaggageSchema } from './chunk-4IFSYQVX.js';
10
- import { resetMetrics } from './chunk-7SAWIN74.js';
11
- export { Metric, getMetrics, resetMetrics } from './chunk-7SAWIN74.js';
12
- import './chunk-5ZN622AO.js';
13
- export { createCounter, createHistogram, createObservableGauge, createUpDownCounter, getMeter } from './chunk-TQ5UWA7S.js';
14
- export { traceDB, traceHTTP, traceLLM, traceMessaging } from './chunk-NVGPMGI4.js';
15
- import { trace as trace$1 } from './chunk-YWCESU4Y.js';
16
- export { ctx, instrument, markAsImmediate, span, withBaggage, withNewContext, withTracing } from './chunk-YWCESU4Y.js';
17
- export { createDeterministicTraceId, enrichWithTraceContext, finalizeSpan, flattenMetadata, getActiveContext, getActiveSpan, getTraceContext, getTracer, isTracing, resolveTraceUrl, runWithSpan } from './chunk-HT5JQKN2.js';
18
- import { resetEvents } from './chunk-O7JOKRN2.js';
19
- export { Event, getEvents, resetEvents } from './chunk-O7JOKRN2.js';
20
- import './chunk-LITNXTTT.js';
21
- import './chunk-BZHG5IZ4.js';
22
- export { getOperationContext, runInOperationContext } from './chunk-SEO6NAQT.js';
23
- import { getEventQueue, resetEventQueue, track, createTraceContext, flattenToAttributes, recordStructuredError, createStructuredError } from './chunk-O4JZUCUE.js';
24
- export { CORRELATION_ID_BAGGAGE_KEY, createStructuredError, defineBaggageSchema, flattenToAttributes, generateCorrelationId, getCorrelationId, getEventQueue, getOrCreateCorrelationId, getStructuredErrorAttributes, recordStructuredError, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage, structuredErrorToJSON, toAttributeValue, track } from './chunk-O4JZUCUE.js';
25
- import { getLogger, getSdk, _closeEmbeddedDevtools } from './chunk-ALPYR2GC.js';
26
- export { BaggageSpanProcessor, createStringRedactor, init, isInitialized, isLoggerLocked, lockLogger } from './chunk-ALPYR2GC.js';
27
- import './chunk-CMHVQR6P.js';
28
- import './chunk-A4E5AQFK.js';
29
- export { FilteringSpanProcessor } from './chunk-WGWSHJ2N.js';
30
- export { NORMALIZER_PATTERNS, NORMALIZER_PRESETS, SpanNameNormalizingProcessor } from './chunk-GYR5K654.js';
31
- export { AttributeRedactingProcessor, REDACTOR_PATTERNS, REDACTOR_PRESETS, builtinPatterns, createAttributeRedactor, createRedactedSpan, normalizeAttributeRedactorConfig } from './chunk-RUPKBKUF.js';
32
- import './chunk-6UQRVUN3.js';
33
- export { formatDuration } from './chunk-3QXBFGKP.js';
34
- import './chunk-Q4EULJQY.js';
35
- export { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, NeverSampler, RandomSampler, UserIdSampler, createLinkFromHeaders, extractLinksFromBatch, resolveSamplingPreset, samplingPresets } from './chunk-DPSA4QLA.js';
36
- import './chunk-55ER2KD5.js';
37
- import './chunk-J5QENANM.js';
38
- export { getAutotelTracer, getAutotelTracerProvider, setAutotelTracerProvider } from './chunk-HA2WBOGQ.js';
39
- import { trace } from '@opentelemetry/api';
40
- export { ROOT_CONTEXT, SpanKind, SpanStatusCode, context, trace as otelTrace, propagation } from '@opentelemetry/api';
41
- import { createHash } from 'crypto';
42
- import { AsyncLocalStorage } from 'async_hooks';
43
- import { AggregationType } from '@opentelemetry/sdk-metrics';
1
+ import { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, NeverSampler, RandomSampler, UserIdSampler, createLinkFromHeaders, extractLinksFromBatch, resolveSamplingPreset, samplingPresets } from "./sampling.js";
2
+ import { a as getSdk, c as isInitialized, f as createStringRedactor, i as getLogger, l as isLoggerLocked, p as BaggageSpanProcessor, s as init, t as _closeEmbeddedDevtools, u as lockLogger } from "./init-Ch6t7MNI.js";
3
+ import { FilteringSpanProcessor } from "./filtering-span-processor.js";
4
+ import { NORMALIZER_PATTERNS, NORMALIZER_PRESETS, SpanNameNormalizingProcessor } from "./span-name-normalizer.js";
5
+ import { AttributeRedactingProcessor, REDACTOR_PATTERNS, REDACTOR_PRESETS, builtinPatterns, createAttributeRedactor, createRedactedSpan, normalizeAttributeRedactorConfig } from "./attribute-redacting-processor.js";
6
+ import { n as formatDuration } from "./canonical-log-line-processor-DbBQT5vY.js";
7
+ import { getAutotelTracer, getAutotelTracerProvider, setAutotelTracerProvider } from "./tracer-provider.js";
8
+ import { a as CORRELATION_ID_BAGGAGE_KEY, d as setCorrelationId, f as setCorrelationIdInBaggage, l as getOrCreateCorrelationId, m as defineBaggageSchema, n as resetEventQueue, o as generateCorrelationId, p as createTraceContext, r as track, s as getCorrelationId, t as getEventQueue, u as runWithCorrelationId } from "./track-nsKVy-pj.js";
9
+ import { a as flattenToAttributes, i as structuredErrorToJSON, n as getStructuredErrorAttributes, o as toAttributeValue, r as recordStructuredError, t as createStructuredError } from "./structured-error-9--cxBay.js";
10
+ import { createDeterministicTraceId, enrichWithTraceContext, finalizeSpan, flattenMetadata, getActiveContext, getActiveSpan, getTraceContext, getTracer, isTracing, resolveTraceUrl, runWithSpan } from "./trace-helpers.js";
11
+ import { n as runInOperationContext, t as getOperationContext } from "./operation-context-C-2hmmtP.js";
12
+ import { a as trace$2, c as withTracing, i as span, n as instrument, o as withBaggage, r as markAsImmediate, s as withNewContext, t as ctx } from "./functional-BGkT8J-h.js";
13
+ import { t as hashJson } from "./stable-hash-Cg5cT34Q.js";
14
+ import { n as getEvents, r as resetEvents, t as Event } from "./event-_58ryBjh.js";
15
+ import { Metric, getMetrics, resetMetrics } from "./metric.js";
16
+ import { t as emitCorrelatedEvent } from "./correlated-events-Bzh5y-UB.js";
17
+ import { parseError } from "./parse-error.js";
18
+ import { createDrainPipeline } from "./drain-pipeline.js";
19
+ import { createCounter, createHistogram, createObservableGauge, createUpDownCounter, getMeter } from "./metric-helpers.js";
20
+ import { traceDB, traceHTTP, traceLLM, traceMessaging } from "./semantic-helpers.js";
21
+ import { b as ServiceAttributes, f as HTTPAttributes, w as URLAttributes } from "./registry-DfXA3R1L.js";
22
+ import { httpRequestHeaderAttribute, httpResponseHeaderAttribute } from "./semantic-conventions.js";
23
+ import { a as identify, c as setDevice, d as setSession, f as setUser, h as autoRedactPII, i as httpServer, l as setError, m as safeSetAttributes, n as dbClient, o as mergeServiceResource, p as mergeAttrs, r as httpClient, s as request, u as setException, v as validateAttribute, y as attrs } from "./attributes-ksn4HVbd.js";
24
+ import { traceConsumer, traceProducer } from "./messaging.js";
25
+ import { BusinessBaggage, createSafeBaggageSchema } from "./business-baggage.js";
26
+ import { getCurrentWorkflowContext, isInWorkflow, traceStep, traceWorkflow } from "./workflow.js";
27
+ import { ROOT_CONTEXT, SpanKind, SpanStatusCode, context, propagation, trace as otelTrace, trace as trace$1 } from "@opentelemetry/api";
28
+ import { AggregationType } from "@opentelemetry/sdk-metrics";
29
+ import { AsyncLocalStorage } from "node:async_hooks";
44
30
 
45
- var otelMethods = {
46
- // Class methods on TraceAPI — bind to the singleton.
47
- setGlobalTracerProvider: trace.setGlobalTracerProvider.bind(trace),
48
- getTracerProvider: trace.getTracerProvider.bind(trace),
49
- getTracer: trace.getTracer.bind(trace),
50
- disable: trace.disable.bind(trace),
51
- // Instance fields on TraceAPI — already standalone, copy by reference.
52
- wrapSpanContext: trace.wrapSpanContext,
53
- isSpanContextValid: trace.isSpanContextValid,
54
- deleteSpan: trace.deleteSpan,
55
- getSpan: trace.getSpan,
56
- getActiveSpan: trace.getActiveSpan,
57
- getSpanContext: trace.getSpanContext,
58
- setSpan: trace.setSpan,
59
- setSpanContext: trace.setSpanContext
31
+ //#region src/trace-hybrid.ts
32
+ /**
33
+ * Hybrid `trace` export: callable like autotel's `trace(fn)`, AND exposes the
34
+ * full `@opentelemetry/api` `TraceAPI` surface (`trace.getActiveSpan()`,
35
+ * `trace.getTracer()`, …) so existing OTel code "just works" when imported
36
+ * from `autotel`.
37
+ *
38
+ * Implementation: `Object.assign` mutates the autotel `trace` function to
39
+ * attach the OTel TraceAPI methods. Because every reference to `trace` across
40
+ * autotel resolves to the same function instance, this is a one-time, global
41
+ * augmentation.
42
+ */
43
+ const otelMethods = {
44
+ setGlobalTracerProvider: trace$1.setGlobalTracerProvider.bind(trace$1),
45
+ getTracerProvider: trace$1.getTracerProvider.bind(trace$1),
46
+ getTracer: trace$1.getTracer.bind(trace$1),
47
+ disable: trace$1.disable.bind(trace$1),
48
+ wrapSpanContext: trace$1.wrapSpanContext,
49
+ isSpanContextValid: trace$1.isSpanContextValid,
50
+ deleteSpan: trace$1.deleteSpan,
51
+ getSpan: trace$1.getSpan,
52
+ getActiveSpan: trace$1.getActiveSpan,
53
+ getSpanContext: trace$1.getSpanContext,
54
+ setSpan: trace$1.setSpan,
55
+ setSpanContext: trace$1.setSpanContext
60
56
  };
61
- var trace2 = Object.assign(
62
- trace$1,
63
- otelMethods
64
- );
57
+ const trace = Object.assign(trace$2, otelMethods);
58
+
59
+ //#endregion
60
+ //#region src/define-event.ts
65
61
  function defineEvent(name, schema, options = {}) {
66
- const jsonSchema = options.toJsonSchema?.(schema);
67
- const schemaMetadata = jsonSchema ? {
68
- source: "zod",
69
- jsonSchema,
70
- hash: hashSchema(jsonSchema)
71
- } : void 0;
72
- return {
73
- name,
74
- schemaMetadata,
75
- track(payload) {
76
- const parsed = schema.safeParse(payload);
77
- if (!parsed.success) {
78
- throw new Error(
79
- `Invalid payload for event "${name}". Schema validation failed.`
80
- );
81
- }
82
- track(
83
- name,
84
- parsed.data,
85
- schemaMetadata ? { schema: schemaMetadata } : void 0
86
- );
87
- }
88
- };
89
- }
90
- function hashSchema(schema) {
91
- return createHash("sha256").update(stableStringify(schema)).digest("hex");
92
- }
93
- function stableStringify(value) {
94
- if (value === null || value === void 0 || typeof value !== "object") {
95
- return JSON.stringify(value);
96
- }
97
- if (Array.isArray(value)) {
98
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
99
- }
100
- const obj = value;
101
- const body = Object.keys(obj).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",");
102
- return "{" + body + "}";
62
+ const jsonSchema = options.toJsonSchema?.(schema);
63
+ const schemaMetadata = jsonSchema ? {
64
+ source: "zod",
65
+ jsonSchema,
66
+ hash: hashJson(jsonSchema)
67
+ } : void 0;
68
+ return {
69
+ name,
70
+ schemaMetadata,
71
+ track(payload) {
72
+ const parsed = schema.safeParse(payload);
73
+ if (!parsed.success) throw new Error(`Invalid payload for event "${name}". Schema validation failed.`);
74
+ track(name, parsed.data, schemaMetadata ? { schema: schemaMetadata } : void 0);
75
+ }
76
+ };
103
77
  }
104
78
 
105
- // src/shutdown.ts
79
+ //#endregion
80
+ //#region src/shutdown.ts
81
+ /**
82
+ * Graceful shutdown with flush and cleanup
83
+ */
84
+ /**
85
+ * Flush all pending telemetry
86
+ *
87
+ * Flushes both events events and OpenTelemetry spans to their destinations.
88
+ * Includes timeout protection to prevent hanging in serverless environments.
89
+ *
90
+ * Safe to call multiple times.
91
+ *
92
+ * @param options - Optional configuration
93
+ * @param options.timeout - Timeout in milliseconds (default: 2000ms)
94
+ * @param options.forShutdown - If true, permanently disables the events queue after flush (used internally by shutdown())
95
+ *
96
+ * @example Manual flush in serverless
97
+ * ```typescript
98
+ * import { flush } from 'autotel';
99
+ *
100
+ * export const handler = async (event) => {
101
+ * // ... process event
102
+ * await flush(); // Flush before function returns
103
+ * return result;
104
+ * };
105
+ * ```
106
+ *
107
+ * @example With custom timeout
108
+ * ```typescript
109
+ * await flush({ timeout: 5000 }); // 5 second timeout
110
+ * ```
111
+ */
106
112
  async function flush(options) {
107
- const timeout = options?.timeout ?? 2e3;
108
- const forShutdown = options?.forShutdown ?? false;
109
- const doFlush = async () => {
110
- const eventsQueue = getEventQueue();
111
- if (eventsQueue) {
112
- if (forShutdown) {
113
- await eventsQueue.shutdown();
114
- } else {
115
- await eventsQueue.flush();
116
- }
117
- }
118
- const sdk = getSdk();
119
- if (sdk) {
120
- try {
121
- const sdkAny = sdk;
122
- if (typeof sdkAny.getTracerProvider === "function") {
123
- const tracerProvider = sdkAny.getTracerProvider();
124
- if (tracerProvider && typeof tracerProvider.forceFlush === "function") {
125
- await tracerProvider.forceFlush();
126
- }
127
- }
128
- } catch {
129
- }
130
- }
131
- };
132
- let timeoutHandle;
133
- try {
134
- await Promise.race([
135
- doFlush().finally(() => {
136
- if (timeoutHandle) {
137
- clearTimeout(timeoutHandle);
138
- }
139
- }),
140
- new Promise((_, reject) => {
141
- timeoutHandle = setTimeout(
142
- () => reject(new Error("Flush timeout")),
143
- timeout
144
- );
145
- timeoutHandle.unref();
146
- })
147
- ]);
148
- } catch (error) {
149
- if (timeoutHandle) {
150
- clearTimeout(timeoutHandle);
151
- }
152
- const logger = getLogger();
153
- logger.error(
154
- {
155
- err: error instanceof Error ? error : new Error(String(error))
156
- },
157
- "[autotel] Flush error"
158
- );
159
- throw error;
160
- }
161
- }
113
+ const timeout = options?.timeout ?? 2e3;
114
+ const forShutdown = options?.forShutdown ?? false;
115
+ const doFlush = async () => {
116
+ const eventsQueue = getEventQueue();
117
+ if (eventsQueue) if (forShutdown) await eventsQueue.shutdown();
118
+ else await eventsQueue.flush();
119
+ const sdk = getSdk();
120
+ if (sdk) try {
121
+ const sdkAny = sdk;
122
+ if (typeof sdkAny.getTracerProvider === "function") {
123
+ const tracerProvider = sdkAny.getTracerProvider();
124
+ if (tracerProvider && typeof tracerProvider.forceFlush === "function") await tracerProvider.forceFlush();
125
+ }
126
+ } catch {}
127
+ };
128
+ let timeoutHandle;
129
+ try {
130
+ await Promise.race([doFlush().finally(() => {
131
+ if (timeoutHandle) clearTimeout(timeoutHandle);
132
+ }), new Promise((_, reject) => {
133
+ timeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error("Flush timeout")), timeout);
134
+ timeoutHandle.unref();
135
+ })]);
136
+ } catch (error) {
137
+ if (timeoutHandle) clearTimeout(timeoutHandle);
138
+ getLogger().error({ err: error instanceof Error ? error : new Error(String(error)) }, "[autotel] Flush error");
139
+ throw error;
140
+ }
141
+ }
142
+ /**
143
+ * Shutdown telemetry and cleanup resources
144
+ *
145
+ * - Flushes all pending data
146
+ * - Shuts down OpenTelemetry SDK
147
+ * - Cleans up resources
148
+ *
149
+ * Call this before process exit.
150
+ *
151
+ * Always performs cleanup even if flush fails, preventing resource leaks
152
+ * in serverless handlers or tests.
153
+ *
154
+ * @example Express server
155
+ * ```typescript
156
+ * const server = app.listen(3000)
157
+ *
158
+ * process.on('SIGTERM', async () => {
159
+ * await server.close()
160
+ * await shutdown()
161
+ * process.exit(0)
162
+ * })
163
+ * ```
164
+ */
162
165
  async function shutdown() {
163
- const logger = getLogger();
164
- let shutdownError = null;
165
- try {
166
- await flush({ forShutdown: true });
167
- } catch (error) {
168
- const err = error instanceof Error ? error : new Error(String(error));
169
- shutdownError = err;
170
- logger.error(
171
- {
172
- err
173
- },
174
- "[autotel] Flush failed during shutdown, continuing cleanup"
175
- );
176
- }
177
- try {
178
- const sdk = getSdk();
179
- if (sdk) {
180
- await sdk.shutdown();
181
- }
182
- } catch (error) {
183
- const err = error instanceof Error ? error : new Error(String(error));
184
- const isConnectionRefused = typeof error === "object" && error !== null && "code" in error && error.code === "ECONNREFUSED";
185
- if (!isConnectionRefused) {
186
- if (!shutdownError) {
187
- shutdownError = err;
188
- }
189
- logger.error({ err }, "[autotel] SDK shutdown failed");
190
- }
191
- } finally {
192
- await _closeEmbeddedDevtools();
193
- const eventsQueue = getEventQueue();
194
- if (eventsQueue && typeof eventsQueue.cleanup === "function") {
195
- eventsQueue.cleanup();
196
- }
197
- resetEvents();
198
- resetMetrics();
199
- resetEventQueue();
200
- }
201
- if (shutdownError) {
202
- throw shutdownError;
203
- }
204
- }
166
+ const logger = getLogger();
167
+ let shutdownError = null;
168
+ try {
169
+ await flush({ forShutdown: true });
170
+ } catch (error) {
171
+ const err = error instanceof Error ? error : new Error(String(error));
172
+ shutdownError = err;
173
+ logger.error({ err }, "[autotel] Flush failed during shutdown, continuing cleanup");
174
+ }
175
+ try {
176
+ const sdk = getSdk();
177
+ if (sdk) await sdk.shutdown();
178
+ } catch (error) {
179
+ const err = error instanceof Error ? error : new Error(String(error));
180
+ if (!(typeof error === "object" && error !== null && "code" in error && error.code === "ECONNREFUSED")) {
181
+ if (!shutdownError) shutdownError = err;
182
+ logger.error({ err }, "[autotel] SDK shutdown failed");
183
+ }
184
+ } finally {
185
+ await _closeEmbeddedDevtools();
186
+ const eventsQueue = getEventQueue();
187
+ if (eventsQueue && typeof eventsQueue.cleanup === "function") eventsQueue.cleanup();
188
+ resetEvents();
189
+ resetMetrics();
190
+ resetEventQueue();
191
+ }
192
+ if (shutdownError) throw shutdownError;
193
+ }
194
+ /**
195
+ * Register automatic shutdown hooks for common signals
196
+ *
197
+ * Handles:
198
+ * - SIGTERM (Docker/K8s graceful shutdown)
199
+ * - SIGINT (Ctrl+C)
200
+ *
201
+ * @internal Called automatically on module load
202
+ */
205
203
  function registerShutdownHooks() {
206
- if (typeof process === "undefined") return;
207
- const signals = ["SIGTERM", "SIGINT"];
208
- let shuttingDown = false;
209
- for (const signal of signals) {
210
- process.on(signal, async () => {
211
- if (shuttingDown) return;
212
- shuttingDown = true;
213
- if (process.env.NODE_ENV !== "test") {
214
- getLogger().info(
215
- {},
216
- `[autotel] Received ${signal}, flushing telemetry...`
217
- );
218
- }
219
- try {
220
- await shutdown();
221
- } catch (error) {
222
- getLogger().error(
223
- {
224
- err: error instanceof Error ? error : void 0
225
- },
226
- "[autotel] Error during shutdown"
227
- );
228
- } finally {
229
- process.exit(0);
230
- }
231
- });
232
- }
204
+ if (typeof process === "undefined") return;
205
+ const signals = ["SIGTERM", "SIGINT"];
206
+ let shuttingDown = false;
207
+ for (const signal of signals) process.on(signal, async () => {
208
+ if (shuttingDown) return;
209
+ shuttingDown = true;
210
+ if (process.env.NODE_ENV !== "test") getLogger().info({}, `[autotel] Received ${signal}, flushing telemetry...`);
211
+ try {
212
+ await shutdown();
213
+ } catch (error) {
214
+ getLogger().error({ err: error instanceof Error ? error : void 0 }, "[autotel] Error during shutdown");
215
+ } finally {
216
+ process.exit(0);
217
+ }
218
+ });
233
219
  }
234
220
  registerShutdownHooks();
235
- var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when available.";
221
+
222
+ //#endregion
223
+ //#region src/request-logger.ts
224
+ const POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when available.";
236
225
  function warnPostEmit(method, detail) {
237
- console.warn(
238
- `[autotel] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`
239
- );
240
- }
241
- function mergeInto(target, source) {
242
- for (const key in source) {
243
- const sourceVal = source[key];
244
- if (sourceVal === void 0) continue;
245
- const targetVal = target[key];
246
- if (sourceVal !== null && typeof sourceVal === "object" && !Array.isArray(sourceVal) && targetVal !== null && typeof targetVal === "object" && !Array.isArray(targetVal)) {
247
- mergeInto(
248
- targetVal,
249
- sourceVal
250
- );
251
- } else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {
252
- target[key] = [...targetVal, ...sourceVal];
253
- } else {
254
- target[key] = sourceVal;
255
- }
256
- }
257
- }
258
- var requestContextStore = new AsyncLocalStorage();
259
- function runWithRequestContext(ctx2, fn) {
260
- return requestContextStore.run(ctx2, fn);
261
- }
262
- function resolveContext(ctx2) {
263
- if (ctx2) return ctx2;
264
- const stored = requestContextStore.getStore();
265
- if (stored) return stored;
266
- const span2 = trace.getActiveSpan();
267
- if (!span2) {
268
- throw new Error(
269
- "[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext()."
270
- );
271
- }
272
- return createTraceContext(span2);
273
- }
274
- function getRequestLogger(ctx2, options) {
275
- const activeContext = resolveContext(ctx2);
276
- let contextState = {};
277
- let emitted = false;
278
- let lastSnapshot = null;
279
- const addLogEvent = (level, message, fields) => {
280
- const attrs2 = fields ? flattenToAttributes(fields) : void 0;
281
- emitCorrelatedEvent(activeContext, `log.${level}`, {
282
- message,
283
- ...attrs2 ?? {}
284
- });
285
- };
286
- const sealCheck = (method, keys) => {
287
- if (emitted) {
288
- warnPostEmit(
289
- method,
290
- `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`
291
- );
292
- }
293
- };
294
- return {
295
- set(fields) {
296
- sealCheck("log.set()", Object.keys(fields));
297
- if (emitted) return;
298
- mergeInto(contextState, fields);
299
- activeContext.setAttributes(flattenToAttributes(fields));
300
- },
301
- info(message, fields) {
302
- const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"];
303
- sealCheck("log.info()", keys);
304
- if (emitted) return;
305
- addLogEvent("info", message, fields);
306
- if (fields) {
307
- mergeInto(contextState, fields);
308
- activeContext.setAttributes(flattenToAttributes(fields));
309
- }
310
- },
311
- warn(message, fields) {
312
- const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"];
313
- sealCheck("log.warn()", keys);
314
- if (emitted) return;
315
- addLogEvent("warn", message, fields);
316
- activeContext.setAttribute("autotel.log.level", "warn");
317
- if (fields) {
318
- mergeInto(contextState, fields);
319
- activeContext.setAttributes(flattenToAttributes(fields));
320
- }
321
- },
322
- error(error, fields) {
323
- const keys = fields ? [...Object.keys(fields), "error"] : ["error"];
324
- sealCheck("log.error()", keys);
325
- if (emitted) return;
326
- const err = typeof error === "string" ? new Error(error) : error;
327
- recordStructuredError(activeContext, err);
328
- addLogEvent("error", err.message, fields);
329
- if (fields) {
330
- mergeInto(contextState, fields);
331
- activeContext.setAttributes(flattenToAttributes(fields));
332
- }
333
- activeContext.setAttribute("autotel.log.level", "error");
334
- },
335
- getContext() {
336
- return { ...contextState };
337
- },
338
- emitNow(overrides) {
339
- if (emitted) {
340
- warnPostEmit("log.emitNow()", "Ignoring duplicate emit.");
341
- return lastSnapshot;
342
- }
343
- const mergedContext = {
344
- ...contextState,
345
- ...overrides ?? {}
346
- };
347
- const flattened = flattenToAttributes(mergedContext);
348
- activeContext.setAttributes(flattened);
349
- const snapshot = {
350
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
351
- traceId: activeContext.traceId,
352
- spanId: activeContext.spanId,
353
- correlationId: activeContext.correlationId,
354
- context: mergedContext
355
- };
356
- emitCorrelatedEvent(activeContext, "log.emit.manual", {
357
- ...flattened
358
- });
359
- if (options?.onEmit) {
360
- Promise.resolve(options.onEmit(snapshot)).catch((error) => {
361
- console.warn("[autotel] request logger onEmit failed:", error);
362
- });
363
- }
364
- emitted = true;
365
- lastSnapshot = snapshot;
366
- return snapshot;
367
- },
368
- fork(label, fn, forkOptions) {
369
- const parentRequestId = activeContext.correlationId;
370
- if (typeof parentRequestId !== "string" || parentRequestId.length === 0) {
371
- throw new Error(
372
- "[autotel] log.fork() requires the parent logger to have a correlationId. Ensure the request was created by autotel middleware."
373
- );
374
- }
375
- const tracer = trace.getTracer("autotel.request-logger");
376
- const lifecycle = forkOptions?.lifecycle;
377
- void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {
378
- const childContext = {
379
- ...createTraceContext(childSpan),
380
- correlationId: crypto.randomUUID()
381
- };
382
- requestContextStore.run(childContext, () => {
383
- const childLog = getRequestLogger(childContext);
384
- childLog.set({
385
- operation: label,
386
- _parentCorrelationId: parentRequestId
387
- });
388
- lifecycle?.onChildEnter?.(childLog);
389
- void Promise.resolve().then(() => fn()).then(() => {
390
- childLog.emitNow();
391
- }).catch((err) => {
392
- const error = err instanceof Error ? err : new Error(String(err));
393
- childLog.error(error);
394
- childLog.emitNow();
395
- }).finally(() => {
396
- try {
397
- lifecycle?.onChildExit?.(childLog);
398
- } catch (hookError) {
399
- console.warn(
400
- "[autotel] fork onChildExit hook threw:",
401
- hookError
402
- );
403
- }
404
- childSpan.end();
405
- });
406
- });
407
- });
408
- }
409
- };
226
+ console.warn(`[autotel] ${method} called after the wide event was emitted — ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
227
+ }
228
+ function mergeInto$1(target, source) {
229
+ for (const key in source) {
230
+ const sourceVal = source[key];
231
+ if (sourceVal === void 0) continue;
232
+ const targetVal = target[key];
233
+ if (sourceVal !== null && typeof sourceVal === "object" && !Array.isArray(sourceVal) && targetVal !== null && typeof targetVal === "object" && !Array.isArray(targetVal)) mergeInto$1(targetVal, sourceVal);
234
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) target[key] = [...targetVal, ...sourceVal];
235
+ else target[key] = sourceVal;
236
+ }
237
+ }
238
+ const requestContextStore = new AsyncLocalStorage();
239
+ function runWithRequestContext(ctx, fn) {
240
+ return requestContextStore.run(ctx, fn);
241
+ }
242
+ function resolveContext(ctx) {
243
+ if (ctx) return ctx;
244
+ const stored = requestContextStore.getStore();
245
+ if (stored) return stored;
246
+ const span = trace$1.getActiveSpan();
247
+ if (!span) throw new Error("[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext().");
248
+ return createTraceContext(span);
249
+ }
250
+ function getRequestLogger(ctx, options) {
251
+ const activeContext = resolveContext(ctx);
252
+ let contextState = {};
253
+ let emitted = false;
254
+ let lastSnapshot = null;
255
+ const addLogEvent = (level, message, fields) => {
256
+ const attrs = fields ? flattenToAttributes(fields) : void 0;
257
+ emitCorrelatedEvent(activeContext, `log.${level}`, {
258
+ message,
259
+ ...attrs ?? {}
260
+ });
261
+ };
262
+ const sealCheck = (method, keys) => {
263
+ if (emitted) warnPostEmit(method, `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
264
+ };
265
+ return {
266
+ set(fields) {
267
+ sealCheck("log.set()", Object.keys(fields));
268
+ if (emitted) return;
269
+ mergeInto$1(contextState, fields);
270
+ activeContext.setAttributes(flattenToAttributes(fields));
271
+ },
272
+ info(message, fields) {
273
+ sealCheck("log.info()", fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]);
274
+ if (emitted) return;
275
+ addLogEvent("info", message, fields);
276
+ if (fields) {
277
+ mergeInto$1(contextState, fields);
278
+ activeContext.setAttributes(flattenToAttributes(fields));
279
+ }
280
+ },
281
+ warn(message, fields) {
282
+ sealCheck("log.warn()", fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]);
283
+ if (emitted) return;
284
+ addLogEvent("warn", message, fields);
285
+ activeContext.setAttribute("autotel.log.level", "warn");
286
+ if (fields) {
287
+ mergeInto$1(contextState, fields);
288
+ activeContext.setAttributes(flattenToAttributes(fields));
289
+ }
290
+ },
291
+ error(error, fields) {
292
+ sealCheck("log.error()", fields ? [...Object.keys(fields), "error"] : ["error"]);
293
+ if (emitted) return;
294
+ const err = typeof error === "string" ? new Error(error) : error;
295
+ recordStructuredError(activeContext, err);
296
+ addLogEvent("error", err.message, fields);
297
+ if (fields) {
298
+ mergeInto$1(contextState, fields);
299
+ activeContext.setAttributes(flattenToAttributes(fields));
300
+ }
301
+ activeContext.setAttribute("autotel.log.level", "error");
302
+ },
303
+ getContext() {
304
+ return { ...contextState };
305
+ },
306
+ emitNow(overrides) {
307
+ if (emitted) {
308
+ warnPostEmit("log.emitNow()", "Ignoring duplicate emit.");
309
+ return lastSnapshot;
310
+ }
311
+ const mergedContext = {
312
+ ...contextState,
313
+ ...overrides ?? {}
314
+ };
315
+ const flattened = flattenToAttributes(mergedContext);
316
+ activeContext.setAttributes(flattened);
317
+ const snapshot = {
318
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
319
+ traceId: activeContext.traceId,
320
+ spanId: activeContext.spanId,
321
+ correlationId: activeContext.correlationId,
322
+ context: mergedContext
323
+ };
324
+ emitCorrelatedEvent(activeContext, "log.emit.manual", { ...flattened });
325
+ if (options?.onEmit) Promise.resolve(options.onEmit(snapshot)).catch((error) => {
326
+ console.warn("[autotel] request logger onEmit failed:", error);
327
+ });
328
+ emitted = true;
329
+ lastSnapshot = snapshot;
330
+ return snapshot;
331
+ },
332
+ fork(label, fn, forkOptions) {
333
+ const parentRequestId = activeContext.correlationId;
334
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0) throw new Error("[autotel] log.fork() requires the parent logger to have a correlationId. Ensure the request was created by autotel middleware.");
335
+ const tracer = trace$1.getTracer("autotel.request-logger");
336
+ const lifecycle = forkOptions?.lifecycle;
337
+ tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {
338
+ const childContext = {
339
+ ...createTraceContext(childSpan),
340
+ correlationId: crypto.randomUUID()
341
+ };
342
+ requestContextStore.run(childContext, () => {
343
+ const childLog = getRequestLogger(childContext);
344
+ childLog.set({
345
+ operation: label,
346
+ _parentCorrelationId: parentRequestId
347
+ });
348
+ lifecycle?.onChildEnter?.(childLog);
349
+ Promise.resolve().then(() => fn()).then(() => {
350
+ childLog.emitNow();
351
+ }).catch((err) => {
352
+ const error = err instanceof Error ? err : new Error(String(err));
353
+ childLog.error(error);
354
+ childLog.emitNow();
355
+ }).finally(() => {
356
+ try {
357
+ lifecycle?.onChildExit?.(childLog);
358
+ } catch (hookError) {
359
+ console.warn("[autotel] fork onChildExit hook threw:", hookError);
360
+ }
361
+ childSpan.end();
362
+ });
363
+ });
364
+ });
365
+ }
366
+ };
367
+ }
368
+ /**
369
+ * Returns `true` when a request-logger context can be resolved without throwing —
370
+ * i.e. an explicit `ctx` was provided, a `runWithRequestContext()` scope is active,
371
+ * or there is an active OpenTelemetry span.
372
+ *
373
+ * Use this to branch on observability availability instead of wrapping
374
+ * {@link getRequestLogger} in try/catch.
375
+ */
376
+ function hasRequestContext(ctx) {
377
+ if (ctx) return true;
378
+ if (requestContextStore.getStore()) return true;
379
+ return trace$1.getActiveSpan() != null;
380
+ }
381
+ /**
382
+ * Like {@link getRequestLogger}, but returns `null` instead of throwing when no
383
+ * request context is available. Intended for best-effort instrumentation where a
384
+ * missing telemetry context must never crash business logic.
385
+ */
386
+ function getRequestLoggerSafe(ctx, options) {
387
+ if (!hasRequestContext(ctx)) return null;
388
+ return getRequestLogger(ctx, options);
389
+ }
390
+ /**
391
+ * A no-op {@link RequestLogger} whose methods do nothing. Used as a fallback by
392
+ * best-effort instrumentation so wrapped handlers can run un-instrumented without
393
+ * branching on logger presence.
394
+ */
395
+ function createNoopRequestLogger() {
396
+ const snapshot = () => ({
397
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
398
+ traceId: "",
399
+ spanId: "",
400
+ correlationId: "",
401
+ context: {}
402
+ });
403
+ return {
404
+ set() {},
405
+ info() {},
406
+ warn() {},
407
+ error() {},
408
+ getContext() {
409
+ return {};
410
+ },
411
+ emitNow() {
412
+ return snapshot();
413
+ },
414
+ fork(_label, fn) {
415
+ Promise.resolve().then(() => fn());
416
+ }
417
+ };
410
418
  }
411
419
 
412
- // src/error-catalog.ts
413
- var catalogCodeKey = /* @__PURE__ */ Symbol.for("autotel.catalog.code");
420
+ //#endregion
421
+ //#region src/error-catalog.ts
422
+ /**
423
+ * Typed error and audit catalogs.
424
+ *
425
+ * Group related errors into one catalog and get a refactor-safe builder per
426
+ * code, with autocomplete at every call site and typed message parameters.
427
+ *
428
+ * @example
429
+ * ```typescript
430
+ * import { defineErrorCatalog } from 'autotel';
431
+ *
432
+ * export const billing = defineErrorCatalog('billing', {
433
+ * PAYMENT_DECLINED: {
434
+ * status: 402,
435
+ * message: 'Card declined',
436
+ * why: 'The issuer rejected the charge',
437
+ * fix: 'Try a different payment method',
438
+ * },
439
+ * INSUFFICIENT_FUNDS: {
440
+ * status: 402,
441
+ * message: ({ available, required }: { available: number; required: number }) =>
442
+ * `Insufficient funds: $${available} of $${required}`,
443
+ * },
444
+ * });
445
+ *
446
+ * throw billing.PAYMENT_DECLINED({ cause: stripeError });
447
+ * throw billing.INSUFFICIENT_FUNDS({ available: 5, required: 100 });
448
+ *
449
+ * // In a catch block — refactor-safe, no magic strings:
450
+ * if (billing.PAYMENT_DECLINED.match(err)) { ... }
451
+ * ```
452
+ */
453
+ const catalogCodeKey = Symbol.for("autotel.catalog.code");
414
454
  function readCatalogCode(error) {
415
- if (error === null || typeof error !== "object") return void 0;
416
- return error[catalogCodeKey];
455
+ if (error === null || typeof error !== "object") return void 0;
456
+ return error[catalogCodeKey];
417
457
  }
458
+ /** True when `error` was produced by any autotel error catalog. */
418
459
  function isCatalogError(error) {
419
- return readCatalogCode(error) !== void 0;
460
+ return readCatalogCode(error) !== void 0;
420
461
  }
462
+ /** Returns the catalog code of `error`, or `undefined` if it has none. */
421
463
  function getCatalogCode(error) {
422
- return readCatalogCode(error);
464
+ return readCatalogCode(error);
423
465
  }
466
+ /**
467
+ * Define a typed error catalog. Returns an object whose keys are error
468
+ * builders. Each builder produces a {@link StructuredError} carrying the
469
+ * entry's message, status, code, why, fix, and link.
470
+ */
424
471
  function defineErrorCatalog(namespace, entries) {
425
- const catalog = {};
426
- for (const [key, entry] of Object.entries(entries)) {
427
- const code = entry.code ?? `${namespace}.${key}`;
428
- const usesParams = typeof entry.message === "function" || typeof entry.why === "function";
429
- const builder = ((paramsOrOptions, maybeOptions) => {
430
- const params = usesParams ? paramsOrOptions : void 0;
431
- const options = usesParams ? maybeOptions : paramsOrOptions;
432
- const message = typeof entry.message === "function" ? entry.message(params) : entry.message;
433
- const why = typeof entry.why === "function" ? entry.why(params) : entry.why;
434
- const error = createStructuredError({
435
- message,
436
- name: entry.name ?? key,
437
- code,
438
- ...entry.status === void 0 ? {} : { status: entry.status },
439
- ...why === void 0 ? {} : { why },
440
- ...entry.fix === void 0 ? {} : { fix: entry.fix },
441
- ...entry.link === void 0 ? {} : { link: entry.link },
442
- ...options?.cause === void 0 ? {} : { cause: options.cause },
443
- ...options?.details === void 0 ? {} : { details: options.details },
444
- ...options?.internal === void 0 ? {} : { internal: options.internal }
445
- });
446
- Object.defineProperty(error, catalogCodeKey, {
447
- value: code,
448
- enumerable: false,
449
- writable: false,
450
- configurable: true
451
- });
452
- return error;
453
- });
454
- Object.defineProperty(builder, "code", {
455
- value: code,
456
- enumerable: true
457
- });
458
- Object.defineProperty(builder, "match", {
459
- value: (error) => readCatalogCode(error) === code,
460
- enumerable: false
461
- });
462
- catalog[key] = builder;
463
- }
464
- return Object.freeze(catalog);
465
- }
472
+ const catalog = {};
473
+ for (const [key, entry] of Object.entries(entries)) {
474
+ const code = entry.code ?? `${namespace}.${key}`;
475
+ const usesParams = typeof entry.message === "function" || typeof entry.why === "function";
476
+ const builder = ((paramsOrOptions, maybeOptions) => {
477
+ const params = usesParams ? paramsOrOptions : void 0;
478
+ const options = usesParams ? maybeOptions : paramsOrOptions;
479
+ const message = typeof entry.message === "function" ? entry.message(params) : entry.message;
480
+ const why = typeof entry.why === "function" ? entry.why(params) : entry.why;
481
+ const error = createStructuredError({
482
+ message,
483
+ name: entry.name ?? key,
484
+ code,
485
+ ...entry.status === void 0 ? {} : { status: entry.status },
486
+ ...why === void 0 ? {} : { why },
487
+ ...entry.fix === void 0 ? {} : { fix: entry.fix },
488
+ ...entry.link === void 0 ? {} : { link: entry.link },
489
+ ...options?.cause === void 0 ? {} : { cause: options.cause },
490
+ ...options?.details === void 0 ? {} : { details: options.details },
491
+ ...options?.internal === void 0 ? {} : { internal: options.internal }
492
+ });
493
+ Object.defineProperty(error, catalogCodeKey, {
494
+ value: code,
495
+ enumerable: false,
496
+ writable: false,
497
+ configurable: true
498
+ });
499
+ return error;
500
+ });
501
+ Object.defineProperty(builder, "code", {
502
+ value: code,
503
+ enumerable: true
504
+ });
505
+ Object.defineProperty(builder, "match", {
506
+ value: (error) => readCatalogCode(error) === code,
507
+ enumerable: false
508
+ });
509
+ catalog[key] = builder;
510
+ }
511
+ return Object.freeze(catalog);
512
+ }
513
+ /**
514
+ * Define a typed audit catalog. Returns typed action descriptors you can pass
515
+ * to `track()` or audit helpers without scattering magic strings.
516
+ */
466
517
  function defineAuditCatalog(namespace, entries) {
467
- const catalog = {};
468
- for (const [key, entry] of Object.entries(entries)) {
469
- const action = entry.action ?? `${namespace}.${key}`;
470
- const severity = entry.severity ?? "info";
471
- const descriptor = ((params) => {
472
- const message = typeof entry.message === "function" ? entry.message(params) : entry.message;
473
- return Object.freeze({
474
- action,
475
- severity,
476
- ...message === void 0 ? {} : { message }
477
- });
478
- });
479
- Object.defineProperty(descriptor, "action", {
480
- value: action,
481
- enumerable: true
482
- });
483
- Object.defineProperty(descriptor, "severity", {
484
- value: severity,
485
- enumerable: true
486
- });
487
- catalog[key] = descriptor;
488
- }
489
- return Object.freeze(catalog);
518
+ const catalog = {};
519
+ for (const [key, entry] of Object.entries(entries)) {
520
+ const action = entry.action ?? `${namespace}.${key}`;
521
+ const severity = entry.severity ?? "info";
522
+ const descriptor = ((params) => {
523
+ const message = typeof entry.message === "function" ? entry.message(params) : entry.message;
524
+ return Object.freeze({
525
+ action,
526
+ severity,
527
+ ...message === void 0 ? {} : { message }
528
+ });
529
+ });
530
+ Object.defineProperty(descriptor, "action", {
531
+ value: action,
532
+ enumerable: true
533
+ });
534
+ Object.defineProperty(descriptor, "severity", {
535
+ value: severity,
536
+ enumerable: true
537
+ });
538
+ catalog[key] = descriptor;
539
+ }
540
+ return Object.freeze(catalog);
490
541
  }
491
542
 
492
- // src/drain-toolkit.ts
493
- var DEFAULT_TIMEOUT_MS = 5e3;
494
- var DEFAULT_RETRIES = 2;
543
+ //#endregion
544
+ //#region src/drain-toolkit.ts
545
+ const DEFAULT_TIMEOUT_MS = 5e3;
546
+ const DEFAULT_RETRIES = 2;
495
547
  function delay(ms) {
496
- return new Promise((resolve) => {
497
- const t = setTimeout(resolve, ms);
498
- t.unref?.();
499
- });
548
+ return new Promise((resolve) => {
549
+ setTimeout(resolve, ms).unref?.();
550
+ });
500
551
  }
501
552
  async function postWithRetry(options) {
502
- const { name, request: request2, timeoutMs, retries } = options;
503
- const attempts = Math.max(1, retries);
504
- let lastError;
505
- for (let attempt = 1; attempt <= attempts; attempt++) {
506
- const controller = new AbortController();
507
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
508
- timeout.unref?.();
509
- try {
510
- const response = await fetch(request2.url, {
511
- method: "POST",
512
- headers: request2.headers,
513
- body: request2.body,
514
- signal: controller.signal
515
- });
516
- if (!response.ok) {
517
- throw new Error(
518
- `[autotel/${name}] HTTP ${response.status} draining ${request2.url}`
519
- );
520
- }
521
- return;
522
- } catch (error) {
523
- lastError = error;
524
- if (attempt < attempts) {
525
- await delay(100 * attempt);
526
- }
527
- } finally {
528
- clearTimeout(timeout);
529
- }
530
- }
531
- throw lastError;
553
+ const { name, request, timeoutMs, retries } = options;
554
+ const attempts = Math.max(1, retries);
555
+ let lastError;
556
+ for (let attempt = 1; attempt <= attempts; attempt++) {
557
+ const controller = new AbortController();
558
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
559
+ timeout.unref?.();
560
+ try {
561
+ const response = await fetch(request.url, {
562
+ method: "POST",
563
+ headers: request.headers,
564
+ body: request.body,
565
+ signal: controller.signal
566
+ });
567
+ if (!response.ok) throw new Error(`[autotel/${name}] HTTP ${response.status} draining ${request.url}`);
568
+ return;
569
+ } catch (error) {
570
+ lastError = error;
571
+ if (attempt < attempts) await delay(100 * attempt);
572
+ } finally {
573
+ clearTimeout(timeout);
574
+ }
575
+ }
576
+ throw lastError;
532
577
  }
533
578
  function defineDrain(options) {
534
- return async (ctx2) => {
535
- const contexts = Array.isArray(ctx2) ? ctx2 : [ctx2];
536
- if (contexts.length === 0) return;
537
- const config = await options.resolve();
538
- if (!config) return;
539
- const payloads = options.transform ? options.transform(contexts) : contexts;
540
- if (payloads.length === 0) return;
541
- try {
542
- await options.send(payloads, config);
543
- } catch (error) {
544
- console.error(`[autotel/${options.name}] drain failed:`, error);
545
- }
546
- };
579
+ return async (ctx) => {
580
+ const contexts = Array.isArray(ctx) ? ctx : [ctx];
581
+ if (contexts.length === 0) return;
582
+ const config = await options.resolve();
583
+ if (!config) return;
584
+ const payloads = options.transform ? options.transform(contexts) : contexts;
585
+ if (payloads.length === 0) return;
586
+ try {
587
+ await options.send(payloads, config);
588
+ } catch (error) {
589
+ console.error(`[autotel/${options.name}] drain failed:`, error);
590
+ }
591
+ };
547
592
  }
548
593
  function defineHttpDrain(options) {
549
- return defineDrain({
550
- name: options.name,
551
- resolve: options.resolve,
552
- transform: options.transform,
553
- send: async (payloads, config) => {
554
- const request2 = options.encode(payloads, config);
555
- if (!request2) return;
556
- const timeoutMs = options.resolveTimeoutMs?.(config) ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
557
- const retries = options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES;
558
- await postWithRetry({
559
- name: options.name,
560
- request: request2,
561
- timeoutMs,
562
- retries
563
- });
564
- }
565
- });
594
+ return defineDrain({
595
+ name: options.name,
596
+ resolve: options.resolve,
597
+ transform: options.transform,
598
+ send: async (payloads, config) => {
599
+ const request = options.encode(payloads, config);
600
+ if (!request) return;
601
+ const timeoutMs = options.resolveTimeoutMs?.(config) ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
602
+ const retries = options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES;
603
+ await postWithRetry({
604
+ name: options.name,
605
+ request,
606
+ timeoutMs,
607
+ retries
608
+ });
609
+ }
610
+ });
566
611
  }
567
612
 
568
- // src/enricher-toolkit.ts
613
+ //#endregion
614
+ //#region src/enricher-toolkit.ts
569
615
  function isPlainObject(value) {
570
- return value !== null && typeof value === "object" && !Array.isArray(value);
571
- }
572
- function mergeInto2(target, source) {
573
- for (const key in source) {
574
- const sourceVal = source[key];
575
- if (sourceVal === void 0) continue;
576
- const targetVal = target[key];
577
- if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {
578
- mergeInto2(targetVal, sourceVal);
579
- } else {
580
- target[key] = sourceVal;
581
- }
582
- }
616
+ return value !== null && typeof value === "object" && !Array.isArray(value);
617
+ }
618
+ function mergeInto(target, source) {
619
+ for (const key in source) {
620
+ const sourceVal = source[key];
621
+ if (sourceVal === void 0) continue;
622
+ const targetVal = target[key];
623
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal)) mergeInto(targetVal, sourceVal);
624
+ else target[key] = sourceVal;
625
+ }
583
626
  }
584
627
  function defineEnricher(def, options = {}) {
585
- return (ctx2) => {
586
- let computed;
587
- try {
588
- computed = def.compute(ctx2);
589
- } catch (error) {
590
- console.error(`[autotel/${def.name}] enrich failed:`, error);
591
- return;
592
- }
593
- if (!computed) return;
594
- if (options.overwrite || !isPlainObject(ctx2.event[def.field])) {
595
- ctx2.event[def.field] = computed;
596
- return;
597
- }
598
- mergeInto2(
599
- ctx2.event[def.field],
600
- computed
601
- );
602
- };
603
- }
604
- var GEN_AI_DURATION_BUCKETS_SECONDS = Object.freeze(
605
- [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300]
606
- );
607
- var GEN_AI_TOKEN_USAGE_BUCKETS = Object.freeze([
608
- 1,
609
- 4,
610
- 16,
611
- 64,
612
- 256,
613
- 1024,
614
- 4096,
615
- 16384,
616
- 65536,
617
- 262144,
618
- 1048576,
619
- 4194304
628
+ return (ctx) => {
629
+ let computed;
630
+ try {
631
+ computed = def.compute(ctx);
632
+ } catch (error) {
633
+ console.error(`[autotel/${def.name}] enrich failed:`, error);
634
+ return;
635
+ }
636
+ if (!computed) return;
637
+ if (options.overwrite || !isPlainObject(ctx.event[def.field])) {
638
+ ctx.event[def.field] = computed;
639
+ return;
640
+ }
641
+ mergeInto(ctx.event[def.field], computed);
642
+ };
643
+ }
644
+
645
+ //#endregion
646
+ //#region src/gen-ai-metrics.ts
647
+ /**
648
+ * LLM-tuned histogram buckets.
649
+ *
650
+ * Default OpenTelemetry histogram buckets target HTTP latency (0ms–10s)
651
+ * and small counter values. LLM workloads have very different shapes:
652
+ *
653
+ * - **Duration**: single-token prompts can be fast (50ms), long
654
+ * generations and reasoning models can run for minutes. Default buckets
655
+ * crush everything above 10s into one bucket.
656
+ * - **Token usage**: heavily right-skewed. A single request can range
657
+ * from tens of tokens to the million-token context windows.
658
+ * - **Cost (USD)**: per-request values are tiny (fractions of a cent),
659
+ * so linear buckets waste resolution at the low end.
660
+ *
661
+ * This module exposes empirically-chosen bucket arrays and a View helper
662
+ * so users can apply them to their `MeterProvider` without knowing the
663
+ * exact instrument names emitted by OpenAI/Anthropic/Traceloop plugins.
664
+ *
665
+ * @example
666
+ * ```typescript
667
+ * import { NodeSDK } from '@opentelemetry/sdk-node';
668
+ * import { genAiMetricViews } from 'autotel';
669
+ *
670
+ * const sdk = new NodeSDK({
671
+ * serviceName: 'my-agent',
672
+ * views: [...genAiMetricViews()],
673
+ * });
674
+ * sdk.start();
675
+ * ```
676
+ */
677
+ /**
678
+ * Duration buckets for LLM operations, in **seconds**. Covers fast
679
+ * completions (50ms) through long-running reasoning jobs (5 min).
680
+ *
681
+ * Aligns with the OTel GenAI semantic conventions' published advice for
682
+ * `gen_ai.client.operation.duration`.
683
+ */
684
+ const GEN_AI_DURATION_BUCKETS_SECONDS = Object.freeze([
685
+ .01,
686
+ .05,
687
+ .1,
688
+ .25,
689
+ .5,
690
+ 1,
691
+ 2,
692
+ 5,
693
+ 10,
694
+ 20,
695
+ 30,
696
+ 60,
697
+ 120,
698
+ 300
699
+ ]);
700
+ /**
701
+ * Token-count buckets for prompt, completion, and total token histograms.
702
+ * Ranges from tiny prompts to million-token context windows.
703
+ *
704
+ * Aligns with the OTel GenAI semantic conventions' published advice for
705
+ * `gen_ai.client.token.usage`.
706
+ */
707
+ const GEN_AI_TOKEN_USAGE_BUCKETS = Object.freeze([
708
+ 1,
709
+ 4,
710
+ 16,
711
+ 64,
712
+ 256,
713
+ 1024,
714
+ 4096,
715
+ 16384,
716
+ 65536,
717
+ 262144,
718
+ 1048576,
719
+ 4194304
620
720
  ]);
621
- var GEN_AI_COST_USD_BUCKETS = Object.freeze([
622
- 1e-5,
623
- 1e-4,
624
- 1e-3,
625
- 5e-3,
626
- 0.01,
627
- 0.05,
628
- 0.1,
629
- 0.5,
630
- 1,
631
- 5,
632
- 10,
633
- 50
721
+ /**
722
+ * USD cost buckets. Sub-cent resolution at the low end (fractions of a
723
+ * cent per small call) up to tens of dollars (batch jobs, Opus/o1 runs).
724
+ */
725
+ const GEN_AI_COST_USD_BUCKETS = Object.freeze([
726
+ 1e-5,
727
+ 1e-4,
728
+ .001,
729
+ .005,
730
+ .01,
731
+ .05,
732
+ .1,
733
+ .5,
734
+ 1,
735
+ 5,
736
+ 10,
737
+ 50
634
738
  ]);
739
+ /**
740
+ * Instrument-level advice object for `createHistogram(name, advice)`.
741
+ * Use when you control the instrument creation (e.g. custom business
742
+ * LLM metrics); `genAiMetricViews()` is better when the metric comes
743
+ * from a third-party plugin.
744
+ */
635
745
  function llmHistogramAdvice(kind) {
636
- const boundaries = kind === "duration" ? GEN_AI_DURATION_BUCKETS_SECONDS : kind === "tokens" ? GEN_AI_TOKEN_USAGE_BUCKETS : GEN_AI_COST_USD_BUCKETS;
637
- return { advice: { explicitBucketBoundaries: [...boundaries] } };
638
- }
746
+ return { advice: { explicitBucketBoundaries: [...kind === "duration" ? GEN_AI_DURATION_BUCKETS_SECONDS : kind === "tokens" ? GEN_AI_TOKEN_USAGE_BUCKETS : GEN_AI_COST_USD_BUCKETS] } };
747
+ }
748
+ /**
749
+ * Returns `View`s that re-bucket the standard OTel GenAI histograms. Pass
750
+ * the result to your `MeterProvider`'s `views` option.
751
+ *
752
+ * Matches instrument names emitted by:
753
+ * - OpenTelemetry GenAI autoinstrumentation
754
+ * - OpenInference / OpenLLMetry (traceloop)
755
+ * - Arize Phoenix, LangSmith, etc. that follow the OTel spec
756
+ *
757
+ * Add more instrument patterns via the `extra` argument if you emit
758
+ * custom LLM metrics.
759
+ */
639
760
  function genAiMetricViews(extra = []) {
640
- const defaults = [
641
- { instrumentName: "gen_ai.client.operation.duration", kind: "duration" },
642
- { instrumentName: "gen_ai.client.token.usage", kind: "tokens" },
643
- // Autotel-emitted cost metric. No-op if you don't emit it.
644
- { instrumentName: "gen_ai.client.cost.usd", kind: "cost" }
645
- ];
646
- return [...defaults, ...extra].map(
647
- ({ instrumentName, kind }) => ({
648
- instrumentName,
649
- aggregation: {
650
- type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
651
- options: {
652
- boundaries: kind === "duration" ? [...GEN_AI_DURATION_BUCKETS_SECONDS] : kind === "tokens" ? [...GEN_AI_TOKEN_USAGE_BUCKETS] : [...GEN_AI_COST_USD_BUCKETS]
653
- }
654
- }
655
- })
656
- );
761
+ return [...[
762
+ {
763
+ instrumentName: "gen_ai.client.operation.duration",
764
+ kind: "duration"
765
+ },
766
+ {
767
+ instrumentName: "gen_ai.client.token.usage",
768
+ kind: "tokens"
769
+ },
770
+ {
771
+ instrumentName: "gen_ai.client.cost.usd",
772
+ kind: "cost"
773
+ }
774
+ ], ...extra].map(({ instrumentName, kind }) => ({
775
+ instrumentName,
776
+ aggregation: {
777
+ type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
778
+ options: { boundaries: kind === "duration" ? [...GEN_AI_DURATION_BUCKETS_SECONDS] : kind === "tokens" ? [...GEN_AI_TOKEN_USAGE_BUCKETS] : [...GEN_AI_COST_USD_BUCKETS] }
779
+ }
780
+ }));
657
781
  }
658
782
 
659
- // src/gen-ai-events.ts
660
- function recordPromptSent(ctx2, event = {}) {
661
- emitCorrelatedEvent(ctx2, "gen_ai.prompt.sent", buildPromptSentAttrs(event));
662
- }
663
- function recordResponseReceived(ctx2, event = {}) {
664
- emitCorrelatedEvent(
665
- ctx2,
666
- "gen_ai.response.received",
667
- buildResponseAttrs(event)
668
- );
669
- }
670
- function recordRetry(ctx2, event) {
671
- emitCorrelatedEvent(ctx2, "gen_ai.retry", buildRetryAttrs(event));
672
- }
673
- function recordToolCall(ctx2, event) {
674
- emitCorrelatedEvent(ctx2, "gen_ai.tool.call", buildToolCallAttrs(event));
675
- }
676
- function recordStreamFirstToken(ctx2, event = {}) {
677
- emitCorrelatedEvent(
678
- ctx2,
679
- "gen_ai.stream.first_token",
680
- buildStreamFirstTokenAttrs(event)
681
- );
783
+ //#endregion
784
+ //#region src/gen-ai-events.ts
785
+ /**
786
+ * Record that a prompt was dispatched to the provider. Typically called
787
+ * before `await provider.chat.completions.create(...)`.
788
+ */
789
+ function recordPromptSent(ctx, event = {}) {
790
+ emitCorrelatedEvent(ctx, "gen_ai.prompt.sent", buildPromptSentAttrs(event));
791
+ }
792
+ /**
793
+ * Record a successful provider response. Call after the response arrives
794
+ * (for non-streaming) or after the stream completes.
795
+ */
796
+ function recordResponseReceived(ctx, event = {}) {
797
+ emitCorrelatedEvent(ctx, "gen_ai.response.received", buildResponseAttrs(event));
798
+ }
799
+ /**
800
+ * Record a retry attempt on an LLM call. Call *before* sleeping for
801
+ * `delayMs` so the event timestamp accurately marks when the retry
802
+ * decision was made.
803
+ */
804
+ function recordRetry(ctx, event) {
805
+ emitCorrelatedEvent(ctx, "gen_ai.retry", buildRetryAttrs(event));
806
+ }
807
+ /**
808
+ * Record a tool / function call made in the course of an agent step.
809
+ * Emits an event rather than a child span because many frameworks fire
810
+ * several tool calls within a single provider response.
811
+ */
812
+ function recordToolCall(ctx, event) {
813
+ emitCorrelatedEvent(ctx, "gen_ai.tool.call", buildToolCallAttrs(event));
814
+ }
815
+ /**
816
+ * Record the time-to-first-token for a streaming response. Pair with
817
+ * `recordResponseReceived` at the end so the span carries both the TTFT
818
+ * marker and the final usage numbers.
819
+ */
820
+ function recordStreamFirstToken(ctx, event = {}) {
821
+ emitCorrelatedEvent(ctx, "gen_ai.stream.first_token", buildStreamFirstTokenAttrs(event));
682
822
  }
683
823
  function buildPromptSentAttrs(event) {
684
- const attrs2 = {};
685
- if (event.model) attrs2["gen_ai.request.model"] = event.model;
686
- if (event.promptTokens !== void 0)
687
- attrs2["gen_ai.usage.input_tokens"] = event.promptTokens;
688
- if (event.messageCount !== void 0)
689
- attrs2["gen_ai.request.message_count"] = event.messageCount;
690
- if (event.operation) attrs2["gen_ai.operation.name"] = event.operation;
691
- return attrs2;
824
+ const attrs = {};
825
+ if (event.model) attrs["gen_ai.request.model"] = event.model;
826
+ if (event.promptTokens !== void 0) attrs["gen_ai.usage.input_tokens"] = event.promptTokens;
827
+ if (event.messageCount !== void 0) attrs["gen_ai.request.message_count"] = event.messageCount;
828
+ if (event.operation) attrs["gen_ai.operation.name"] = event.operation;
829
+ return attrs;
692
830
  }
693
831
  function buildResponseAttrs(event) {
694
- const attrs2 = {};
695
- if (event.model) attrs2["gen_ai.response.model"] = event.model;
696
- if (event.promptTokens !== void 0)
697
- attrs2["gen_ai.usage.input_tokens"] = event.promptTokens;
698
- if (event.completionTokens !== void 0)
699
- attrs2["gen_ai.usage.output_tokens"] = event.completionTokens;
700
- if (event.totalTokens !== void 0)
701
- attrs2["gen_ai.usage.total_tokens"] = event.totalTokens;
702
- if (event.finishReasons && event.finishReasons.length > 0) {
703
- attrs2["gen_ai.response.finish_reasons"] = event.finishReasons.join(",");
704
- }
705
- return attrs2;
832
+ const attrs = {};
833
+ if (event.model) attrs["gen_ai.response.model"] = event.model;
834
+ if (event.promptTokens !== void 0) attrs["gen_ai.usage.input_tokens"] = event.promptTokens;
835
+ if (event.completionTokens !== void 0) attrs["gen_ai.usage.output_tokens"] = event.completionTokens;
836
+ if (event.totalTokens !== void 0) attrs["gen_ai.usage.total_tokens"] = event.totalTokens;
837
+ if (event.finishReasons && event.finishReasons.length > 0) attrs["gen_ai.response.finish_reasons"] = event.finishReasons.join(",");
838
+ return attrs;
706
839
  }
707
840
  function buildRetryAttrs(event) {
708
- const attrs2 = { "retry.attempt": event.attempt };
709
- if (event.reason) attrs2["retry.reason"] = event.reason;
710
- if (event.delayMs !== void 0) attrs2["retry.delay_ms"] = event.delayMs;
711
- if (event.statusCode !== void 0)
712
- attrs2["http.response.status_code"] = event.statusCode;
713
- return attrs2;
841
+ const attrs = { "retry.attempt": event.attempt };
842
+ if (event.reason) attrs["retry.reason"] = event.reason;
843
+ if (event.delayMs !== void 0) attrs["retry.delay_ms"] = event.delayMs;
844
+ if (event.statusCode !== void 0) attrs["http.response.status_code"] = event.statusCode;
845
+ return attrs;
714
846
  }
715
847
  function buildToolCallAttrs(event) {
716
- const attrs2 = { "gen_ai.tool.name": event.toolName };
717
- if (event.toolCallId) attrs2["gen_ai.tool.call.id"] = event.toolCallId;
718
- if (event.arguments) attrs2["gen_ai.tool.arguments"] = event.arguments;
719
- return attrs2;
848
+ const attrs = { "gen_ai.tool.name": event.toolName };
849
+ if (event.toolCallId) attrs["gen_ai.tool.call.id"] = event.toolCallId;
850
+ if (event.arguments) attrs["gen_ai.tool.arguments"] = event.arguments;
851
+ return attrs;
720
852
  }
721
853
  function buildStreamFirstTokenAttrs(event) {
722
- const attrs2 = {};
723
- if (event.tokensSoFar !== void 0)
724
- attrs2["gen_ai.stream.tokens_so_far"] = event.tokensSoFar;
725
- return attrs2;
854
+ const attrs = {};
855
+ if (event.tokensSoFar !== void 0) attrs["gen_ai.stream.tokens_so_far"] = event.tokensSoFar;
856
+ return attrs;
726
857
  }
727
858
 
728
- // src/gen-ai-cost.ts
729
- var GEN_AI_COST_ATTRIBUTE = "gen_ai.usage.cost.usd";
730
- var MODEL_PRICING = {
731
- // OpenAI
732
- "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10 },
733
- "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6 },
734
- "gpt-4.1": { inputPer1M: 2, outputPer1M: 8 },
735
- "gpt-4.1-mini": { inputPer1M: 0.4, outputPer1M: 1.6 },
736
- "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4 },
737
- "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4 },
738
- // Anthropic Claude
739
- "claude-opus-4": { inputPer1M: 15, outputPer1M: 75 },
740
- "claude-sonnet-4": { inputPer1M: 3, outputPer1M: 15 },
741
- "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15 },
742
- "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4 },
743
- "claude-3-opus": { inputPer1M: 15, outputPer1M: 75 },
744
- "claude-3-haiku": { inputPer1M: 0.25, outputPer1M: 1.25 },
745
- // Google Gemini
746
- "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5 },
747
- "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3 },
748
- "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4 }
859
+ //#endregion
860
+ //#region src/gen-ai-cost.ts
861
+ /** Span attribute key autotel sets for an estimated call cost. */
862
+ const GEN_AI_COST_ATTRIBUTE = "gen_ai.usage.cost.usd";
863
+ /**
864
+ * Approximate public list prices (USD per 1M tokens) at the time of writing.
865
+ * Prices change; treat these as convenience defaults, not a billing source of
866
+ * truth. Override per call via `options.pricing` or mutate this table at init.
867
+ * Matching is exact first, then by longest key prefix, so versioned model ids
868
+ * (`claude-sonnet-4-6-20251101`) resolve to a base entry (`claude-sonnet-4-6`).
869
+ */
870
+ const MODEL_PRICING = {
871
+ "gpt-4o": {
872
+ inputPer1M: 2.5,
873
+ outputPer1M: 10
874
+ },
875
+ "gpt-4o-mini": {
876
+ inputPer1M: .15,
877
+ outputPer1M: .6
878
+ },
879
+ "gpt-4.1": {
880
+ inputPer1M: 2,
881
+ outputPer1M: 8
882
+ },
883
+ "gpt-4.1-mini": {
884
+ inputPer1M: .4,
885
+ outputPer1M: 1.6
886
+ },
887
+ "gpt-4.1-nano": {
888
+ inputPer1M: .1,
889
+ outputPer1M: .4
890
+ },
891
+ "o3-mini": {
892
+ inputPer1M: 1.1,
893
+ outputPer1M: 4.4
894
+ },
895
+ "claude-opus-4": {
896
+ inputPer1M: 15,
897
+ outputPer1M: 75
898
+ },
899
+ "claude-sonnet-4": {
900
+ inputPer1M: 3,
901
+ outputPer1M: 15
902
+ },
903
+ "claude-3-5-sonnet": {
904
+ inputPer1M: 3,
905
+ outputPer1M: 15
906
+ },
907
+ "claude-3-5-haiku": {
908
+ inputPer1M: .8,
909
+ outputPer1M: 4
910
+ },
911
+ "claude-3-opus": {
912
+ inputPer1M: 15,
913
+ outputPer1M: 75
914
+ },
915
+ "claude-3-haiku": {
916
+ inputPer1M: .25,
917
+ outputPer1M: 1.25
918
+ },
919
+ "gemini-1.5-pro": {
920
+ inputPer1M: 1.25,
921
+ outputPer1M: 5
922
+ },
923
+ "gemini-1.5-flash": {
924
+ inputPer1M: .075,
925
+ outputPer1M: .3
926
+ },
927
+ "gemini-2.0-flash": {
928
+ inputPer1M: .1,
929
+ outputPer1M: .4
930
+ }
749
931
  };
750
932
  function resolvePricing(table, model) {
751
- const exact = table[model];
752
- if (exact) return exact;
753
- let best;
754
- let bestLength = 0;
755
- for (const key of Object.keys(table)) {
756
- if (model.startsWith(key) && key.length > bestLength) {
757
- best = table[key];
758
- bestLength = key.length;
759
- }
760
- }
761
- return best;
933
+ const exact = table[model];
934
+ if (exact) return exact;
935
+ let best;
936
+ let bestLength = 0;
937
+ for (const key of Object.keys(table)) if (model.startsWith(key) && key.length > bestLength) {
938
+ best = table[key];
939
+ bestLength = key.length;
940
+ }
941
+ return best;
762
942
  }
763
943
  function round(value) {
764
- return Math.round(value * 1e6) / 1e6;
944
+ return Math.round(value * 1e6) / 1e6;
765
945
  }
946
+ /**
947
+ * Estimate the USD cost of an LLM call. Returns `undefined` when the model has
948
+ * no known pricing (supply one via `options.pricing`).
949
+ */
766
950
  function estimateLLMCost(model, usage, options) {
767
- const table = options?.pricing ? { ...MODEL_PRICING, ...options.pricing } : MODEL_PRICING;
768
- const price = resolvePricing(table, model);
769
- if (!price) return void 0;
770
- const cachedInput = usage.cachedInputTokens ?? 0;
771
- const billedInput = Math.max(0, (usage.inputTokens ?? 0) - cachedInput);
772
- const output = usage.outputTokens ?? 0;
773
- const cachedRate = price.cachedInputPer1M ?? price.inputPer1M;
774
- const cost = billedInput / 1e6 * price.inputPer1M + cachedInput / 1e6 * cachedRate + output / 1e6 * price.outputPer1M;
775
- return round(cost);
776
- }
777
- function recordLLMCost(ctx2, model, usage, options) {
778
- const cost = estimateLLMCost(model, usage, options);
779
- if (cost !== void 0) {
780
- ctx2.setAttribute(GEN_AI_COST_ATTRIBUTE, cost);
781
- }
782
- return cost;
951
+ const price = resolvePricing(options?.pricing ? {
952
+ ...MODEL_PRICING,
953
+ ...options.pricing
954
+ } : MODEL_PRICING, model);
955
+ if (!price) return void 0;
956
+ const cachedInput = usage.cachedInputTokens ?? 0;
957
+ const billedInput = Math.max(0, (usage.inputTokens ?? 0) - cachedInput);
958
+ const output = usage.outputTokens ?? 0;
959
+ const cachedRate = price.cachedInputPer1M ?? price.inputPer1M;
960
+ return round(billedInput / 1e6 * price.inputPer1M + cachedInput / 1e6 * cachedRate + output / 1e6 * price.outputPer1M);
961
+ }
962
+ /**
963
+ * Estimate cost and record it on `ctx` as the `gen_ai.usage.cost.usd` span
964
+ * attribute. Returns the estimated cost, or `undefined` when the model is
965
+ * unknown (in which case no attribute is set).
966
+ */
967
+ function recordLLMCost(ctx, model, usage, options) {
968
+ const cost = estimateLLMCost(model, usage, options);
969
+ if (cost !== void 0) ctx.setAttribute(GEN_AI_COST_ATTRIBUTE, cost);
970
+ return cost;
783
971
  }
784
972
 
785
- export { GEN_AI_COST_ATTRIBUTE, GEN_AI_COST_USD_BUCKETS, GEN_AI_DURATION_BUCKETS_SECONDS, GEN_AI_TOKEN_USAGE_BUCKETS, MODEL_PRICING, defineAuditCatalog, defineDrain, defineEnricher, defineErrorCatalog, defineEvent, defineHttpDrain, estimateLLMCost, flush, genAiMetricViews, getCatalogCode, getRequestLogger, isCatalogError, llmHistogramAdvice, recordLLMCost, recordPromptSent, recordResponseReceived, recordRetry, recordStreamFirstToken, recordToolCall, runWithRequestContext, shutdown, trace2 as trace };
786
- //# sourceMappingURL=index.js.map
973
+ //#endregion
974
+ export { AUTOTEL_SAMPLING_TAIL_EVALUATED, AUTOTEL_SAMPLING_TAIL_KEEP, AdaptiveSampler, AlwaysSampler, AttributeRedactingProcessor, BaggageSpanProcessor, BusinessBaggage, CORRELATION_ID_BAGGAGE_KEY, Event, FilteringSpanProcessor, GEN_AI_COST_ATTRIBUTE, GEN_AI_COST_USD_BUCKETS, GEN_AI_DURATION_BUCKETS_SECONDS, GEN_AI_TOKEN_USAGE_BUCKETS, HTTPAttributes, MODEL_PRICING, Metric, NORMALIZER_PATTERNS, NORMALIZER_PRESETS, NeverSampler, REDACTOR_PATTERNS, REDACTOR_PRESETS, ROOT_CONTEXT, RandomSampler, ServiceAttributes, SpanKind, SpanNameNormalizingProcessor, SpanStatusCode, URLAttributes, UserIdSampler, attrs, autoRedactPII, builtinPatterns, context, createAttributeRedactor, createCounter, createDeterministicTraceId, createDrainPipeline, createHistogram, createLinkFromHeaders, createNoopRequestLogger, createObservableGauge, createRedactedSpan, createSafeBaggageSchema, createStringRedactor, createStructuredError, createUpDownCounter, ctx, dbClient, defineAuditCatalog, defineBaggageSchema, defineDrain, defineEnricher, defineErrorCatalog, defineEvent, defineHttpDrain, enrichWithTraceContext, estimateLLMCost, extractLinksFromBatch, finalizeSpan, flattenMetadata, flattenToAttributes, flush, formatDuration, genAiMetricViews, generateCorrelationId, getActiveContext, getActiveSpan, getAutotelTracer, getAutotelTracerProvider, getCatalogCode, getCorrelationId, getCurrentWorkflowContext, getEventQueue, getEvents, getMeter, getMetrics, getOperationContext, getOrCreateCorrelationId, getRequestLogger, getRequestLoggerSafe, getStructuredErrorAttributes, getTraceContext, getTracer, hasRequestContext, httpClient, httpRequestHeaderAttribute, httpResponseHeaderAttribute, httpServer, identify, init, instrument, isCatalogError, isInWorkflow, isInitialized, isLoggerLocked, isTracing, llmHistogramAdvice, lockLogger, markAsImmediate, mergeAttrs, mergeServiceResource, normalizeAttributeRedactorConfig, otelTrace, parseError, propagation, recordLLMCost, recordPromptSent, recordResponseReceived, recordRetry, recordStreamFirstToken, recordStructuredError, recordToolCall, request, resetEvents, resetMetrics, resolveSamplingPreset, resolveTraceUrl, runInOperationContext, runWithCorrelationId, runWithRequestContext, runWithSpan, safeSetAttributes, samplingPresets, setAutotelTracerProvider, setCorrelationId, setCorrelationIdInBaggage, setDevice, setError, setException, setSession, setUser, shutdown, span, structuredErrorToJSON, toAttributeValue, trace, traceConsumer, traceDB, traceHTTP, traceLLM, traceMessaging, traceProducer, traceStep, traceWorkflow, track, validateAttribute, withBaggage, withNewContext, withTracing };
787
975
  //# sourceMappingURL=index.js.map