autotel 2.1.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 (272) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1946 -0
  3. package/dist/chunk-2LNRY4QK.js +273 -0
  4. package/dist/chunk-2LNRY4QK.js.map +1 -0
  5. package/dist/chunk-3HENGDW2.js +587 -0
  6. package/dist/chunk-3HENGDW2.js.map +1 -0
  7. package/dist/chunk-4OAT42CA.cjs +73 -0
  8. package/dist/chunk-4OAT42CA.cjs.map +1 -0
  9. package/dist/chunk-5GWX5LFW.js +70 -0
  10. package/dist/chunk-5GWX5LFW.js.map +1 -0
  11. package/dist/chunk-5R2M36QB.js +195 -0
  12. package/dist/chunk-5R2M36QB.js.map +1 -0
  13. package/dist/chunk-5ZN622AO.js +73 -0
  14. package/dist/chunk-5ZN622AO.js.map +1 -0
  15. package/dist/chunk-77MSMAUQ.cjs +498 -0
  16. package/dist/chunk-77MSMAUQ.cjs.map +1 -0
  17. package/dist/chunk-ABPEQ6RK.cjs +596 -0
  18. package/dist/chunk-ABPEQ6RK.cjs.map +1 -0
  19. package/dist/chunk-BWYGJKRB.js +95 -0
  20. package/dist/chunk-BWYGJKRB.js.map +1 -0
  21. package/dist/chunk-BZHG5IZ4.js +73 -0
  22. package/dist/chunk-BZHG5IZ4.js.map +1 -0
  23. package/dist/chunk-G7VZBCD6.cjs +35 -0
  24. package/dist/chunk-G7VZBCD6.cjs.map +1 -0
  25. package/dist/chunk-GVLK7YUU.cjs +30 -0
  26. package/dist/chunk-GVLK7YUU.cjs.map +1 -0
  27. package/dist/chunk-HCCXC7XG.js +205 -0
  28. package/dist/chunk-HCCXC7XG.js.map +1 -0
  29. package/dist/chunk-HE6T6FIX.cjs +203 -0
  30. package/dist/chunk-HE6T6FIX.cjs.map +1 -0
  31. package/dist/chunk-KIXWPOCO.cjs +100 -0
  32. package/dist/chunk-KIXWPOCO.cjs.map +1 -0
  33. package/dist/chunk-KVGNW3FC.js +87 -0
  34. package/dist/chunk-KVGNW3FC.js.map +1 -0
  35. package/dist/chunk-LITNXTTT.js +3 -0
  36. package/dist/chunk-LITNXTTT.js.map +1 -0
  37. package/dist/chunk-M4ANN7RL.js +114 -0
  38. package/dist/chunk-M4ANN7RL.js.map +1 -0
  39. package/dist/chunk-NC52UBR2.cjs +32 -0
  40. package/dist/chunk-NC52UBR2.cjs.map +1 -0
  41. package/dist/chunk-NHCNRQD3.cjs +212 -0
  42. package/dist/chunk-NHCNRQD3.cjs.map +1 -0
  43. package/dist/chunk-NZ72VDNY.cjs +4 -0
  44. package/dist/chunk-NZ72VDNY.cjs.map +1 -0
  45. package/dist/chunk-P6JUDYNO.js +57 -0
  46. package/dist/chunk-P6JUDYNO.js.map +1 -0
  47. package/dist/chunk-RJYY7BWX.js +1349 -0
  48. package/dist/chunk-RJYY7BWX.js.map +1 -0
  49. package/dist/chunk-TRI4V5BF.cjs +126 -0
  50. package/dist/chunk-TRI4V5BF.cjs.map +1 -0
  51. package/dist/chunk-UL33I6IS.js +139 -0
  52. package/dist/chunk-UL33I6IS.js.map +1 -0
  53. package/dist/chunk-URRW6M2C.cjs +61 -0
  54. package/dist/chunk-URRW6M2C.cjs.map +1 -0
  55. package/dist/chunk-UY3UYPBZ.cjs +77 -0
  56. package/dist/chunk-UY3UYPBZ.cjs.map +1 -0
  57. package/dist/chunk-W3253FGB.cjs +277 -0
  58. package/dist/chunk-W3253FGB.cjs.map +1 -0
  59. package/dist/chunk-W7LHZVQF.js +26 -0
  60. package/dist/chunk-W7LHZVQF.js.map +1 -0
  61. package/dist/chunk-WBWNM6LB.cjs +1360 -0
  62. package/dist/chunk-WBWNM6LB.cjs.map +1 -0
  63. package/dist/chunk-WFJ7L2RV.js +494 -0
  64. package/dist/chunk-WFJ7L2RV.js.map +1 -0
  65. package/dist/chunk-X4RMFFMR.js +28 -0
  66. package/dist/chunk-X4RMFFMR.js.map +1 -0
  67. package/dist/chunk-Y4Y2S7BM.cjs +92 -0
  68. package/dist/chunk-Y4Y2S7BM.cjs.map +1 -0
  69. package/dist/chunk-YLPNXZFI.cjs +143 -0
  70. package/dist/chunk-YLPNXZFI.cjs.map +1 -0
  71. package/dist/chunk-YTXEZ4SD.cjs +77 -0
  72. package/dist/chunk-YTXEZ4SD.cjs.map +1 -0
  73. package/dist/chunk-Z6ZWNWWR.js +30 -0
  74. package/dist/chunk-Z6ZWNWWR.js.map +1 -0
  75. package/dist/config.cjs +26 -0
  76. package/dist/config.cjs.map +1 -0
  77. package/dist/config.d.cts +75 -0
  78. package/dist/config.d.ts +75 -0
  79. package/dist/config.js +5 -0
  80. package/dist/config.js.map +1 -0
  81. package/dist/db.cjs +233 -0
  82. package/dist/db.cjs.map +1 -0
  83. package/dist/db.d.cts +123 -0
  84. package/dist/db.d.ts +123 -0
  85. package/dist/db.js +228 -0
  86. package/dist/db.js.map +1 -0
  87. package/dist/decorators.cjs +67 -0
  88. package/dist/decorators.cjs.map +1 -0
  89. package/dist/decorators.d.cts +91 -0
  90. package/dist/decorators.d.ts +91 -0
  91. package/dist/decorators.js +65 -0
  92. package/dist/decorators.js.map +1 -0
  93. package/dist/event-subscriber.cjs +6 -0
  94. package/dist/event-subscriber.cjs.map +1 -0
  95. package/dist/event-subscriber.d.cts +116 -0
  96. package/dist/event-subscriber.d.ts +116 -0
  97. package/dist/event-subscriber.js +3 -0
  98. package/dist/event-subscriber.js.map +1 -0
  99. package/dist/event-testing.cjs +21 -0
  100. package/dist/event-testing.cjs.map +1 -0
  101. package/dist/event-testing.d.cts +110 -0
  102. package/dist/event-testing.d.ts +110 -0
  103. package/dist/event-testing.js +4 -0
  104. package/dist/event-testing.js.map +1 -0
  105. package/dist/event.cjs +30 -0
  106. package/dist/event.cjs.map +1 -0
  107. package/dist/event.d.cts +282 -0
  108. package/dist/event.d.ts +282 -0
  109. package/dist/event.js +13 -0
  110. package/dist/event.js.map +1 -0
  111. package/dist/exporters.cjs +17 -0
  112. package/dist/exporters.cjs.map +1 -0
  113. package/dist/exporters.d.cts +1 -0
  114. package/dist/exporters.d.ts +1 -0
  115. package/dist/exporters.js +4 -0
  116. package/dist/exporters.js.map +1 -0
  117. package/dist/functional.cjs +46 -0
  118. package/dist/functional.cjs.map +1 -0
  119. package/dist/functional.d.cts +478 -0
  120. package/dist/functional.d.ts +478 -0
  121. package/dist/functional.js +13 -0
  122. package/dist/functional.js.map +1 -0
  123. package/dist/http.cjs +189 -0
  124. package/dist/http.cjs.map +1 -0
  125. package/dist/http.d.cts +169 -0
  126. package/dist/http.d.ts +169 -0
  127. package/dist/http.js +184 -0
  128. package/dist/http.js.map +1 -0
  129. package/dist/index.cjs +333 -0
  130. package/dist/index.cjs.map +1 -0
  131. package/dist/index.d.cts +758 -0
  132. package/dist/index.d.ts +758 -0
  133. package/dist/index.js +143 -0
  134. package/dist/index.js.map +1 -0
  135. package/dist/instrumentation.cjs +182 -0
  136. package/dist/instrumentation.cjs.map +1 -0
  137. package/dist/instrumentation.d.cts +49 -0
  138. package/dist/instrumentation.d.ts +49 -0
  139. package/dist/instrumentation.js +179 -0
  140. package/dist/instrumentation.js.map +1 -0
  141. package/dist/logger.cjs +19 -0
  142. package/dist/logger.cjs.map +1 -0
  143. package/dist/logger.d.cts +146 -0
  144. package/dist/logger.d.ts +146 -0
  145. package/dist/logger.js +6 -0
  146. package/dist/logger.js.map +1 -0
  147. package/dist/metric-helpers.cjs +31 -0
  148. package/dist/metric-helpers.cjs.map +1 -0
  149. package/dist/metric-helpers.d.cts +13 -0
  150. package/dist/metric-helpers.d.ts +13 -0
  151. package/dist/metric-helpers.js +6 -0
  152. package/dist/metric-helpers.js.map +1 -0
  153. package/dist/metric-testing.cjs +21 -0
  154. package/dist/metric-testing.cjs.map +1 -0
  155. package/dist/metric-testing.d.cts +110 -0
  156. package/dist/metric-testing.d.ts +110 -0
  157. package/dist/metric-testing.js +4 -0
  158. package/dist/metric-testing.js.map +1 -0
  159. package/dist/metric.cjs +26 -0
  160. package/dist/metric.cjs.map +1 -0
  161. package/dist/metric.d.cts +240 -0
  162. package/dist/metric.d.ts +240 -0
  163. package/dist/metric.js +9 -0
  164. package/dist/metric.js.map +1 -0
  165. package/dist/processors.cjs +17 -0
  166. package/dist/processors.cjs.map +1 -0
  167. package/dist/processors.d.cts +1 -0
  168. package/dist/processors.d.ts +1 -0
  169. package/dist/processors.js +4 -0
  170. package/dist/processors.js.map +1 -0
  171. package/dist/sampling.cjs +40 -0
  172. package/dist/sampling.cjs.map +1 -0
  173. package/dist/sampling.d.cts +260 -0
  174. package/dist/sampling.d.ts +260 -0
  175. package/dist/sampling.js +7 -0
  176. package/dist/sampling.js.map +1 -0
  177. package/dist/semantic-helpers.cjs +35 -0
  178. package/dist/semantic-helpers.cjs.map +1 -0
  179. package/dist/semantic-helpers.d.cts +442 -0
  180. package/dist/semantic-helpers.d.ts +442 -0
  181. package/dist/semantic-helpers.js +14 -0
  182. package/dist/semantic-helpers.js.map +1 -0
  183. package/dist/tail-sampling-processor.cjs +13 -0
  184. package/dist/tail-sampling-processor.cjs.map +1 -0
  185. package/dist/tail-sampling-processor.d.cts +27 -0
  186. package/dist/tail-sampling-processor.d.ts +27 -0
  187. package/dist/tail-sampling-processor.js +4 -0
  188. package/dist/tail-sampling-processor.js.map +1 -0
  189. package/dist/testing.cjs +286 -0
  190. package/dist/testing.cjs.map +1 -0
  191. package/dist/testing.d.cts +291 -0
  192. package/dist/testing.d.ts +291 -0
  193. package/dist/testing.js +263 -0
  194. package/dist/testing.js.map +1 -0
  195. package/dist/trace-context-DRZdUvVY.d.cts +181 -0
  196. package/dist/trace-context-DRZdUvVY.d.ts +181 -0
  197. package/dist/trace-helpers.cjs +54 -0
  198. package/dist/trace-helpers.cjs.map +1 -0
  199. package/dist/trace-helpers.d.cts +524 -0
  200. package/dist/trace-helpers.d.ts +524 -0
  201. package/dist/trace-helpers.js +5 -0
  202. package/dist/trace-helpers.js.map +1 -0
  203. package/dist/tracer-provider.cjs +21 -0
  204. package/dist/tracer-provider.cjs.map +1 -0
  205. package/dist/tracer-provider.d.cts +169 -0
  206. package/dist/tracer-provider.d.ts +169 -0
  207. package/dist/tracer-provider.js +4 -0
  208. package/dist/tracer-provider.js.map +1 -0
  209. package/package.json +280 -0
  210. package/src/baggage-span-processor.test.ts +202 -0
  211. package/src/baggage-span-processor.ts +98 -0
  212. package/src/circuit-breaker.test.ts +341 -0
  213. package/src/circuit-breaker.ts +184 -0
  214. package/src/config.test.ts +94 -0
  215. package/src/config.ts +169 -0
  216. package/src/db.test.ts +252 -0
  217. package/src/db.ts +447 -0
  218. package/src/decorators.test.ts +203 -0
  219. package/src/decorators.ts +188 -0
  220. package/src/env-config.test.ts +246 -0
  221. package/src/env-config.ts +158 -0
  222. package/src/event-queue.test.ts +222 -0
  223. package/src/event-queue.ts +203 -0
  224. package/src/event-subscriber.ts +136 -0
  225. package/src/event-testing.ts +197 -0
  226. package/src/event.test.ts +718 -0
  227. package/src/event.ts +556 -0
  228. package/src/exporters.ts +96 -0
  229. package/src/functional.test.ts +1059 -0
  230. package/src/functional.ts +2295 -0
  231. package/src/http.test.ts +487 -0
  232. package/src/http.ts +424 -0
  233. package/src/index.ts +158 -0
  234. package/src/init.customization.test.ts +210 -0
  235. package/src/init.integrations.test.ts +366 -0
  236. package/src/init.openllmetry.test.ts +282 -0
  237. package/src/init.protocol.test.ts +215 -0
  238. package/src/init.ts +1426 -0
  239. package/src/instrumentation.test.ts +108 -0
  240. package/src/instrumentation.ts +308 -0
  241. package/src/logger.test.ts +117 -0
  242. package/src/logger.ts +246 -0
  243. package/src/metric-helpers.ts +47 -0
  244. package/src/metric-testing.ts +197 -0
  245. package/src/metric.ts +434 -0
  246. package/src/metrics.test.ts +205 -0
  247. package/src/operation-context.ts +93 -0
  248. package/src/processors.ts +106 -0
  249. package/src/rate-limiter.test.ts +199 -0
  250. package/src/rate-limiter.ts +98 -0
  251. package/src/sampling.test.ts +513 -0
  252. package/src/sampling.ts +428 -0
  253. package/src/semantic-helpers.test.ts +311 -0
  254. package/src/semantic-helpers.ts +584 -0
  255. package/src/shutdown.test.ts +311 -0
  256. package/src/shutdown.ts +222 -0
  257. package/src/stub.integration.test.ts +361 -0
  258. package/src/tail-sampling-processor.test.ts +226 -0
  259. package/src/tail-sampling-processor.ts +51 -0
  260. package/src/testing.ts +670 -0
  261. package/src/trace-context.ts +470 -0
  262. package/src/trace-helpers.new.test.ts +278 -0
  263. package/src/trace-helpers.test.ts +242 -0
  264. package/src/trace-helpers.ts +690 -0
  265. package/src/tracer-provider.test.ts +183 -0
  266. package/src/tracer-provider.ts +266 -0
  267. package/src/track.test.ts +153 -0
  268. package/src/track.ts +120 -0
  269. package/src/validation.test.ts +306 -0
  270. package/src/validation.ts +239 -0
  271. package/src/variable-name-inference.test.ts +178 -0
  272. package/src/variable-name-inference.ts +242 -0
