autotel 2.26.3 → 3.0.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 (144) hide show
  1. package/README.md +29 -19
  2. package/dist/attributes.d.cts +3 -3
  3. package/dist/attributes.d.ts +3 -3
  4. package/dist/business-baggage.d.cts +1 -1
  5. package/dist/business-baggage.d.ts +1 -1
  6. package/dist/{chunk-YN7USLHW.js → chunk-3QMFLJHJ.js} +11 -10
  7. package/dist/chunk-3QMFLJHJ.js.map +1 -0
  8. package/dist/{chunk-BJ2XPN77.js → chunk-4DAG3RFS.js} +4 -4
  9. package/dist/{chunk-BJ2XPN77.js.map → chunk-4DAG3RFS.js.map} +1 -1
  10. package/dist/chunk-4P6ZOARG.cjs +33 -0
  11. package/dist/chunk-4P6ZOARG.cjs.map +1 -0
  12. package/dist/{chunk-U54FTVFH.js → chunk-7HNQYHK4.js} +3 -3
  13. package/dist/{chunk-U54FTVFH.js.map → chunk-7HNQYHK4.js.map} +1 -1
  14. package/dist/chunk-CJ4PD2TZ.cjs +1207 -0
  15. package/dist/chunk-CJ4PD2TZ.cjs.map +1 -0
  16. package/dist/{chunk-HPUGKUMZ.js → chunk-DAAJLUTO.js} +13 -640
  17. package/dist/chunk-DAAJLUTO.js.map +1 -0
  18. package/dist/{chunk-B3ZHLLMP.js → chunk-DSMSIVTG.js} +2 -2
  19. package/dist/chunk-DSMSIVTG.js.map +1 -0
  20. package/dist/{chunk-6YGUN7IY.cjs → chunk-DWOBIBLY.cjs} +18 -17
  21. package/dist/chunk-DWOBIBLY.cjs.map +1 -0
  22. package/dist/{chunk-QC5MNKVF.js → chunk-IUDXKLS4.js} +13 -12
  23. package/dist/chunk-IUDXKLS4.js.map +1 -0
  24. package/dist/{chunk-OBWXM4NN.cjs → chunk-KHGA4OST.cjs} +15 -14
  25. package/dist/chunk-KHGA4OST.cjs.map +1 -0
  26. package/dist/chunk-KIL5CUN6.js +31 -0
  27. package/dist/chunk-KIL5CUN6.js.map +1 -0
  28. package/dist/{chunk-YEVCD6DR.cjs → chunk-L7JDUDJD.cjs} +7 -7
  29. package/dist/{chunk-YEVCD6DR.cjs.map → chunk-L7JDUDJD.cjs.map} +1 -1
  30. package/dist/{chunk-UTZR7P7E.cjs → chunk-MOK3E54E.cjs} +29 -659
  31. package/dist/chunk-MOK3E54E.cjs.map +1 -0
  32. package/dist/{chunk-GML3FBOT.cjs → chunk-NCSMD3TK.cjs} +2 -2
  33. package/dist/chunk-NCSMD3TK.cjs.map +1 -0
  34. package/dist/chunk-QG3U5ONP.js +1183 -0
  35. package/dist/chunk-QG3U5ONP.js.map +1 -0
  36. package/dist/chunk-SEO6NAQT.js +14 -0
  37. package/dist/chunk-SEO6NAQT.js.map +1 -0
  38. package/dist/chunk-VQTCQKHQ.cjs +17 -0
  39. package/dist/chunk-VQTCQKHQ.cjs.map +1 -0
  40. package/dist/{chunk-WZOKY3PW.cjs → chunk-ZSABTI3C.cjs} +8 -8
  41. package/dist/{chunk-WZOKY3PW.cjs.map → chunk-ZSABTI3C.cjs.map} +1 -1
  42. package/dist/correlation-id.cjs +22 -10
  43. package/dist/correlation-id.js +14 -2
  44. package/dist/decorators.cjs +5 -6
  45. package/dist/decorators.cjs.map +1 -1
  46. package/dist/decorators.d.cts +1 -1
  47. package/dist/decorators.d.ts +1 -1
  48. package/dist/decorators.js +4 -5
  49. package/dist/decorators.js.map +1 -1
  50. package/dist/event.cjs +6 -7
  51. package/dist/event.js +3 -4
  52. package/dist/functional.cjs +11 -12
  53. package/dist/functional.d.cts +1 -1
  54. package/dist/functional.d.ts +1 -1
  55. package/dist/functional.js +4 -5
  56. package/dist/http.cjs +13 -2
  57. package/dist/http.cjs.map +1 -1
  58. package/dist/http.js +12 -1
  59. package/dist/http.js.map +1 -1
  60. package/dist/index.cjs +134 -243
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +23 -8
  63. package/dist/index.d.ts +23 -8
  64. package/dist/index.js +52 -176
  65. package/dist/index.js.map +1 -1
  66. package/dist/messaging-adapters.d.cts +1 -1
  67. package/dist/messaging-adapters.d.ts +1 -1
  68. package/dist/messaging-testing.d.cts +1 -1
  69. package/dist/messaging-testing.d.ts +1 -1
  70. package/dist/messaging.cjs +9 -9
  71. package/dist/messaging.d.cts +1 -1
  72. package/dist/messaging.d.ts +1 -1
  73. package/dist/messaging.js +6 -6
  74. package/dist/semantic-helpers.cjs +9 -10
  75. package/dist/semantic-helpers.d.cts +1 -1
  76. package/dist/semantic-helpers.d.ts +1 -1
  77. package/dist/semantic-helpers.js +5 -6
  78. package/dist/{trace-context-t5X1AP-e.d.ts → trace-context-DbGKd1Rn.d.cts} +18 -5
  79. package/dist/{trace-context-t5X1AP-e.d.cts → trace-context-DbGKd1Rn.d.ts} +18 -5
  80. package/dist/trace-helpers.cjs +13 -13
  81. package/dist/trace-helpers.d.cts +2 -2
  82. package/dist/trace-helpers.d.ts +2 -2
  83. package/dist/trace-helpers.js +1 -1
  84. package/dist/{utils-CbUkl8r1.d.cts → utils-BahBCFtJ.d.cts} +1 -1
  85. package/dist/{utils-Buel3cj0.d.ts → utils-CLKwaUlG.d.ts} +1 -1
  86. package/dist/webhook.cjs +19 -10
  87. package/dist/webhook.cjs.map +1 -1
  88. package/dist/webhook.d.cts +1 -1
  89. package/dist/webhook.d.ts +1 -1
  90. package/dist/webhook.js +18 -9
  91. package/dist/webhook.js.map +1 -1
  92. package/dist/workflow-distributed.cjs +23 -19
  93. package/dist/workflow-distributed.cjs.map +1 -1
  94. package/dist/workflow-distributed.d.cts +1 -1
  95. package/dist/workflow-distributed.d.ts +1 -1
  96. package/dist/workflow-distributed.js +21 -17
  97. package/dist/workflow-distributed.js.map +1 -1
  98. package/dist/workflow.cjs +10 -10
  99. package/dist/workflow.d.cts +1 -1
  100. package/dist/workflow.d.ts +1 -1
  101. package/dist/workflow.js +6 -6
  102. package/package.json +1 -1
  103. package/skills/autotel-core/SKILL.md +2 -0
  104. package/skills/autotel-events/SKILL.md +2 -0
  105. package/skills/autotel-frameworks/SKILL.md +2 -0
  106. package/skills/autotel-instrumentation/SKILL.md +2 -0
  107. package/skills/autotel-request-logging/SKILL.md +2 -0
  108. package/skills/autotel-structured-errors/SKILL.md +2 -0
  109. package/src/correlated-events.test.ts +151 -0
  110. package/src/correlated-events.ts +47 -0
  111. package/src/functional.ts +2 -0
  112. package/src/gen-ai-events.ts +14 -5
  113. package/src/index.ts +20 -4
  114. package/src/messaging.ts +10 -9
  115. package/src/request-logger.ts +4 -3
  116. package/src/structured-error.test.ts +83 -1
  117. package/src/structured-error.ts +9 -2
  118. package/src/trace-context.ts +39 -11
  119. package/src/trace-helpers.ts +2 -2
  120. package/src/trace-hybrid.test.ts +42 -0
  121. package/src/trace-hybrid.ts +37 -0
  122. package/src/webhook.ts +16 -7
  123. package/src/workflow-distributed.ts +18 -13
  124. package/src/workflow.ts +7 -6
  125. package/dist/chunk-6YGUN7IY.cjs.map +0 -1
  126. package/dist/chunk-B3ZHLLMP.js.map +0 -1
  127. package/dist/chunk-BBBWDIYQ.js +0 -211
  128. package/dist/chunk-BBBWDIYQ.js.map +0 -1
  129. package/dist/chunk-D5LMF53P.cjs +0 -150
  130. package/dist/chunk-D5LMF53P.cjs.map +0 -1
  131. package/dist/chunk-GML3FBOT.cjs.map +0 -1
  132. package/dist/chunk-HPUGKUMZ.js.map +0 -1
  133. package/dist/chunk-HZ3FYBJG.cjs +0 -217
  134. package/dist/chunk-HZ3FYBJG.cjs.map +0 -1
  135. package/dist/chunk-JSNUWSBH.cjs +0 -62
  136. package/dist/chunk-JSNUWSBH.cjs.map +0 -1
  137. package/dist/chunk-OBWXM4NN.cjs.map +0 -1
  138. package/dist/chunk-QC5MNKVF.js.map +0 -1
  139. package/dist/chunk-S4OFEXLA.js +0 -53
  140. package/dist/chunk-S4OFEXLA.js.map +0 -1
  141. package/dist/chunk-UTZR7P7E.cjs.map +0 -1
  142. package/dist/chunk-WD4RP6IV.js +0 -146
  143. package/dist/chunk-WD4RP6IV.js.map +0 -1
  144. package/dist/chunk-YN7USLHW.js.map +0 -1