@@ -0,0 +1,1360 @@
1
+ 'use strict';
2
+
3
+ var chunkTRI4V5BF_cjs = require('./chunk-TRI4V5BF.cjs');
4
+ var chunkNHCNRQD3_cjs = require('./chunk-NHCNRQD3.cjs');
5
+ var chunkYLPNXZFI_cjs = require('./chunk-YLPNXZFI.cjs');
6
+ var chunkABPEQ6RK_cjs = require('./chunk-ABPEQ6RK.cjs');
7
+ var chunkHE6T6FIX_cjs = require('./chunk-HE6T6FIX.cjs');
8
+ var chunkY4Y2S7BM_cjs = require('./chunk-Y4Y2S7BM.cjs');
9
+ var api = require('@opentelemetry/api');
10
+ var fs = require('fs');
11
+ var url = require('url');
12
+
13
+ // src/rate-limiter.ts
14
+ var TokenBucketRateLimiter = class {
15
+ tokens;
16
+ maxTokens;
17
+ refillRate;
18
+ // tokens per millisecond
19
+ lastRefill;
20
+ constructor(config) {
21
+ this.maxTokens = config.burstCapacity || config.maxEventsPerSecond * 2;
22
+ this.tokens = this.maxTokens;
23
+ this.refillRate = config.maxEventsPerSecond / 1e3;
24
+ this.lastRefill = Date.now();
25
+ }
26
+ /**
27
+ * Try to consume a token (allow an event)
28
+ * Returns true if allowed, false if rate limit exceeded
29
+ */
30
+ tryConsume(count = 1) {
31
+ this.refill();
32
+ if (this.tokens >= count) {
33
+ this.tokens -= count;
34
+ return true;
35
+ }
36
+ return false;
37
+ }
38
+ /**
39
+ * Wait until a token is available (async rate limiting)
40
+ * Returns a promise that resolves when the event can be processed
41
+ */
42
+ async waitForToken(count = 1) {
43
+ this.refill();
44
+ if (this.tokens >= count) {
45
+ this.tokens -= count;
46
+ return;
47
+ }
48
+ const tokensNeeded = count - this.tokens;
49
+ const waitMs = Math.ceil(tokensNeeded / this.refillRate);
50
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
51
+ return this.waitForToken(count);
52
+ }
53
+ /**
54
+ * Refill tokens based on elapsed time
55
+ */
56
+ refill() {
57
+ const now = Date.now();
58
+ const elapsed = now - this.lastRefill;
59
+ const tokensToAdd = elapsed * this.refillRate;
60
+ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
61
+ this.lastRefill = now;
62
+ }
63
+ /**
64
+ * Get current available tokens (for testing/debugging)
65
+ */
66
+ getAvailableTokens() {
67
+ this.refill();
68
+ return Math.floor(this.tokens);
69
+ }
70
+ /**
71
+ * Reset the rate limiter (for testing)
72
+ */
73
+ reset() {
74
+ this.tokens = this.maxTokens;
75
+ this.lastRefill = Date.now();
76
+ }
77
+ };
78
+
79
+ // src/event-queue.ts
80
+ var DEFAULT_CONFIG = {
81
+ maxSize: 5e4,
82
+ batchSize: 100,
83
+ flushInterval: 1e4,
84
+ maxRetries: 3,
85
+ rateLimit: {
86
+ maxEventsPerSecond: 100,
87
+ burstCapacity: 200
88
+ }
89
+ };
90
+ var EventQueue = class {
91
+ queue = [];
92
+ flushTimer = null;
93
+ config;
94
+ subscribers;
95
+ rateLimiter;
96
+ flushing = false;
97
+ constructor(subscribers, config) {
98
+ this.subscribers = subscribers;
99
+ this.config = { ...DEFAULT_CONFIG, ...config };
100
+ this.rateLimiter = this.config.rateLimit ? new TokenBucketRateLimiter(this.config.rateLimit) : null;
101
+ }
102
+ /**
103
+ * Enqueue an event for sending
104
+ *
105
+ * Backpressure policy:
106
+ * - Drops oldest event and logs warning if queue is full (same behavior in all environments)
107
+ */
108
+ enqueue(event) {
109
+ if (this.queue.length >= this.config.maxSize) {
110
+ const droppedEvent = this.queue.shift();
111
+ chunkABPEQ6RK_cjs.getLogger().warn(
112
+ `[autotel] Events queue full (${this.config.maxSize} events). Dropping oldest event. Events are being produced faster than they can be sent. Check your subscribers or reduce tracking frequency.`,
113
+ { droppedEvent: droppedEvent?.name }
114
+ );
115
+ }
116
+ this.queue.push(event);
117
+ this.scheduleBatchFlush();
118
+ }
119
+ /**
120
+ * Schedule a batch flush if not already scheduled
121
+ */
122
+ scheduleBatchFlush() {
123
+ if (this.flushTimer || this.flushing) return;
124
+ this.flushTimer = setTimeout(() => {
125
+ this.flushTimer = null;
126
+ void this.flushBatch();
127
+ }, this.config.flushInterval);
128
+ }
129
+ /**
130
+ * Flush a batch of events
131
+ */
132
+ async flushBatch() {
133
+ if (this.queue.length === 0 || this.flushing) return;
134
+ this.flushing = true;
135
+ try {
136
+ const batch = this.queue.splice(0, this.config.batchSize);
137
+ await this.sendWithRetry(batch, this.config.maxRetries);
138
+ } finally {
139
+ this.flushing = false;
140
+ if (this.queue.length > 0) {
141
+ this.scheduleBatchFlush();
142
+ }
143
+ }
144
+ }
145
+ /**
146
+ * Send events with exponential backoff retry
147
+ */
148
+ async sendWithRetry(events, retriesLeft) {
149
+ try {
150
+ await this.sendToSubscribers(events);
151
+ } catch (error) {
152
+ if (retriesLeft > 0) {
153
+ const delay = Math.pow(2, this.config.maxRetries - retriesLeft) * 1e3;
154
+ await new Promise((resolve) => setTimeout(resolve, delay));
155
+ return this.sendWithRetry(events, retriesLeft - 1);
156
+ } else {
157
+ chunkABPEQ6RK_cjs.getLogger().error(
158
+ "[autotel] Failed to send events after retries",
159
+ error instanceof Error ? error : void 0,
160
+ { retriesAttempted: this.config.maxRetries }
161
+ );
162
+ }
163
+ }
164
+ }
165
+ /**
166
+ * Send events to all configured subscribers with rate limiting
167
+ */
168
+ async sendToSubscribers(events) {
169
+ if (!this.rateLimiter) {
170
+ const promises = events.map(
171
+ (event) => Promise.all(
172
+ this.subscribers.map(
173
+ (subscriber) => subscriber.trackEvent(event.name, event.attributes)
174
+ )
175
+ )
176
+ );
177
+ await Promise.all(promises);
178
+ return;
179
+ }
180
+ for (const event of events) {
181
+ await this.rateLimiter.waitForToken();
182
+ await Promise.all(
183
+ this.subscribers.map(
184
+ (subscriber) => subscriber.trackEvent(event.name, event.attributes)
185
+ )
186
+ );
187
+ }
188
+ }
189
+ /**
190
+ * Flush all remaining events (for shutdown)
191
+ */
192
+ async flush() {
193
+ if (this.flushTimer) {
194
+ clearTimeout(this.flushTimer);
195
+ this.flushTimer = null;
196
+ }
197
+ while (this.flushing) {
198
+ await new Promise((resolve) => setTimeout(resolve, 10));
199
+ }
200
+ while (this.queue.length > 0) {
201
+ await this.flushBatch();
202
+ }
203
+ }
204
+ /**
205
+ * Get queue size (for testing/debugging)
206
+ */
207
+ size() {
208
+ return this.queue.length;
209
+ }
210
+ };
211
+
212
+ // src/track.ts
213
+ var eventsQueue = null;
214
+ function getOrCreateQueue() {
215
+ if (!chunkABPEQ6RK_cjs.isInitialized()) {
216
+ chunkABPEQ6RK_cjs.warnIfNotInitialized("track()");
217
+ return null;
218
+ }
219
+ if (!eventsQueue) {
220
+ const config = chunkABPEQ6RK_cjs.getConfig();
221
+ if (!config?.subscribers || config.subscribers.length === 0) {
222
+ return null;
223
+ }
224
+ eventsQueue = new EventQueue(config.subscribers);
225
+ }
226
+ return eventsQueue;
227
+ }
228
+ function track(event, data) {
229
+ const queue = getOrCreateQueue();
230
+ if (!queue) return;
231
+ const validationConfig = chunkABPEQ6RK_cjs.getValidationConfig();
232
+ const validated = chunkYLPNXZFI_cjs.validateEvent(event, data, validationConfig || void 0);
233
+ const span2 = api.trace.getActiveSpan();
234
+ const enrichedData = span2 ? {
235
+ ...validated.attributes,
236
+ traceId: span2.spanContext().traceId,
237
+ spanId: span2.spanContext().spanId
238
+ } : validated.attributes;
239
+ queue.enqueue({
240
+ name: validated.eventName,
241
+ attributes: enrichedData,
242
+ timestamp: Date.now()
243
+ });
244
+ }
245
+ function getEventQueue() {
246
+ return eventsQueue;
247
+ }
248
+ function resetEventQueue() {
249
+ eventsQueue = null;
250
+ }
251
+
252
+ // src/functional.ts
253
+ chunkNHCNRQD3_cjs.init_trace_context();
254
+ var inferenceCache = /* @__PURE__ */ new Map();
255
+ var MAX_CACHE_SIZE = 50;
256
+ function captureStackTrace() {
257
+ const originalStackTraceLimit = Error.stackTraceLimit;
258
+ Error.stackTraceLimit = 10;
259
+ const err = new Error("Stack trace capture");
260
+ const stack = err.stack || "";
261
+ Error.stackTraceLimit = originalStackTraceLimit;
262
+ return stack;
263
+ }
264
+ function parseCallLocation(stack) {
265
+ const lines = stack.split("\n");
266
+ let skippedExternalFrame = false;
267
+ for (const line of lines) {
268
+ if (line.includes("variable-name-inference.ts") || line.includes("variable-name-inference.js") || line.includes("functional.ts") || line.includes("functional.js")) {
269
+ continue;
270
+ }
271
+ const match = line.match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/) || line.match(/^.*?([^:]+):(\d+):(\d+)/);
272
+ if (match) {
273
+ let filePath = match[1].trim();
274
+ if (filePath.startsWith("file://")) {
275
+ try {
276
+ filePath = url.fileURLToPath(filePath);
277
+ } catch {
278
+ continue;
279
+ }
280
+ }
281
+ if (!skippedExternalFrame) {
282
+ skippedExternalFrame = true;
283
+ continue;
284
+ }
285
+ return {
286
+ file: filePath,
287
+ line: Number.parseInt(match[2], 10),
288
+ column: Number.parseInt(match[3], 10)
289
+ };
290
+ }
291
+ }
292
+ return void 0;
293
+ }
294
+ function readSourceLine(filePath, lineNumber) {
295
+ try {
296
+ if (typeof fs.readFileSync !== "function") {
297
+ return void 0;
298
+ }
299
+ const content = fs.readFileSync(filePath, "utf8");
300
+ const lines = content.split("\n");
301
+ return lines[lineNumber - 1];
302
+ } catch {
303
+ return void 0;
304
+ }
305
+ }
306
+ function extractVariableName(sourceLine) {
307
+ const trimmed = sourceLine.trim();
308
+ const patterns = [
309
+ // export const varName = anyFunction(
310
+ /export\s+const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/,
311
+ // const varName = anyFunction(
312
+ /const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/,
313
+ // export let varName = anyFunction(
314
+ /export\s+let\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/,
315
+ // let varName = anyFunction(
316
+ /let\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/,
317
+ // export var varName = anyFunction(
318
+ /export\s+var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/,
319
+ // var varName = anyFunction(
320
+ /var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/
321
+ ];
322
+ for (const pattern of patterns) {
323
+ const match = trimmed.match(pattern);
324
+ if (match && match[1]) {
325
+ return match[1];
326
+ }
327
+ }
328
+ return void 0;
329
+ }
330
+ function cacheInference(key, value) {
331
+ if (inferenceCache.size >= MAX_CACHE_SIZE) {
332
+ const firstKey = inferenceCache.keys().next().value;
333
+ if (firstKey) {
334
+ inferenceCache.delete(firstKey);
335
+ }
336
+ }
337
+ inferenceCache.set(key, value);
338
+ }
339
+ function inferVariableNameFromCallStack() {
340
+ try {
341
+ const stack = captureStackTrace();
342
+ const callLocation = parseCallLocation(stack);
343
+ if (!callLocation) {
344
+ return void 0;
345
+ }
346
+ const cacheKey = `${callLocation.file}:${callLocation.line}`;
347
+ if (inferenceCache.has(cacheKey)) {
348
+ return inferenceCache.get(cacheKey);
349
+ }
350
+ const sourceLine = readSourceLine(callLocation.file, callLocation.line);
351
+ if (!sourceLine) {
352
+ return void 0;
353
+ }
354
+ const variableName = extractVariableName(sourceLine);
355
+ cacheInference(cacheKey, variableName);
356
+ return variableName;
357
+ } catch {
358
+ return void 0;
359
+ }
360
+ }
361
+
362
+ // src/functional.ts
363
+ var FACTORY_NAME_HINTS = /* @__PURE__ */ new Set([
364
+ "ctx",
365
+ "_ctx",
366
+ "context",
367
+ "tracecontext",
368
+ "tracectx"
369
+ ]);
370
+ var TRACE_FACTORY_SET = /* @__PURE__ */ new WeakSet();
371
+ var SINGLE_LINE_COMMENT_REGEX = /\/\/.*$/gm;
372
+ var MULTI_LINE_COMMENT_REGEX = /\/\*[\s\S]*?\*\//gm;
373
+ var PARAM_TOKEN_SANITIZE_REGEX = new RegExp(String.raw`[{}\[\]\s]`, "g");
374
+ function markAsTraceFactory(fn) {
375
+ TRACE_FACTORY_SET.add(fn);
376
+ }
377
+ function hasFactoryMark(fn) {
378
+ return TRACE_FACTORY_SET.has(fn);
379
+ }
380
+ function sanitizeParameterToken(token) {
381
+ const [firstToken] = token.split("=");
382
+ return (firstToken ?? "").replaceAll(PARAM_TOKEN_SANITIZE_REGEX, "").trim();
383
+ }
384
+ function getFirstParameterToken(fn) {
385
+ let source = Function.prototype.toString.call(fn);
386
+ source = source.replaceAll(MULTI_LINE_COMMENT_REGEX, "").replaceAll(SINGLE_LINE_COMMENT_REGEX, "").trim();
387
+ const arrowMatch = source.match(
388
+ /^(?:async\s*)?(?:\(([^)]*)\)|([^=()]+))\s*=>/
389
+ );
390
+ if (arrowMatch) {
391
+ const params = (arrowMatch[1] ?? arrowMatch[2] ?? "").split(",");
392
+ const first = params[0]?.trim();
393
+ if (first) {
394
+ return sanitizeParameterToken(first);
395
+ }
396
+ return null;
397
+ }
398
+ const functionMatch = source.match(/^[^(]*\(([^)]*)\)/);
399
+ if (functionMatch) {
400
+ const params = functionMatch[1]?.split(",");
401
+ const first = params?.[0]?.trim();
402
+ if (first) {
403
+ return sanitizeParameterToken(first);
404
+ }
405
+ }
406
+ return null;
407
+ }
408
+ function looksLikeTraceFactory(fn) {
409
+ if (hasFactoryMark(fn)) {
410
+ return true;
411
+ }
412
+ if (fn.length === 0) {
413
+ return false;
414
+ }
415
+ const firstParam = getFirstParameterToken(fn);
416
+ if (!firstParam) {
417
+ return false;
418
+ }
419
+ const normalized = firstParam.toLowerCase();
420
+ if (FACTORY_NAME_HINTS.has(normalized) || normalized.startsWith("ctx") || normalized.startsWith("_ctx") || normalized.startsWith("trace")) {
421
+ return true;
422
+ }
423
+ return false;
424
+ }
425
+ function isFactoryReturningFunction(fnWithCtx) {
426
+ try {
427
+ const result = fnWithCtx(createDummyCtx());
428
+ return typeof result === "function";
429
+ } catch {
430
+ return false;
431
+ }
432
+ }
433
+ function isTraceFactoryFunction(fn) {
434
+ if (typeof fn !== "function") {
435
+ return false;
436
+ }
437
+ if (hasFactoryMark(fn)) {
438
+ return true;
439
+ }
440
+ if (looksLikeTraceFactory(fn)) {
441
+ markAsTraceFactory(fn);
442
+ return true;
443
+ }
444
+ return false;
445
+ }
446
+ function ensureTraceFactory(fnOrFactory) {
447
+ if (isTraceFactoryFunction(fnOrFactory)) {
448
+ return fnOrFactory;
449
+ }
450
+ const plainFn = fnOrFactory;
451
+ const factory = (ctx2) => {
452
+ return plainFn;
453
+ };
454
+ markAsTraceFactory(factory);
455
+ return factory;
456
+ }
457
+ function wrapFactoryWithTracing(fnOrFactory, options, variableName) {
458
+ const factory = ensureTraceFactory(fnOrFactory);
459
+ const sampleFn = factory(createDummyCtx());
460
+ const innerFunctionName = inferFunctionName(
461
+ sampleFn
462
+ );
463
+ const callStackVariableName = innerFunctionName ? void 0 : inferVariableNameFromCallStack();
464
+ const factoryName = inferFunctionName(factory);
465
+ const effectiveVariableName = variableName || innerFunctionName || callStackVariableName || factoryName;
466
+ const useAsyncWrapper = isAsyncFunction(sampleFn);
467
+ if (useAsyncWrapper) {
468
+ return wrapWithTracing(
469
+ factory,
470
+ options,
471
+ effectiveVariableName
472
+ );
473
+ }
474
+ return wrapWithTracingSync(
475
+ factory,
476
+ options,
477
+ effectiveVariableName
478
+ );
479
+ }
480
+ var MAX_ERROR_MESSAGE_LENGTH = 500;
481
+ function createDummyCtx() {
482
+ return {
483
+ traceId: "",
484
+ spanId: "",
485
+ correlationId: "",
486
+ setAttribute: () => {
487
+ },
488
+ setAttributes: () => {
489
+ },
490
+ setStatus: () => {
491
+ },
492
+ recordException: () => {
493
+ },
494
+ getBaggage: () => {
495
+ },
496
+ setBaggage: () => "",
497
+ deleteBaggage: () => {
498
+ },
499
+ getAllBaggage: () => /* @__PURE__ */ new Map()
500
+ };
501
+ }
502
+ function isAsyncFunction(fn) {
503
+ return typeof fn === "function" && fn.constructor?.name === "AsyncFunction";
504
+ }
505
+ var INSTRUMENTED_SYMBOL = Symbol.for("autotel.functional.instrumented");
506
+ function hasInstrumentationFlag(value) {
507
+ return (typeof value === "function" || typeof value === "object") && value !== null && Boolean(value[INSTRUMENTED_SYMBOL]);
508
+ }
509
+ function truncateErrorMessage(message) {
510
+ if (message.length <= MAX_ERROR_MESSAGE_LENGTH) {
511
+ return message;
512
+ }
513
+ return `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}... (truncated)`;
514
+ }
515
+ function inferFunctionName(fn) {
516
+ const displayName = fn.displayName;
517
+ if (displayName) {
518
+ return displayName;
519
+ }
520
+ if (fn.name && fn.name !== "anonymous" && fn.name !== "") {
521
+ return fn.name;
522
+ }
523
+ const source = Function.prototype.toString.call(fn);
524
+ const match = source.match(/function\s+([^(\s]+)/);
525
+ if (match && match[1] && match[1] !== "anonymous") {
526
+ return match[1];
527
+ }
528
+ return void 0;
529
+ }
530
+ function getSpanName(options, fn, variableName) {
531
+ if (options.name) {
532
+ return options.name;
533
+ }
534
+ let fnName = variableName || inferFunctionName(fn);
535
+ fnName = fnName || "anonymous";
536
+ if (options.serviceName) {
537
+ return `${options.serviceName}.${fnName}`;
538
+ }
539
+ if (fnName && fnName !== "anonymous") {
540
+ return fnName;
541
+ }
542
+ return "unknown";
543
+ }
544
+ function shouldSkip(key, fn, skip) {
545
+ if (key.startsWith("_")) {
546
+ return true;
547
+ }
548
+ if (!skip || skip.length === 0) {
549
+ return false;
550
+ }
551
+ for (const rule of skip) {
552
+ if (typeof rule === "string" && key === rule) {
553
+ return true;
554
+ } else if (rule instanceof RegExp && rule.test(key)) {
555
+ return true;
556
+ } else if (typeof rule === "function" && rule(key, fn)) {
557
+ return true;
558
+ }
559
+ }
560
+ return false;
561
+ }
562
+ function getCtxValue() {
563
+ const activeSpan = api.trace.getActiveSpan();
564
+ if (!activeSpan) return null;
565
+ return chunkNHCNRQD3_cjs.createTraceContext(activeSpan);
566
+ }
567
+ var ctx = new Proxy({}, {
568
+ get(_target, prop) {
569
+ const ctxValue = getCtxValue();
570
+ if (!ctxValue) {
571
+ return;
572
+ }
573
+ return ctxValue[prop];
574
+ },
575
+ has(_target, prop) {
576
+ const ctxValue = getCtxValue();
577
+ if (!ctxValue) {
578
+ return false;
579
+ }
580
+ return prop in ctxValue;
581
+ },
582
+ ownKeys() {
583
+ const ctxValue = getCtxValue();
584
+ if (!ctxValue) {
585
+ return [];
586
+ }
587
+ return Object.keys(ctxValue);
588
+ },
589
+ getOwnPropertyDescriptor(_target, prop) {
590
+ const ctxValue = getCtxValue();
591
+ if (!ctxValue) {
592
+ return;
593
+ }
594
+ return Object.getOwnPropertyDescriptor(ctxValue, prop);
595
+ }
596
+ });
597
+ function wrapWithTracing(fnFactory, options, variableName) {
598
+ if (hasInstrumentationFlag(fnFactory)) ;
599
+ const config = chunkY4Y2S7BM_cjs.getConfig();
600
+ const tracer = config.tracer;
601
+ const meter = config.meter;
602
+ const sampler = options.sampler || new chunkHE6T6FIX_cjs.AlwaysSampler();
603
+ const tempFn = fnFactory(createDummyCtx());
604
+ const spanName = getSpanName(options, tempFn, variableName);
605
+ const callCounter = options.withMetrics ? meter.createCounter(`${spanName}.calls`, {
606
+ description: `Call count for ${spanName}`,
607
+ unit: "1"
608
+ }) : void 0;
609
+ const durationHistogram = options.withMetrics ? meter.createHistogram(`${spanName}.duration`, {
610
+ description: `Duration for ${spanName}`,
611
+ unit: "ms"
612
+ }) : void 0;
613
+ const wrappedFunction = async function wrappedFunction2(...args) {
614
+ const samplingContext = {
615
+ operationName: spanName,
616
+ args,
617
+ metadata: {}
618
+ };
619
+ const shouldSample = sampler.shouldSample(samplingContext);
620
+ const needsTailSampling = "needsTailSampling" in sampler && typeof sampler.needsTailSampling === "function" ? sampler.needsTailSampling() : false;
621
+ if (!shouldSample && !needsTailSampling) {
622
+ const fn = fnFactory(createDummyCtx());
623
+ return await fn.call(this, ...args);
624
+ }
625
+ const startTime = performance.now();
626
+ const isRootSpan = options.startNewRoot || api.trace.getActiveSpan() === void 0;
627
+ const shouldAutoFlush = options.autoFlushEvents ?? chunkABPEQ6RK_cjs.getConfig()?.autoFlushEvents ?? true;
628
+ const shouldAutoFlushSpans = chunkABPEQ6RK_cjs.getConfig()?.autoFlush ?? false;
629
+ const flushIfNeeded = async () => {
630
+ if (!shouldAutoFlush || !isRootSpan) return;
631
+ try {
632
+ const queue = getEventQueue();
633
+ if (queue && queue.size() > 0) {
634
+ await queue.flush();
635
+ }
636
+ if (shouldAutoFlushSpans) {
637
+ const sdk = chunkABPEQ6RK_cjs.getSdk();
638
+ if (sdk) {
639
+ try {
640
+ const sdkAny = sdk;
641
+ if (typeof sdkAny.getTracerProvider === "function") {
642
+ const tracerProvider = sdkAny.getTracerProvider();
643
+ if (tracerProvider && typeof tracerProvider.forceFlush === "function") {
644
+ await tracerProvider.forceFlush();
645
+ }
646
+ }
647
+ } catch {
648
+ }
649
+ }
650
+ }
651
+ } catch (error) {
652
+ const initConfig = chunkABPEQ6RK_cjs.getConfig();
653
+ const logger = initConfig?.logger;
654
+ if (logger?.error) {
655
+ if (error instanceof Error) {
656
+ logger.error("[autotel] Auto-flush failed", error);
657
+ } else {
658
+ logger.error(`[autotel] Auto-flush failed: ${String(error)}`);
659
+ }
660
+ }
661
+ }
662
+ };
663
+ return tracer.startActiveSpan(
664
+ spanName,
665
+ options.startNewRoot ? { root: true } : {},
666
+ async (span2) => {
667
+ return chunkYLPNXZFI_cjs.runInOperationContext(spanName, async () => {
668
+ let shouldKeepSpan = true;
669
+ chunkTRI4V5BF_cjs.setSpanName(span2, spanName);
670
+ const initialContext = api.context.active();
671
+ const contextStorage = chunkNHCNRQD3_cjs.getContextStorage();
672
+ if (!contextStorage.getStore()) {
673
+ contextStorage.enterWith(initialContext);
674
+ }
675
+ const ctxValue = chunkNHCNRQD3_cjs.createTraceContext(span2);
676
+ const fn = fnFactory(ctxValue);
677
+ const argsAttributes = options.attributesFromArgs ? options.attributesFromArgs(args) : {};
678
+ const handleTailSampling = (success, duration, error) => {
679
+ if (needsTailSampling && "shouldKeepTrace" in sampler && typeof sampler.shouldKeepTrace === "function") {
680
+ shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {
681
+ success,
682
+ duration,
683
+ error
684
+ });
685
+ span2.setAttribute("sampling.tail.keep", shouldKeepSpan);
686
+ span2.setAttribute("sampling.tail.evaluated", true);
687
+ }
688
+ };
689
+ const onSuccess = async (result) => {
690
+ const duration = performance.now() - startTime;
691
+ callCounter?.add(1, {
692
+ operation: spanName,
693
+ status: "success"
694
+ });
695
+ durationHistogram?.record(duration, {
696
+ operation: spanName,
697
+ status: "success"
698
+ });
699
+ const resultAttributes = options.attributesFromResult ? options.attributesFromResult(result) : {};
700
+ span2.setStatus({ code: api.SpanStatusCode.OK });
701
+ span2.setAttributes({
702
+ ...argsAttributes,
703
+ ...resultAttributes,
704
+ "operation.name": spanName,
705
+ "code.function": spanName,
706
+ "operation.duration": duration,
707
+ "operation.success": true
708
+ });
709
+ handleTailSampling(true, duration);
710
+ span2.end();
711
+ await flushIfNeeded();
712
+ return result;
713
+ };
714
+ const onError = async (error) => {
715
+ const duration = performance.now() - startTime;
716
+ callCounter?.add(1, {
717
+ operation: spanName,
718
+ status: "error"
719
+ });
720
+ durationHistogram?.record(duration, {
721
+ operation: spanName,
722
+ status: "error"
723
+ });
724
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
725
+ const truncatedMessage = truncateErrorMessage(errorMessage);
726
+ span2.setStatus({
727
+ code: api.SpanStatusCode.ERROR,
728
+ message: truncatedMessage
729
+ });
730
+ span2.setAttributes({
731
+ ...argsAttributes,
732
+ "operation.name": spanName,
733
+ "code.function": spanName,
734
+ "operation.duration": duration,
735
+ "operation.success": false,
736
+ error: true,
737
+ "exception.type": error instanceof Error ? error.constructor.name : "Error",
738
+ "exception.message": truncatedMessage
739
+ });
740
+ if (error instanceof Error && error.stack) {
741
+ span2.setAttribute(
742
+ "exception.stack",
743
+ error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH)
744
+ );
745
+ }
746
+ span2.recordException(
747
+ error instanceof Error ? error : new Error(String(error))
748
+ );
749
+ handleTailSampling(false, duration, error);
750
+ span2.end();
751
+ await flushIfNeeded();
752
+ throw error;
753
+ };
754
+ try {
755
+ callCounter?.add(1, {
756
+ operation: spanName,
757
+ status: "started"
758
+ });
759
+ const executeWithContext = async () => {
760
+ const currentContext = chunkNHCNRQD3_cjs.getActiveContextWithBaggage();
761
+ return api.context.with(currentContext, async () => {
762
+ return fn.call(this, ...args);
763
+ });
764
+ };
765
+ const result = await executeWithContext();
766
+ return await onSuccess(result);
767
+ } catch (error) {
768
+ await onError(error);
769
+ throw error;
770
+ }
771
+ });
772
+ }
773
+ );
774
+ };
775
+ wrappedFunction[INSTRUMENTED_SYMBOL] = true;
776
+ Object.defineProperty(wrappedFunction, "name", {
777
+ value: tempFn.name || "trace",
778
+ configurable: true
779
+ });
780
+ return wrappedFunction;
781
+ }
782
+ function wrapWithTracingSync(fnFactory, options, variableName) {
783
+ if (hasInstrumentationFlag(fnFactory)) ;
784
+ const config = chunkY4Y2S7BM_cjs.getConfig();
785
+ const tracer = config.tracer;
786
+ const meter = config.meter;
787
+ const sampler = options.sampler || new chunkHE6T6FIX_cjs.AlwaysSampler();
788
+ const tempFn = fnFactory(createDummyCtx());
789
+ const spanName = getSpanName(options, tempFn, variableName);
790
+ const callCounter = options.withMetrics ? meter.createCounter(`${spanName}.calls`, {
791
+ description: `Call count for ${spanName}`,
792
+ unit: "1"
793
+ }) : void 0;
794
+ const durationHistogram = options.withMetrics ? meter.createHistogram(`${spanName}.duration`, {
795
+ description: `Duration for ${spanName}`,
796
+ unit: "ms"
797
+ }) : void 0;
798
+ function wrappedFunction(...args) {
799
+ const samplingContext = {
800
+ operationName: spanName,
801
+ args,
802
+ metadata: {}
803
+ };
804
+ const shouldSample = sampler.shouldSample(samplingContext);
805
+ const needsTailSampling = "needsTailSampling" in sampler && typeof sampler.needsTailSampling === "function" ? sampler.needsTailSampling() : false;
806
+ if (!shouldSample && !needsTailSampling) {
807
+ const fn = fnFactory(createDummyCtx());
808
+ return fn.call(this, ...args);
809
+ }
810
+ const startTime = performance.now();
811
+ const isRootSpan = options.startNewRoot || api.trace.getActiveSpan() === void 0;
812
+ const shouldAutoFlush = options.autoFlushEvents ?? chunkABPEQ6RK_cjs.getConfig()?.autoFlushEvents ?? true;
813
+ const shouldAutoFlushSpans = chunkABPEQ6RK_cjs.getConfig()?.autoFlush ?? false;
814
+ const flushIfNeeded = () => {
815
+ if (!shouldAutoFlush || !isRootSpan) return;
816
+ const queue = getEventQueue();
817
+ if (queue && queue.size() > 0) {
818
+ void queue.flush().catch((error) => {
819
+ const initConfig = chunkABPEQ6RK_cjs.getConfig();
820
+ const logger = initConfig?.logger;
821
+ if (logger?.error) {
822
+ if (error instanceof Error) {
823
+ logger.error("[autotel] Auto-flush failed", error);
824
+ } else {
825
+ logger.error(`[autotel] Auto-flush failed: ${String(error)}`);
826
+ }
827
+ }
828
+ });
829
+ }
830
+ if (shouldAutoFlushSpans) {
831
+ const sdk = chunkABPEQ6RK_cjs.getSdk();
832
+ if (sdk) {
833
+ try {
834
+ const sdkAny = sdk;
835
+ if (typeof sdkAny.getTracerProvider === "function") {
836
+ const tracerProvider = sdkAny.getTracerProvider();
837
+ if (tracerProvider && typeof tracerProvider.forceFlush === "function") {
838
+ void tracerProvider.forceFlush().catch((error) => {
839
+ const initConfig = chunkABPEQ6RK_cjs.getConfig();
840
+ const logger = initConfig?.logger;
841
+ if (logger?.error) {
842
+ if (error instanceof Error) {
843
+ logger.error("[autotel] Span flush failed", error);
844
+ } else {
845
+ logger.error(
846
+ `[autotel] Span flush failed: ${String(error)}`
847
+ );
848
+ }
849
+ }
850
+ });
851
+ }
852
+ }
853
+ } catch {
854
+ }
855
+ }
856
+ }
857
+ };
858
+ return tracer.startActiveSpan(
859
+ spanName,
860
+ options.startNewRoot ? { root: true } : {},
861
+ (span2) => {
862
+ return chunkYLPNXZFI_cjs.runInOperationContext(spanName, () => {
863
+ let shouldKeepSpan = true;
864
+ chunkTRI4V5BF_cjs.setSpanName(span2, spanName);
865
+ const ctxValue = chunkNHCNRQD3_cjs.createTraceContext(span2);
866
+ const fn = fnFactory(ctxValue);
867
+ const argsAttributes = options.attributesFromArgs ? options.attributesFromArgs(args) : {};
868
+ const handleTailSampling = (success, duration, error) => {
869
+ if (needsTailSampling && "shouldKeepTrace" in sampler && typeof sampler.shouldKeepTrace === "function") {
870
+ shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {
871
+ success,
872
+ duration,
873
+ error
874
+ });
875
+ span2.setAttribute("sampling.tail.keep", shouldKeepSpan);
876
+ span2.setAttribute("sampling.tail.evaluated", true);
877
+ }
878
+ };
879
+ const onSuccess = (result) => {
880
+ const duration = performance.now() - startTime;
881
+ callCounter?.add(1, {
882
+ operation: spanName,
883
+ status: "success"
884
+ });
885
+ durationHistogram?.record(duration, {
886
+ operation: spanName,
887
+ status: "success"
888
+ });
889
+ const resultAttributes = options.attributesFromResult ? options.attributesFromResult(result) : {};
890
+ span2.setStatus({ code: api.SpanStatusCode.OK });
891
+ span2.setAttributes({
892
+ ...argsAttributes,
893
+ ...resultAttributes,
894
+ "operation.name": spanName,
895
+ "code.function": spanName,
896
+ "operation.duration": duration,
897
+ "operation.success": true
898
+ });
899
+ handleTailSampling(true, duration);
900
+ span2.end();
901
+ void flushIfNeeded();
902
+ return result;
903
+ };
904
+ const onError = (error) => {
905
+ const duration = performance.now() - startTime;
906
+ callCounter?.add(1, {
907
+ operation: spanName,
908
+ status: "error"
909
+ });
910
+ durationHistogram?.record(duration, {
911
+ operation: spanName,
912
+ status: "error"
913
+ });
914
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
915
+ const truncatedMessage = truncateErrorMessage(errorMessage);
916
+ span2.setStatus({
917
+ code: api.SpanStatusCode.ERROR,
918
+ message: truncatedMessage
919
+ });
920
+ span2.setAttributes({
921
+ ...argsAttributes,
922
+ "operation.name": spanName,
923
+ "code.function": spanName,
924
+ "operation.duration": duration,
925
+ "operation.success": false,
926
+ error: true,
927
+ "exception.type": error instanceof Error ? error.constructor.name : "Error",
928
+ "exception.message": truncatedMessage
929
+ });
930
+ span2.recordException(
931
+ error instanceof Error ? error : new Error(String(error))
932
+ );
933
+ handleTailSampling(false, duration, error);
934
+ span2.end();
935
+ void flushIfNeeded();
936
+ throw error;
937
+ };
938
+ try {
939
+ callCounter?.add(1, {
940
+ operation: spanName,
941
+ status: "started"
942
+ });
943
+ const result = fn.call(this, ...args);
944
+ if (result instanceof Promise) {
945
+ return result.then(onSuccess, onError);
946
+ }
947
+ return onSuccess(result);
948
+ } catch (error) {
949
+ return onError(error);
950
+ }
951
+ });
952
+ }
953
+ );
954
+ }
955
+ wrappedFunction[INSTRUMENTED_SYMBOL] = true;
956
+ Object.defineProperty(wrappedFunction, "name", {
957
+ value: tempFn.name || "trace",
958
+ configurable: true
959
+ });
960
+ return wrappedFunction;
961
+ }
962
+ function executeImmediately(fn, options) {
963
+ const config = chunkY4Y2S7BM_cjs.getConfig();
964
+ const tracer = config.tracer;
965
+ const meter = config.meter;
966
+ const sampler = options.sampler || new chunkHE6T6FIX_cjs.AlwaysSampler();
967
+ const spanName = options.name || "anonymous";
968
+ const samplingContext = {
969
+ operationName: spanName,
970
+ args: [],
971
+ metadata: {}
972
+ };
973
+ const shouldSample = sampler.shouldSample(samplingContext);
974
+ const needsTailSampling = "needsTailSampling" in sampler && typeof sampler.needsTailSampling === "function" ? sampler.needsTailSampling() : false;
975
+ if (!shouldSample && !needsTailSampling) {
976
+ return fn(createDummyCtx());
977
+ }
978
+ const startTime = performance.now();
979
+ const isRootSpan = options.startNewRoot || api.trace.getActiveSpan() === void 0;
980
+ const shouldAutoFlush = options.autoFlushEvents ?? chunkABPEQ6RK_cjs.getConfig()?.autoFlushEvents ?? true;
981
+ const shouldAutoFlushSpans = chunkABPEQ6RK_cjs.getConfig()?.autoFlush ?? false;
982
+ const callCounter = options.withMetrics ? meter.createCounter(`${spanName}.calls`, {
983
+ description: `Call count for ${spanName}`,
984
+ unit: "1"
985
+ }) : void 0;
986
+ const durationHistogram = options.withMetrics ? meter.createHistogram(`${spanName}.duration`, {
987
+ description: `Duration for ${spanName}`,
988
+ unit: "ms"
989
+ }) : void 0;
990
+ const flushIfNeeded = async () => {
991
+ if (!shouldAutoFlush || !isRootSpan) return;
992
+ try {
993
+ const queue = getEventQueue();
994
+ if (queue && queue.size() > 0) {
995
+ await queue.flush();
996
+ }
997
+ if (shouldAutoFlushSpans) {
998
+ const sdk = chunkABPEQ6RK_cjs.getSdk();
999
+ if (sdk) {
1000
+ try {
1001
+ const sdkAny = sdk;
1002
+ if (typeof sdkAny.getTracerProvider === "function") {
1003
+ const tracerProvider = sdkAny.getTracerProvider();
1004
+ if (tracerProvider && typeof tracerProvider.forceFlush === "function") {
1005
+ await tracerProvider.forceFlush();
1006
+ }
1007
+ }
1008
+ } catch {
1009
+ }
1010
+ }
1011
+ }
1012
+ } catch (error) {
1013
+ const initConfig = chunkABPEQ6RK_cjs.getConfig();
1014
+ const logger = initConfig?.logger;
1015
+ if (logger?.error) {
1016
+ if (error instanceof Error) {
1017
+ logger.error("[autotel] Auto-flush failed", error);
1018
+ } else {
1019
+ logger.error(`[autotel] Auto-flush failed: ${String(error)}`);
1020
+ }
1021
+ }
1022
+ }
1023
+ };
1024
+ return tracer.startActiveSpan(
1025
+ spanName,
1026
+ options.startNewRoot ? { root: true } : {},
1027
+ (span2) => {
1028
+ return chunkYLPNXZFI_cjs.runInOperationContext(spanName, () => {
1029
+ let shouldKeepSpan = true;
1030
+ chunkTRI4V5BF_cjs.setSpanName(span2, spanName);
1031
+ const ctxValue = chunkNHCNRQD3_cjs.createTraceContext(span2);
1032
+ const handleTailSampling = (success, duration, error) => {
1033
+ if (needsTailSampling && "shouldKeepTrace" in sampler && typeof sampler.shouldKeepTrace === "function") {
1034
+ shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {
1035
+ success,
1036
+ duration,
1037
+ error
1038
+ });
1039
+ span2.setAttribute("sampling.tail.keep", shouldKeepSpan);
1040
+ span2.setAttribute("sampling.tail.evaluated", true);
1041
+ }
1042
+ };
1043
+ const onSuccessSync = (result) => {
1044
+ const duration = performance.now() - startTime;
1045
+ callCounter?.add(1, {
1046
+ operation: spanName,
1047
+ status: "success"
1048
+ });
1049
+ durationHistogram?.record(duration, {
1050
+ operation: spanName,
1051
+ status: "success"
1052
+ });
1053
+ span2.setStatus({ code: api.SpanStatusCode.OK });
1054
+ span2.setAttributes({
1055
+ "operation.name": spanName,
1056
+ "code.function": spanName,
1057
+ "operation.duration": duration,
1058
+ "operation.success": true
1059
+ });
1060
+ handleTailSampling(true, duration);
1061
+ span2.end();
1062
+ void flushIfNeeded();
1063
+ return result;
1064
+ };
1065
+ const onErrorSync = (error) => {
1066
+ const duration = performance.now() - startTime;
1067
+ callCounter?.add(1, {
1068
+ operation: spanName,
1069
+ status: "error"
1070
+ });
1071
+ durationHistogram?.record(duration, {
1072
+ operation: spanName,
1073
+ status: "error"
1074
+ });
1075
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1076
+ const truncatedMessage = truncateErrorMessage(errorMessage);
1077
+ span2.setStatus({
1078
+ code: api.SpanStatusCode.ERROR,
1079
+ message: truncatedMessage
1080
+ });
1081
+ span2.setAttributes({
1082
+ "operation.name": spanName,
1083
+ "code.function": spanName,
1084
+ "operation.duration": duration,
1085
+ "operation.success": false,
1086
+ error: true,
1087
+ "exception.type": error instanceof Error ? error.constructor.name : "Error",
1088
+ "exception.message": truncatedMessage
1089
+ });
1090
+ if (error instanceof Error && error.stack) {
1091
+ span2.setAttribute(
1092
+ "exception.stack",
1093
+ error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH)
1094
+ );
1095
+ }
1096
+ span2.recordException(
1097
+ error instanceof Error ? error : new Error(String(error))
1098
+ );
1099
+ handleTailSampling(false, duration, error);
1100
+ span2.end();
1101
+ void flushIfNeeded();
1102
+ throw error;
1103
+ };
1104
+ const onSuccessAsync = async (result) => {
1105
+ const duration = performance.now() - startTime;
1106
+ callCounter?.add(1, {
1107
+ operation: spanName,
1108
+ status: "success"
1109
+ });
1110
+ durationHistogram?.record(duration, {
1111
+ operation: spanName,
1112
+ status: "success"
1113
+ });
1114
+ span2.setStatus({ code: api.SpanStatusCode.OK });
1115
+ span2.setAttributes({
1116
+ "operation.name": spanName,
1117
+ "code.function": spanName,
1118
+ "operation.duration": duration,
1119
+ "operation.success": true
1120
+ });
1121
+ handleTailSampling(true, duration);
1122
+ span2.end();
1123
+ await flushIfNeeded();
1124
+ return result;
1125
+ };
1126
+ const onErrorAsync = async (error) => {
1127
+ const duration = performance.now() - startTime;
1128
+ callCounter?.add(1, {
1129
+ operation: spanName,
1130
+ status: "error"
1131
+ });
1132
+ durationHistogram?.record(duration, {
1133
+ operation: spanName,
1134
+ status: "error"
1135
+ });
1136
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1137
+ const truncatedMessage = truncateErrorMessage(errorMessage);
1138
+ span2.setStatus({
1139
+ code: api.SpanStatusCode.ERROR,
1140
+ message: truncatedMessage
1141
+ });
1142
+ span2.setAttributes({
1143
+ "operation.name": spanName,
1144
+ "code.function": spanName,
1145
+ "operation.duration": duration,
1146
+ "operation.success": false,
1147
+ error: true,
1148
+ "exception.type": error instanceof Error ? error.constructor.name : "Error",
1149
+ "exception.message": truncatedMessage
1150
+ });
1151
+ if (error instanceof Error && error.stack) {
1152
+ span2.setAttribute(
1153
+ "exception.stack",
1154
+ error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH)
1155
+ );
1156
+ }
1157
+ span2.recordException(
1158
+ error instanceof Error ? error : new Error(String(error))
1159
+ );
1160
+ handleTailSampling(false, duration, error);
1161
+ span2.end();
1162
+ await flushIfNeeded();
1163
+ throw error;
1164
+ };
1165
+ try {
1166
+ callCounter?.add(1, {
1167
+ operation: spanName,
1168
+ status: "started"
1169
+ });
1170
+ const result = fn(ctxValue);
1171
+ if (result instanceof Promise) {
1172
+ return result.then(onSuccessAsync, onErrorAsync);
1173
+ }
1174
+ return onSuccessSync(result);
1175
+ } catch (error) {
1176
+ return onErrorSync(error);
1177
+ }
1178
+ });
1179
+ }
1180
+ );
1181
+ }
1182
+ function trace2(fnOrNameOrOptions, maybeFn) {
1183
+ if (typeof fnOrNameOrOptions === "function") {
1184
+ if (looksLikeTraceFactory(fnOrNameOrOptions) && !isFactoryReturningFunction(
1185
+ fnOrNameOrOptions
1186
+ )) {
1187
+ return executeImmediately(
1188
+ fnOrNameOrOptions,
1189
+ {}
1190
+ );
1191
+ }
1192
+ return wrapFactoryWithTracing(
1193
+ fnOrNameOrOptions,
1194
+ {}
1195
+ );
1196
+ }
1197
+ if (typeof fnOrNameOrOptions === "string") {
1198
+ if (!maybeFn) {
1199
+ throw new Error("trace(name, fn): fn is required");
1200
+ }
1201
+ if (looksLikeTraceFactory(maybeFn) && !isFactoryReturningFunction(maybeFn)) {
1202
+ return executeImmediately(
1203
+ maybeFn,
1204
+ { name: fnOrNameOrOptions }
1205
+ );
1206
+ }
1207
+ return wrapFactoryWithTracing(
1208
+ maybeFn,
1209
+ { name: fnOrNameOrOptions }
1210
+ );
1211
+ }
1212
+ if (!maybeFn) {
1213
+ throw new Error("trace(options, fn): fn is required");
1214
+ }
1215
+ if (looksLikeTraceFactory(maybeFn) && !isFactoryReturningFunction(maybeFn)) {
1216
+ return executeImmediately(
1217
+ maybeFn,
1218
+ fnOrNameOrOptions
1219
+ );
1220
+ }
1221
+ return wrapFactoryWithTracing(
1222
+ maybeFn,
1223
+ fnOrNameOrOptions
1224
+ );
1225
+ }
1226
+ function withTracing(options = {}) {
1227
+ return (fnFactory) => wrapFactoryWithTracing(fnFactory, options);
1228
+ }
1229
+ function instrument(options) {
1230
+ const { functions, ...tracingOptions } = options;
1231
+ const instrumented = {};
1232
+ for (const key of Object.keys(functions)) {
1233
+ const typedKey = key;
1234
+ const fn = functions[typedKey];
1235
+ if (!fn || typeof fn !== "function") {
1236
+ instrumented[typedKey] = fn;
1237
+ continue;
1238
+ }
1239
+ if (shouldSkip(key, fn, tracingOptions.skip)) {
1240
+ instrumented[typedKey] = fn;
1241
+ continue;
1242
+ }
1243
+ const fnOptions = {
1244
+ ...tracingOptions,
1245
+ ...tracingOptions.overrides?.[key],
1246
+ // If no explicit name, use key as function name
1247
+ name: tracingOptions.overrides?.[key]?.name
1248
+ };
1249
+ const boundFn = fn.bind(functions);
1250
+ const fnFactory = (ctx2) => {
1251
+ return boundFn;
1252
+ };
1253
+ instrumented[typedKey] = wrapFactoryWithTracing(
1254
+ fnFactory,
1255
+ fnOptions,
1256
+ key
1257
+ );
1258
+ }
1259
+ return instrumented;
1260
+ }
1261
+ function span(options, fn) {
1262
+ const config = chunkY4Y2S7BM_cjs.getConfig();
1263
+ const tracer = config.tracer;
1264
+ const { name, attributes } = options;
1265
+ const executeSpan = (span2) => {
1266
+ return chunkYLPNXZFI_cjs.runInOperationContext(name, () => {
1267
+ try {
1268
+ if (attributes) {
1269
+ for (const [key, value] of Object.entries(attributes)) {
1270
+ span2.setAttribute(key, value);
1271
+ }
1272
+ }
1273
+ const result2 = fn(span2);
1274
+ if (result2 instanceof Promise) {
1275
+ return result2.then((resolved) => {
1276
+ span2.setStatus({ code: api.SpanStatusCode.OK });
1277
+ span2.end();
1278
+ return resolved;
1279
+ }).catch((error) => {
1280
+ const errorMessage = error instanceof Error ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH) : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);
1281
+ span2.setAttribute("error.message", errorMessage);
1282
+ span2.setStatus({
1283
+ code: api.SpanStatusCode.ERROR,
1284
+ message: errorMessage
1285
+ });
1286
+ span2.recordException(
1287
+ error instanceof Error ? error : new Error(String(error))
1288
+ );
1289
+ span2.end();
1290
+ throw error;
1291
+ });
1292
+ } else {
1293
+ span2.setStatus({ code: api.SpanStatusCode.OK });
1294
+ span2.end();
1295
+ return result2;
1296
+ }
1297
+ } catch (error) {
1298
+ const errorMessage = error instanceof Error ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH) : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);
1299
+ span2.setAttribute("error.message", errorMessage);
1300
+ span2.setStatus({
1301
+ code: api.SpanStatusCode.ERROR,
1302
+ message: errorMessage
1303
+ });
1304
+ span2.recordException(
1305
+ error instanceof Error ? error : new Error(String(error))
1306
+ );
1307
+ span2.end();
1308
+ throw error;
1309
+ }
1310
+ });
1311
+ };
1312
+ const result = tracer.startActiveSpan(name, executeSpan);
1313
+ if (result instanceof Promise) {
1314
+ return result;
1315
+ }
1316
+ return result;
1317
+ }
1318
+ async function withNewContext(options) {
1319
+ const { fn } = options;
1320
+ const config = chunkY4Y2S7BM_cjs.getConfig();
1321
+ const tracer = config.tracer;
1322
+ return tracer.startActiveSpan("root", { root: true }, async (span2) => {
1323
+ try {
1324
+ const result = await fn();
1325
+ span2.setStatus({ code: api.SpanStatusCode.OK });
1326
+ return result;
1327
+ } catch (error) {
1328
+ span2.recordException(
1329
+ error instanceof Error ? error : new Error(String(error))
1330
+ );
1331
+ span2.setStatus({ code: api.SpanStatusCode.ERROR });
1332
+ throw error;
1333
+ } finally {
1334
+ span2.end();
1335
+ }
1336
+ });
1337
+ }
1338
+ function withBaggage(options) {
1339
+ const { baggage: baggageEntries, fn } = options;
1340
+ const currentContext = api.context.active();
1341
+ let updatedBaggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
1342
+ for (const [key, value] of Object.entries(baggageEntries)) {
1343
+ updatedBaggage = updatedBaggage.setEntry(key, { value });
1344
+ }
1345
+ const newContext = api.propagation.setBaggage(currentContext, updatedBaggage);
1346
+ return api.context.with(newContext, fn);
1347
+ }
1348
+
1349
+ exports.ctx = ctx;
1350
+ exports.getEventQueue = getEventQueue;
1351
+ exports.instrument = instrument;
1352
+ exports.resetEventQueue = resetEventQueue;
1353
+ exports.span = span;
1354
+ exports.trace = trace2;
1355
+ exports.track = track;
1356
+ exports.withBaggage = withBaggage;
1357
+ exports.withNewContext = withNewContext;
1358
+ exports.withTracing = withTracing;
1359
+ //# sourceMappingURL=chunk-WBWNM6LB.cjs.map
1360
+ //# sourceMappingURL=chunk-WBWNM6LB.cjs.map