@@ -0,0 +1,1183 @@
1
+ import { getValidationConfig, isInitialized, warnIfNotInitialized, getConfig, getEventsConfig, getLogger } from './chunk-W35FVJBC.js';
2
+ import { getConfig as getConfig$1 } from './chunk-J5QENANM.js';
3
+ import { SpanStatusCode, trace, context, propagation } from '@opentelemetry/api';
4
+ import { AsyncLocalStorage } from 'async_hooks';
5
+
6
+ // src/flatten-attributes.ts
7
+ function toAttributeValue(value) {
8
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
9
+ return value;
10
+ }
11
+ if (Array.isArray(value)) {
12
+ if (value.every((v) => typeof v === "string") || value.every((v) => typeof v === "number") || value.every((v) => typeof v === "boolean")) {
13
+ return value;
14
+ }
15
+ try {
16
+ return JSON.stringify(value);
17
+ } catch {
18
+ return "<serialization-failed>";
19
+ }
20
+ }
21
+ if (value instanceof Date) {
22
+ return value.toISOString();
23
+ }
24
+ if (value instanceof Error) {
25
+ return value.message;
26
+ }
27
+ return void 0;
28
+ }
29
+ function flattenToAttributes(fields, prefix = "") {
30
+ const out = {};
31
+ const seen = /* @__PURE__ */ new WeakSet();
32
+ function flatten(obj, currentPrefix) {
33
+ for (const [key, value] of Object.entries(obj)) {
34
+ if (value == null) continue;
35
+ const nextKey = currentPrefix ? `${currentPrefix}.${key}` : key;
36
+ const attr = toAttributeValue(value);
37
+ if (attr !== void 0) {
38
+ out[nextKey] = attr;
39
+ continue;
40
+ }
41
+ if (typeof value === "object" && value.constructor === Object) {
42
+ if (seen.has(value)) {
43
+ out[nextKey] = "<circular-reference>";
44
+ continue;
45
+ }
46
+ seen.add(value);
47
+ flatten(value, nextKey);
48
+ continue;
49
+ }
50
+ try {
51
+ out[nextKey] = JSON.stringify(value);
52
+ } catch {
53
+ out[nextKey] = "<serialization-failed>";
54
+ }
55
+ }
56
+ }
57
+ flatten(fields, prefix);
58
+ return out;
59
+ }
60
+
61
+ // src/structured-error.ts
62
+ var internalKey = /* @__PURE__ */ Symbol.for("autotel.error.internal");
63
+ function createStructuredError(input) {
64
+ const error = new Error(input.message, {
65
+ cause: input.cause
66
+ });
67
+ error.name = input.name ?? "StructuredError";
68
+ if (input.why !== void 0) error.why = input.why;
69
+ if (input.fix !== void 0) error.fix = input.fix;
70
+ if (input.link !== void 0) error.link = input.link;
71
+ if (input.code !== void 0) error.code = input.code;
72
+ if (input.status !== void 0) error.status = input.status;
73
+ if (input.details !== void 0) error.details = input.details;
74
+ if (input.internal !== void 0) {
75
+ Object.defineProperty(error, internalKey, {
76
+ value: input.internal,
77
+ enumerable: false,
78
+ writable: false,
79
+ configurable: true
80
+ });
81
+ }
82
+ Object.defineProperty(error, "internal", {
83
+ get() {
84
+ return this[internalKey];
85
+ },
86
+ enumerable: false,
87
+ configurable: true
88
+ });
89
+ error.toString = () => {
90
+ const lines = [`${error.name}: ${error.message}`];
91
+ if (error.why) lines.push(` Why: ${error.why}`);
92
+ if (error.fix) lines.push(` Fix: ${error.fix}`);
93
+ if (error.link) lines.push(` Link: ${error.link}`);
94
+ if (error.code !== void 0) lines.push(` Code: ${error.code}`);
95
+ if (error.status !== void 0) lines.push(` Status: ${error.status}`);
96
+ if (error.cause) {
97
+ const cause = error.cause;
98
+ lines.push(` Caused by: ${cause.name}: ${cause.message}`);
99
+ }
100
+ return lines.join("\n");
101
+ };
102
+ return error;
103
+ }
104
+ function structuredErrorToJSON(error) {
105
+ const result = {
106
+ name: error.name,
107
+ message: error.message
108
+ };
109
+ if (error.status !== void 0) result.status = error.status;
110
+ if (error.why || error.fix || error.link) {
111
+ result.data = {
112
+ ...error.why && { why: error.why },
113
+ ...error.fix && { fix: error.fix },
114
+ ...error.link && { link: error.link }
115
+ };
116
+ }
117
+ if (error.code !== void 0) result.code = error.code;
118
+ if (error.details) result.details = error.details;
119
+ if (error.cause instanceof Error) {
120
+ result.cause = { name: error.cause.name, message: error.cause.message };
121
+ }
122
+ return result;
123
+ }
124
+ function getStructuredErrorAttributes(error) {
125
+ const structured = error;
126
+ const attributes = {
127
+ "error.type": error.name || "Error",
128
+ "error.message": error.message
129
+ };
130
+ if (error.stack) attributes["error.stack"] = error.stack;
131
+ if (structured.why) attributes["error.why"] = structured.why;
132
+ if (structured.fix) attributes["error.fix"] = structured.fix;
133
+ if (structured.link) attributes["error.link"] = structured.link;
134
+ if (structured.code !== void 0) {
135
+ attributes["error.code"] = typeof structured.code === "string" ? structured.code : String(structured.code);
136
+ }
137
+ if (structured.status !== void 0) {
138
+ attributes["error.status"] = structured.status;
139
+ }
140
+ if (structured.details) {
141
+ Object.assign(
142
+ attributes,
143
+ flattenToAttributes(structured.details, "error.details")
144
+ );
145
+ }
146
+ return attributes;
147
+ }
148
+ function recordStructuredError(ctx, error) {
149
+ const maybeRecordException = ctx.recordException;
150
+ if (typeof maybeRecordException === "function") {
151
+ maybeRecordException(error);
152
+ }
153
+ ctx.setStatus({
154
+ code: SpanStatusCode.ERROR,
155
+ message: error.message
156
+ });
157
+ ctx.setAttributes(getStructuredErrorAttributes(error));
158
+ }
159
+
160
+ // src/rate-limiter.ts
161
+ var TokenBucketRateLimiter = class {
162
+ tokens;
163
+ maxTokens;
164
+ refillRate;
165
+ // tokens per millisecond
166
+ lastRefill;
167
+ constructor(config) {
168
+ this.maxTokens = config.burstCapacity || config.maxEventsPerSecond * 2;
169
+ this.tokens = this.maxTokens;
170
+ this.refillRate = config.maxEventsPerSecond / 1e3;
171
+ this.lastRefill = Date.now();
172
+ }
173
+ /**
174
+ * Try to consume a token (allow an event)
175
+ * Returns true if allowed, false if rate limit exceeded
176
+ */
177
+ tryConsume(count = 1) {
178
+ this.refill();
179
+ if (this.tokens >= count) {
180
+ this.tokens -= count;
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+ /**
186
+ * Wait until a token is available (async rate limiting)
187
+ * Returns a promise that resolves when the event can be processed
188
+ */
189
+ async waitForToken(count = 1) {
190
+ this.refill();
191
+ if (this.tokens >= count) {
192
+ this.tokens -= count;
193
+ return;
194
+ }
195
+ const tokensNeeded = count - this.tokens;
196
+ const waitMs = Math.ceil(tokensNeeded / this.refillRate);
197
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
198
+ return this.waitForToken(count);
199
+ }
200
+ /**
201
+ * Refill tokens based on elapsed time
202
+ */
203
+ refill() {
204
+ const now = Date.now();
205
+ const elapsed = now - this.lastRefill;
206
+ const tokensToAdd = elapsed * this.refillRate;
207
+ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
208
+ this.lastRefill = now;
209
+ }
210
+ /**
211
+ * Get current available tokens (for testing/debugging)
212
+ */
213
+ getAvailableTokens() {
214
+ this.refill();
215
+ return Math.floor(this.tokens);
216
+ }
217
+ /**
218
+ * Reset the rate limiter (for testing)
219
+ */
220
+ reset() {
221
+ this.tokens = this.maxTokens;
222
+ this.lastRefill = Date.now();
223
+ }
224
+ };
225
+
226
+ // src/event-queue.ts
227
+ var DEFAULT_CONFIG = {
228
+ maxSize: 5e4,
229
+ batchSize: 100,
230
+ flushInterval: 1e4,
231
+ maxRetries: 3,
232
+ rateLimit: {
233
+ maxEventsPerSecond: 100,
234
+ burstCapacity: 200
235
+ }
236
+ };
237
+ function getSubscriberName(subscriber) {
238
+ if (subscriber.name) {
239
+ return subscriber.name.toLowerCase();
240
+ }
241
+ const className = subscriber.constructor?.name || "unknown";
242
+ return className.replace(/Subscriber$/i, "").toLowerCase();
243
+ }
244
+ var EventQueue = class {
245
+ queue = [];
246
+ flushTimer = null;
247
+ config;
248
+ subscribers;
249
+ rateLimiter;
250
+ flushPromise = null;
251
+ isShuttingDown = false;
252
+ // Metrics
253
+ metrics = null;
254
+ // Observable callback cleanup functions
255
+ observableCleanups = [];
256
+ // Subscriber health tracking (for observable gauges)
257
+ subscriberHealthy = /* @__PURE__ */ new Map();
258
+ constructor(subscribers, config) {
259
+ this.subscribers = subscribers;
260
+ this.config = { ...DEFAULT_CONFIG, ...config };
261
+ this.rateLimiter = this.config.rateLimit ? new TokenBucketRateLimiter(this.config.rateLimit) : null;
262
+ for (const subscriber of subscribers) {
263
+ const name = getSubscriberName(subscriber);
264
+ this.subscriberHealthy.set(name, true);
265
+ }
266
+ this.initMetrics();
267
+ }
268
+ /**
269
+ * Initialize OTel metrics for queue observability
270
+ */
271
+ initMetrics() {
272
+ const runtimeConfig = getConfig$1();
273
+ const meter = runtimeConfig.meter;
274
+ const queueSize = meter.createObservableGauge(
275
+ "autotel.event_delivery.queue.size",
276
+ {
277
+ description: "Current number of events in the delivery queue",
278
+ unit: "count"
279
+ }
280
+ );
281
+ const queueSizeCallback = (observableResult) => {
282
+ observableResult.observe(this.queue.length);
283
+ };
284
+ queueSize.addCallback(queueSizeCallback);
285
+ this.observableCleanups.push(
286
+ () => queueSize.removeCallback(queueSizeCallback)
287
+ );
288
+ const oldestAge = meter.createObservableGauge(
289
+ "autotel.event_delivery.queue.oldest_age_ms",
290
+ {
291
+ description: "Age of the oldest event in the queue in milliseconds",
292
+ unit: "ms"
293
+ }
294
+ );
295
+ const oldestAgeCallback = (observableResult) => {
296
+ if (this.queue.length > 0) {
297
+ const oldest = this.queue[0];
298
+ const ageMs = Date.now() - oldest.timestamp;
299
+ observableResult.observe(ageMs);
300
+ } else {
301
+ observableResult.observe(0);
302
+ }
303
+ };
304
+ oldestAge.addCallback(oldestAgeCallback);
305
+ this.observableCleanups.push(
306
+ () => oldestAge.removeCallback(oldestAgeCallback)
307
+ );
308
+ const delivered = meter.createCounter(
309
+ "autotel.event_delivery.queue.delivered",
310
+ {
311
+ description: "Number of events successfully delivered to subscribers",
312
+ unit: "count"
313
+ }
314
+ );
315
+ const failed = meter.createCounter("autotel.event_delivery.queue.failed", {
316
+ description: "Number of events that failed delivery after all retry attempts",
317
+ unit: "count"
318
+ });
319
+ const dropped = meter.createCounter(
320
+ "autotel.event_delivery.queue.dropped",
321
+ {
322
+ description: "Number of events dropped from the queue",
323
+ unit: "count"
324
+ }
325
+ );
326
+ const latency = meter.createHistogram(
327
+ "autotel.event_delivery.queue.latency_ms",
328
+ {
329
+ description: "Event delivery latency from enqueue to successful send",
330
+ unit: "ms"
331
+ }
332
+ );
333
+ const subscriberHealth = meter.createObservableGauge(
334
+ "autotel.event_delivery.subscriber.health",
335
+ {
336
+ description: "Subscriber health status (1=healthy, 0=unhealthy)",
337
+ unit: "1"
338
+ }
339
+ );
340
+ const subscriberHealthCallback = (observableResult) => {
341
+ for (const [subscriberName, isHealthy] of this.subscriberHealthy) {
342
+ observableResult.observe(isHealthy ? 1 : 0, {
343
+ subscriber: subscriberName
344
+ });
345
+ }
346
+ };
347
+ subscriberHealth.addCallback(subscriberHealthCallback);
348
+ this.observableCleanups.push(
349
+ () => subscriberHealth.removeCallback(subscriberHealthCallback)
350
+ );
351
+ this.metrics = {
352
+ queueSize,
353
+ oldestAge,
354
+ delivered,
355
+ failed,
356
+ dropped,
357
+ latency,
358
+ subscriberHealth
359
+ };
360
+ }
361
+ /**
362
+ * Record a dropped event with reason and emit debug breadcrumb
363
+ */
364
+ recordDropped(reason, event, subscriberName) {
365
+ const attrs = { reason };
366
+ if (subscriberName) {
367
+ attrs.subscriber = subscriberName;
368
+ }
369
+ this.metrics?.dropped.add(1, attrs);
370
+ const logLevel = reason === "payload_invalid" ? "error" : "warn";
371
+ const logger = getLogger();
372
+ if (logLevel === "error") {
373
+ logger.error(
374
+ {
375
+ eventName: event?.name,
376
+ subscriber: subscriberName,
377
+ reason,
378
+ correlationId: event?._correlationId,
379
+ traceId: event?._traceId
380
+ },
381
+ `[autotel] Event dropped: ${reason}`
382
+ );
383
+ } else {
384
+ logger.warn(
385
+ {
386
+ eventName: event?.name,
387
+ subscriber: subscriberName,
388
+ reason,
389
+ correlationId: event?._correlationId,
390
+ traceId: event?._traceId
391
+ },
392
+ `[autotel] Event dropped: ${reason}`
393
+ );
394
+ }
395
+ }
396
+ /**
397
+ * Record permanent delivery failure (after all retries exhausted)
398
+ * Increments failed counter and logs error
399
+ */
400
+ recordFailed(event, subscriberName, error) {
401
+ this.metrics?.failed.add(1, { subscriber: subscriberName });
402
+ this.subscriberHealthy.set(subscriberName, false);
403
+ getLogger().error(
404
+ {
405
+ eventName: event.name,
406
+ subscriber: subscriberName,
407
+ correlationId: event._correlationId,
408
+ traceId: event._traceId,
409
+ err: error
410
+ },
411
+ `[autotel] Event delivery failed after all retries`
412
+ );
413
+ }
414
+ /**
415
+ * Mark subscriber as unhealthy on transient failure (without incrementing failed counter)
416
+ * Used during retry attempts - only recordFailed should increment the counter
417
+ */
418
+ markSubscriberUnhealthy(subscriberName) {
419
+ this.subscriberHealthy.set(subscriberName, false);
420
+ }
421
+ /**
422
+ * Record successful delivery
423
+ */
424
+ recordDelivered(event, subscriberName, startTime) {
425
+ const latencyMs = Date.now() - startTime;
426
+ this.metrics?.delivered.add(1, { subscriber: subscriberName });
427
+ this.metrics?.latency.record(latencyMs, { subscriber: subscriberName });
428
+ this.subscriberHealthy.set(subscriberName, true);
429
+ }
430
+ /**
431
+ * Enqueue an event for sending
432
+ *
433
+ * Backpressure policy:
434
+ * - Drops oldest event and logs warning if queue is full (same behavior in all environments)
435
+ */
436
+ enqueue(event) {
437
+ if (this.isShuttingDown) {
438
+ this.recordDropped("shutdown", event);
439
+ return;
440
+ }
441
+ if (this.queue.length >= this.config.maxSize) {
442
+ const droppedEvent = this.queue.shift();
443
+ this.recordDropped("rate_limit", droppedEvent);
444
+ getLogger().warn(
445
+ {
446
+ droppedEvent: droppedEvent?.name
447
+ },
448
+ `[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.`
449
+ );
450
+ }
451
+ const enrichedEvent = {
452
+ ...event,
453
+ _correlationId: event._correlationId || getOrCreateCorrelationId()
454
+ };
455
+ this.queue.push(enrichedEvent);
456
+ this.scheduleBatchFlush();
457
+ }
458
+ /**
459
+ * Schedule a batch flush if not already scheduled
460
+ */
461
+ scheduleBatchFlush() {
462
+ if (this.flushTimer || this.flushPromise) return;
463
+ this.flushTimer = setTimeout(() => {
464
+ this.flushTimer = null;
465
+ void this.flushBatch();
466
+ }, this.config.flushInterval);
467
+ }
468
+ /**
469
+ * Flush a batch of events
470
+ * Uses promise-based concurrency control to prevent race conditions
471
+ */
472
+ async flushBatch() {
473
+ if (this.queue.length === 0) return;
474
+ if (this.flushPromise) {
475
+ await this.flushPromise;
476
+ return;
477
+ }
478
+ this.flushPromise = this.doFlushBatch();
479
+ try {
480
+ await this.flushPromise;
481
+ } finally {
482
+ this.flushPromise = null;
483
+ if (this.queue.length > 0) {
484
+ this.scheduleBatchFlush();
485
+ }
486
+ }
487
+ }
488
+ /**
489
+ * Internal flush implementation
490
+ */
491
+ async doFlushBatch() {
492
+ const batch = this.queue.splice(0, this.config.batchSize);
493
+ await this.sendWithRetry(batch, this.config.maxRetries);
494
+ }
495
+ /**
496
+ * Send events with exponential backoff retry
497
+ * Tracks per-event, per-subscriber failures so failed counter reflects actual failed deliveries.
498
+ * On retry, only failed (event, subscriber) pairs are re-sent to avoid double-counting delivered.
499
+ */
500
+ async sendWithRetry(events, retriesLeft, subscribersByEventIndex) {
501
+ const failedDeliveries = await this.sendToSubscribers(
502
+ events,
503
+ subscribersByEventIndex
504
+ );
505
+ if (failedDeliveries.length > 0) {
506
+ if (retriesLeft > 0) {
507
+ const failedEventIndices = new Set(
508
+ failedDeliveries.map((f) => f.eventIndex)
509
+ );
510
+ const failedEventIndicesOrdered = [...failedEventIndices].sort(
511
+ (a, b) => a - b
512
+ );
513
+ const eventsToRetry = failedEventIndicesOrdered.map(
514
+ (i) => events[i]
515
+ );
516
+ const failedSubscribersByRetryIndex = /* @__PURE__ */ new Map();
517
+ for (let j = 0; j < failedEventIndicesOrdered.length; j++) {
518
+ const origIndex = failedEventIndicesOrdered[j];
519
+ const set = /* @__PURE__ */ new Set();
520
+ for (const { eventIndex, subscriberName } of failedDeliveries) {
521
+ if (eventIndex === origIndex) set.add(subscriberName);
522
+ }
523
+ failedSubscribersByRetryIndex.set(j, set);
524
+ }
525
+ const delay = Math.pow(2, this.config.maxRetries - retriesLeft) * 1e3;
526
+ await new Promise((resolve) => setTimeout(resolve, delay));
527
+ return this.sendWithRetry(
528
+ eventsToRetry,
529
+ retriesLeft - 1,
530
+ failedSubscribersByRetryIndex
531
+ );
532
+ } else {
533
+ for (const { eventIndex, subscriberName, error } of failedDeliveries) {
534
+ const event = events[eventIndex];
535
+ if (event) this.recordFailed(event, subscriberName, error);
536
+ }
537
+ const failedSubscriberNames = [
538
+ ...new Set(failedDeliveries.map((f) => f.subscriberName))
539
+ ];
540
+ getLogger().error(
541
+ {
542
+ failedSubscribers: failedSubscriberNames,
543
+ retriesAttempted: this.config.maxRetries
544
+ },
545
+ "[autotel] Failed to send events after retries"
546
+ );
547
+ }
548
+ }
549
+ }
550
+ /**
551
+ * Send events to configured subscribers with rate limiting and metrics.
552
+ * When subscribersByEventIndex is provided (retry path), only those subscribers are tried per event.
553
+ * Returns per-event, per-subscriber failures (empty if all succeeded).
554
+ */
555
+ async sendToSubscribers(events, subscribersByEventIndex) {
556
+ const failedDeliveries = [];
557
+ const sendOne = async (event, eventIndex) => {
558
+ const subscriberNames = subscribersByEventIndex?.get(eventIndex);
559
+ const failures = await this.sendEventToSubscribers(
560
+ event,
561
+ subscriberNames ?? void 0
562
+ );
563
+ for (const failure of failures) {
564
+ failedDeliveries.push({
565
+ eventIndex,
566
+ subscriberName: failure.subscriberName,
567
+ error: failure.error
568
+ });
569
+ }
570
+ };
571
+ if (!this.rateLimiter) {
572
+ for (let i = 0; i < events.length; i++) {
573
+ const event = events[i];
574
+ if (event) await sendOne(event, i);
575
+ }
576
+ return failedDeliveries;
577
+ }
578
+ for (let i = 0; i < events.length; i++) {
579
+ await this.rateLimiter.waitForToken();
580
+ const event = events[i];
581
+ if (event) await sendOne(event, i);
582
+ }
583
+ return failedDeliveries;
584
+ }
585
+ /**
586
+ * Send a single event to subscribers.
587
+ * - When subscriberNames is undefined (initial attempt): send to all subscribers.
588
+ * - When subscriberNames is provided (retry): send only to those subscribers (never re-send to healthy ones).
589
+ * Returns list of subscribers that failed (empty if all succeeded).
590
+ */
591
+ async sendEventToSubscribers(event, subscriberNames) {
592
+ const startTime = event.timestamp;
593
+ const failures = [];
594
+ const subscribersToTry = subscriberNames === void 0 ? this.subscribers : this.subscribers.filter(
595
+ (s) => subscriberNames.has(getSubscriberName(s))
596
+ );
597
+ const results = await Promise.allSettled(
598
+ subscribersToTry.map(async (subscriber) => {
599
+ const subscriberName = getSubscriberName(subscriber);
600
+ try {
601
+ await subscriber.trackEvent(event.name, event.attributes, {
602
+ autotel: event.autotel
603
+ });
604
+ this.recordDelivered(event, subscriberName, startTime);
605
+ return { subscriberName, success: true };
606
+ } catch (error) {
607
+ this.markSubscriberUnhealthy(subscriberName);
608
+ return {
609
+ subscriberName,
610
+ success: false,
611
+ error: error instanceof Error ? error : void 0
612
+ };
613
+ }
614
+ })
615
+ );
616
+ for (const result of results) {
617
+ if (result.status === "fulfilled" && !result.value.success) {
618
+ failures.push({
619
+ subscriberName: result.value.subscriberName,
620
+ error: result.value.error
621
+ });
622
+ }
623
+ }
624
+ return failures;
625
+ }
626
+ /**
627
+ * Flush all remaining events. Queue remains usable after flush (e.g. for
628
+ * auto-flush at root span end). Use shutdown() when tearing down the queue.
629
+ */
630
+ async flush() {
631
+ if (this.flushTimer) {
632
+ clearTimeout(this.flushTimer);
633
+ this.flushTimer = null;
634
+ }
635
+ if (this.flushPromise) {
636
+ await this.flushPromise;
637
+ }
638
+ while (this.queue.length > 0) {
639
+ await this.doFlushBatch();
640
+ }
641
+ }
642
+ /**
643
+ * Flush remaining events and permanently disable the queue (reject new events).
644
+ * Use for process/SDK shutdown; use flush() for periodic or span-end drain.
645
+ */
646
+ async shutdown() {
647
+ this.isShuttingDown = true;
648
+ await this.flush();
649
+ }
650
+ /**
651
+ * Cleanup observable metric callbacks to prevent memory leaks
652
+ * Call this when destroying the EventQueue instance
653
+ */
654
+ cleanup() {
655
+ for (const cleanupFn of this.observableCleanups) {
656
+ try {
657
+ cleanupFn();
658
+ } catch {
659
+ }
660
+ }
661
+ this.observableCleanups = [];
662
+ }
663
+ /**
664
+ * Get queue size (for testing/debugging)
665
+ */
666
+ size() {
667
+ return this.queue.length;
668
+ }
669
+ /**
670
+ * Get subscriber health status (for testing/debugging)
671
+ */
672
+ getSubscriberHealth() {
673
+ return new Map(this.subscriberHealthy);
674
+ }
675
+ /**
676
+ * Check if a specific subscriber is healthy
677
+ */
678
+ isSubscriberHealthy(subscriberName) {
679
+ return this.subscriberHealthy.get(subscriberName.toLowerCase()) ?? true;
680
+ }
681
+ /**
682
+ * Manually mark a subscriber as healthy or unhealthy
683
+ * (used for circuit breaker integration)
684
+ */
685
+ setSubscriberHealth(subscriberName, healthy) {
686
+ this.subscriberHealthy.set(subscriberName.toLowerCase(), healthy);
687
+ }
688
+ };
689
+
690
+ // src/validation.ts
691
+ var DEFAULT_CONFIG2 = {
692
+ maxEventNameLength: 100,
693
+ maxAttributeKeyLength: 100,
694
+ maxAttributeValueLength: 1e3,
695
+ maxAttributeCount: 50,
696
+ maxNestingDepth: 3,
697
+ sensitivePatterns: [
698
+ /password/i,
699
+ /secret/i,
700
+ /token/i,
701
+ /api[_-]?key/i,
702
+ /access[_-]?key/i,
703
+ /private[_-]?key/i,
704
+ /auth/i,
705
+ /credential/i,
706
+ /ssn/i,
707
+ /credit[_-]?card/i
708
+ ]
709
+ };
710
+ var ValidationError = class extends Error {
711
+ constructor(message) {
712
+ super(message);
713
+ this.name = "ValidationError";
714
+ }
715
+ };
716
+ function validateEventName(eventName, config = DEFAULT_CONFIG2) {
717
+ if (typeof eventName !== "string") {
718
+ throw new ValidationError(
719
+ `Event name must be a string, got ${typeof eventName}`
720
+ );
721
+ }
722
+ const trimmed = eventName.trim();
723
+ if (trimmed.length === 0) {
724
+ throw new ValidationError("Event name cannot be empty");
725
+ }
726
+ if (trimmed.length > config.maxEventNameLength) {
727
+ throw new ValidationError(
728
+ `Event name too long (${trimmed.length} chars). Max: ${config.maxEventNameLength}`
729
+ );
730
+ }
731
+ if (!/^[a-zA-Z0-9._-]+$/.test(trimmed)) {
732
+ throw new ValidationError(
733
+ `Event name contains invalid characters: "${trimmed}". Use only letters, numbers, dots, underscores, and hyphens.`
734
+ );
735
+ }
736
+ return trimmed;
737
+ }
738
+ function validateAttributes(attributes, config = DEFAULT_CONFIG2) {
739
+ if (attributes === void 0 || attributes === null) {
740
+ return void 0;
741
+ }
742
+ if (typeof attributes !== "object" || Array.isArray(attributes)) {
743
+ throw new ValidationError("Attributes must be an object");
744
+ }
745
+ const keys = Object.keys(attributes);
746
+ if (keys.length > config.maxAttributeCount) {
747
+ throw new ValidationError(
748
+ `Too many attributes (${keys.length}). Max: ${config.maxAttributeCount}`
749
+ );
750
+ }
751
+ const sanitized = {};
752
+ for (const key of keys) {
753
+ if (key.length > config.maxAttributeKeyLength) {
754
+ throw new ValidationError(
755
+ `Attribute key too long: "${key.slice(0, 20)}..." (${key.length} chars). Max: ${config.maxAttributeKeyLength}`
756
+ );
757
+ }
758
+ const isSensitive = config.sensitivePatterns.some(
759
+ (pattern) => pattern.test(key)
760
+ );
761
+ if (isSensitive) {
762
+ sanitized[key] = "[REDACTED]";
763
+ continue;
764
+ }
765
+ const value = attributes[key];
766
+ sanitized[key] = sanitizeValue(value, config, 1);
767
+ }
768
+ return sanitized;
769
+ }
770
+ function sanitizeValue(value, config, depth) {
771
+ if (depth > config.maxNestingDepth) {
772
+ return "[MAX_DEPTH_EXCEEDED]";
773
+ }
774
+ if (value === null || value === void 0) {
775
+ return value;
776
+ }
777
+ if (typeof value === "string") {
778
+ if (value.length > config.maxAttributeValueLength) {
779
+ return value.slice(0, config.maxAttributeValueLength) + "...";
780
+ }
781
+ return value;
782
+ }
783
+ if (typeof value === "number" || typeof value === "boolean") {
784
+ return value;
785
+ }
786
+ if (Array.isArray(value)) {
787
+ return value.map((item) => sanitizeValue(item, config, depth + 1));
788
+ }
789
+ if (typeof value === "object") {
790
+ try {
791
+ JSON.stringify(value);
792
+ const sanitized = {};
793
+ for (const key in value) {
794
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
795
+ const isSensitive = config.sensitivePatterns.some(
796
+ (pattern) => pattern.test(key)
797
+ );
798
+ if (isSensitive) {
799
+ sanitized[key] = "[REDACTED]";
800
+ } else {
801
+ sanitized[key] = sanitizeValue(
802
+ value[key],
803
+ config,
804
+ depth + 1
805
+ );
806
+ }
807
+ }
808
+ }
809
+ return sanitized;
810
+ } catch {
811
+ return "[CIRCULAR]";
812
+ }
813
+ }
814
+ return `[${typeof value}]`;
815
+ }
816
+ function validateEvent(eventName, attributes, config) {
817
+ const fullConfig = { ...DEFAULT_CONFIG2, ...config };
818
+ return {
819
+ eventName: validateEventName(eventName, fullConfig),
820
+ attributes: validateAttributes(attributes, fullConfig)
821
+ };
822
+ }
823
+
824
+ // src/track.ts
825
+ var eventsQueue = null;
826
+ function buildAutotelContext(span) {
827
+ const eventsConfig = getEventsConfig();
828
+ const config = getConfig();
829
+ const correlationId = getOrCreateCorrelationId();
830
+ if (!eventsConfig?.includeTraceContext) {
831
+ return {
832
+ correlation_id: correlationId
833
+ };
834
+ }
835
+ const autotelContext = {
836
+ correlation_id: correlationId
837
+ };
838
+ const spanContext = span?.spanContext();
839
+ if (spanContext) {
840
+ autotelContext.trace_id = spanContext.traceId;
841
+ autotelContext.span_id = spanContext.spanId;
842
+ autotelContext.trace_flags = spanContext.traceFlags.toString(16).padStart(2, "0");
843
+ const traceState = spanContext.traceState;
844
+ if (traceState) {
845
+ try {
846
+ if (typeof traceState.serialize === "function") {
847
+ const traceStateStr = traceState.serialize();
848
+ if (traceStateStr) {
849
+ autotelContext.trace_state = traceStateStr;
850
+ }
851
+ }
852
+ } catch {
853
+ }
854
+ }
855
+ if (eventsConfig.traceUrl && config) {
856
+ const traceUrl = eventsConfig.traceUrl({
857
+ traceId: spanContext.traceId,
858
+ spanId: spanContext.spanId,
859
+ correlationId,
860
+ serviceName: config.service,
861
+ environment: config.environment
862
+ });
863
+ if (traceUrl) {
864
+ autotelContext.trace_url = traceUrl;
865
+ }
866
+ }
867
+ } else {
868
+ if (eventsConfig.traceUrl && config) {
869
+ const traceUrl = eventsConfig.traceUrl({
870
+ correlationId,
871
+ serviceName: config.service,
872
+ environment: config.environment
873
+ });
874
+ if (traceUrl) {
875
+ autotelContext.trace_url = traceUrl;
876
+ }
877
+ }
878
+ }
879
+ return autotelContext;
880
+ }
881
+ function getOrCreateQueue() {
882
+ if (!isInitialized()) {
883
+ warnIfNotInitialized("track()");
884
+ return null;
885
+ }
886
+ if (!eventsQueue) {
887
+ const config = getConfig();
888
+ if (!config?.subscribers || config.subscribers.length === 0) {
889
+ return null;
890
+ }
891
+ eventsQueue = new EventQueue(config.subscribers);
892
+ }
893
+ return eventsQueue;
894
+ }
895
+ function track(event, data) {
896
+ const queue = getOrCreateQueue();
897
+ if (!queue) return;
898
+ const validationConfig = getValidationConfig();
899
+ const validated = validateEvent(event, data, validationConfig || void 0);
900
+ const span = trace.getActiveSpan();
901
+ const enrichedData = span ? {
902
+ ...validated.attributes,
903
+ traceId: span.spanContext().traceId,
904
+ spanId: span.spanContext().spanId
905
+ } : validated.attributes;
906
+ const autotelContext = buildAutotelContext(span);
907
+ queue.enqueue({
908
+ name: validated.eventName,
909
+ attributes: enrichedData,
910
+ timestamp: Date.now(),
911
+ autotel: autotelContext
912
+ });
913
+ }
914
+ function getEventQueue() {
915
+ return eventsQueue;
916
+ }
917
+ function resetEventQueue() {
918
+ eventsQueue = null;
919
+ }
920
+
921
+ // src/trace-context.ts
922
+ var contextStorage = new AsyncLocalStorage();
923
+ function getContextStorage() {
924
+ return contextStorage;
925
+ }
926
+ function getActiveContextWithBaggage() {
927
+ const stored = contextStorage.getStore()?.value;
928
+ return stored ?? context.active();
929
+ }
930
+ function enterOrRun(storage, value) {
931
+ const existingStore = storage.getStore();
932
+ if (existingStore) {
933
+ existingStore.value = value;
934
+ return;
935
+ }
936
+ const boxedValue = { value };
937
+ try {
938
+ storage.enterWith(boxedValue);
939
+ } catch {
940
+ storage.run(boxedValue, () => {
941
+ });
942
+ }
943
+ }
944
+ function updateActiveContext(newContext) {
945
+ enterOrRun(contextStorage, newContext);
946
+ const contextWithManager = context;
947
+ const manager = contextWithManager._getContextManager?.();
948
+ if (!manager) return;
949
+ const asyncLocal = manager._asyncLocalStorage ?? void 0;
950
+ if (asyncLocal?.enterWith) {
951
+ asyncLocal.enterWith(newContext);
952
+ return;
953
+ }
954
+ if (typeof manager.with === "function") {
955
+ manager.with(newContext, () => {
956
+ });
957
+ }
958
+ }
959
+ function createTraceContext(span) {
960
+ const spanContext = span.spanContext();
961
+ const existingStored = contextStorage.getStore()?.value;
962
+ if (!existingStored) {
963
+ const activeContext = context.active();
964
+ enterOrRun(contextStorage, activeContext);
965
+ }
966
+ const baggageHelpers = {
967
+ getBaggage(key) {
968
+ const activeCtx = context.active();
969
+ let baggage = propagation.getBaggage(activeCtx);
970
+ if (!baggage) {
971
+ const storedContext = contextStorage.getStore()?.value;
972
+ if (storedContext) {
973
+ baggage = propagation.getBaggage(storedContext);
974
+ }
975
+ }
976
+ return baggage?.getEntry(key)?.value;
977
+ },
978
+ setBaggage(key, value) {
979
+ const activeCtx = context.active();
980
+ const storedContext = contextStorage.getStore()?.value;
981
+ const currentContext = storedContext ?? activeCtx;
982
+ const baggage = propagation.getBaggage(currentContext) ?? propagation.createBaggage();
983
+ const updated = baggage.setEntry(key, { value });
984
+ const newContext = propagation.setBaggage(currentContext, updated);
985
+ updateActiveContext(newContext);
986
+ return value;
987
+ },
988
+ deleteBaggage(key) {
989
+ const activeCtx = context.active();
990
+ const storedContext = contextStorage.getStore()?.value;
991
+ const currentContext = storedContext ?? activeCtx;
992
+ const baggage = propagation.getBaggage(currentContext);
993
+ if (baggage) {
994
+ const updated = baggage.removeEntry(key);
995
+ const newContext = propagation.setBaggage(currentContext, updated);
996
+ updateActiveContext(newContext);
997
+ }
998
+ },
999
+ getAllBaggage() {
1000
+ const activeCtx = context.active();
1001
+ let baggage = propagation.getBaggage(activeCtx);
1002
+ if (!baggage) {
1003
+ const storedContext = contextStorage.getStore()?.value;
1004
+ if (storedContext) {
1005
+ baggage = propagation.getBaggage(storedContext);
1006
+ }
1007
+ }
1008
+ if (!baggage) {
1009
+ return /* @__PURE__ */ new Map();
1010
+ }
1011
+ const entries = /* @__PURE__ */ new Map();
1012
+ for (const [key, entry] of baggage.getAllEntries()) {
1013
+ entries.set(key, entry);
1014
+ }
1015
+ return entries;
1016
+ },
1017
+ // Typed baggage helpers (used by defineBaggageSchema)
1018
+ getTypedBaggage: ((namespace) => {
1019
+ const activeCtx = context.active();
1020
+ let baggage = propagation.getBaggage(activeCtx);
1021
+ if (!baggage) {
1022
+ const storedContext = contextStorage.getStore()?.value;
1023
+ if (storedContext) {
1024
+ baggage = propagation.getBaggage(storedContext);
1025
+ }
1026
+ }
1027
+ if (!baggage) return;
1028
+ const prefix = namespace ? `${namespace}.` : "";
1029
+ const result = {};
1030
+ for (const [key, entry] of baggage.getAllEntries()) {
1031
+ if (namespace && key.startsWith(prefix)) {
1032
+ const fieldName = key.slice(prefix.length);
1033
+ result[fieldName] = entry.value;
1034
+ } else if (!namespace) {
1035
+ result[key] = entry.value;
1036
+ }
1037
+ }
1038
+ return Object.keys(result).length > 0 ? result : void 0;
1039
+ }),
1040
+ setTypedBaggage: ((namespace, value) => {
1041
+ const activeCtx = context.active();
1042
+ const storedContext = contextStorage.getStore()?.value;
1043
+ const currentContext = storedContext ?? activeCtx;
1044
+ let baggage = propagation.getBaggage(currentContext) ?? propagation.createBaggage();
1045
+ const prefix = namespace ? `${namespace}.` : "";
1046
+ for (const [key, val] of Object.entries(value)) {
1047
+ if (val !== void 0) {
1048
+ const baggageKey = `${prefix}${key}`;
1049
+ baggage = baggage.setEntry(baggageKey, { value: String(val) });
1050
+ }
1051
+ }
1052
+ const newContext = propagation.setBaggage(currentContext, baggage);
1053
+ updateActiveContext(newContext);
1054
+ })
1055
+ };
1056
+ const traceCtx = {
1057
+ traceId: spanContext.traceId,
1058
+ spanId: spanContext.spanId,
1059
+ correlationId: spanContext.traceId.slice(0, 16),
1060
+ setAttribute: span.setAttribute.bind(span),
1061
+ setAttributes: span.setAttributes.bind(span),
1062
+ setStatus: span.setStatus.bind(span),
1063
+ recordException: span.recordException.bind(span),
1064
+ addEvent: span.addEvent.bind(span),
1065
+ addLink: span.addLink.bind(span),
1066
+ addLinks: span.addLinks.bind(span),
1067
+ updateName: span.updateName.bind(span),
1068
+ isRecording: span.isRecording.bind(span),
1069
+ recordError: (error) => {
1070
+ const err = error instanceof Error ? error : new Error(String(error));
1071
+ recordStructuredError(traceCtx, err);
1072
+ },
1073
+ track: (event, data) => {
1074
+ track(event, data);
1075
+ },
1076
+ ...baggageHelpers
1077
+ };
1078
+ return traceCtx;
1079
+ }
1080
+ function defineBaggageSchema(namespace) {
1081
+ return {
1082
+ /**
1083
+ * Get typed baggage from context
1084
+ * @param ctx - Trace context
1085
+ * @returns Partial baggage object or undefined if no baggage is set
1086
+ */
1087
+ get: (ctx) => {
1088
+ if (!ctx.getTypedBaggage) return void 0;
1089
+ return ctx.getTypedBaggage(namespace);
1090
+ },
1091
+ /**
1092
+ * Set typed baggage in context
1093
+ *
1094
+ * Note: For proper scoping across async boundaries, use the `with` method instead
1095
+ *
1096
+ * @param ctx - Trace context
1097
+ * @param value - Partial baggage object to set
1098
+ */
1099
+ set: (ctx, value) => {
1100
+ if (!ctx.setTypedBaggage) return;
1101
+ ctx.setTypedBaggage(namespace, value);
1102
+ },
1103
+ /**
1104
+ * Run a function with typed baggage properly scoped
1105
+ *
1106
+ * This is the recommended way to set baggage as it ensures proper
1107
+ * scoping across async boundaries.
1108
+ *
1109
+ * @param ctx - Trace context (can be omitted, will use active context)
1110
+ * @param value - Partial baggage object to set
1111
+ * @param fn - Function to execute with the baggage
1112
+ */
1113
+ with: (ctxOrValue, valueOrFn, maybeFn) => {
1114
+ const value = maybeFn ? valueOrFn : ctxOrValue;
1115
+ const fn = maybeFn || valueOrFn;
1116
+ const prefix = namespace ? `${namespace}.` : "";
1117
+ const flatBaggage = {};
1118
+ for (const [key, val] of Object.entries(value)) {
1119
+ if (val !== void 0) {
1120
+ flatBaggage[`${prefix}${key}`] = String(val);
1121
+ }
1122
+ }
1123
+ const currentContext = context.active();
1124
+ let baggage = propagation.getBaggage(currentContext) ?? propagation.createBaggage();
1125
+ for (const [key, val] of Object.entries(flatBaggage)) {
1126
+ baggage = baggage.setEntry(key, { value: val });
1127
+ }
1128
+ const newContext = propagation.setBaggage(currentContext, baggage);
1129
+ return context.with(newContext, fn);
1130
+ }
1131
+ };
1132
+ }
1133
+
1134
+ // src/correlation-id.ts
1135
+ var correlationStorage = new AsyncLocalStorage();
1136
+ var CORRELATION_ID_BAGGAGE_KEY = "autotel.correlation_id";
1137
+ function generateCorrelationId() {
1138
+ const bytes = new Uint8Array(8);
1139
+ crypto.getRandomValues(bytes);
1140
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
1141
+ }
1142
+ function getCorrelationId() {
1143
+ const storedId = correlationStorage.getStore()?.value;
1144
+ if (storedId) {
1145
+ return storedId;
1146
+ }
1147
+ const activeContext = context.active();
1148
+ const baggage = propagation.getBaggage(activeContext);
1149
+ const baggageEntry = baggage?.getEntry(CORRELATION_ID_BAGGAGE_KEY);
1150
+ if (baggageEntry?.value) {
1151
+ return baggageEntry.value;
1152
+ }
1153
+ const span = trace.getActiveSpan();
1154
+ if (span) {
1155
+ const spanContext = span.spanContext();
1156
+ return spanContext.traceId.slice(0, 16);
1157
+ }
1158
+ return void 0;
1159
+ }
1160
+ function getOrCreateCorrelationId() {
1161
+ return getCorrelationId() ?? generateCorrelationId();
1162
+ }
1163
+ function runWithCorrelationId(correlationId, fn) {
1164
+ return correlationStorage.run({ value: correlationId }, fn);
1165
+ }
1166
+ function setCorrelationId(correlationId) {
1167
+ enterOrRun(correlationStorage, correlationId);
1168
+ }
1169
+ function setCorrelationIdInBaggage(correlationId) {
1170
+ const activeContext = context.active();
1171
+ let baggage = propagation.getBaggage(activeContext) ?? propagation.createBaggage();
1172
+ baggage = baggage.setEntry(CORRELATION_ID_BAGGAGE_KEY, {
1173
+ value: correlationId
1174
+ });
1175
+ return propagation.setBaggage(activeContext, baggage);
1176
+ }
1177
+ function getCorrelationStorage() {
1178
+ return correlationStorage;
1179
+ }
1180
+
1181
+ export { CORRELATION_ID_BAGGAGE_KEY, createStructuredError, createTraceContext, defineBaggageSchema, enterOrRun, flattenToAttributes, generateCorrelationId, getActiveContextWithBaggage, getContextStorage, getCorrelationId, getCorrelationStorage, getEventQueue, getOrCreateCorrelationId, getStructuredErrorAttributes, recordStructuredError, resetEventQueue, runWithCorrelationId, setCorrelationId, setCorrelationIdInBaggage, structuredErrorToJSON, toAttributeValue, track, validateEvent };
1182
+ //# sourceMappingURL=chunk-QG3U5ONP.js.map
1183
+ //# sourceMappingURL=chunk-QG3U5ONP.js.map