@noego/telemetry 0.0.1

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 (120) hide show
  1. package/README.md +130 -0
  2. package/dist/browser/index.cjs +1346 -0
  3. package/dist/browser/index.cjs.map +1 -0
  4. package/dist/browser/index.d.cts +5 -0
  5. package/dist/browser/index.d.ts +5 -0
  6. package/dist/browser/index.js +1318 -0
  7. package/dist/browser/index.js.map +1 -0
  8. package/dist/browser_telemetry_client-BzBPQm4m.d.cts +29 -0
  9. package/dist/browser_telemetry_client-Ch_VzwEa.d.ts +29 -0
  10. package/dist/cli/telemetry_bin.cjs +5531 -0
  11. package/dist/cli/telemetry_bin.cjs.map +1 -0
  12. package/dist/cli/telemetry_bin.d.cts +1 -0
  13. package/dist/cli/telemetry_bin.d.ts +1 -0
  14. package/dist/cli/telemetry_bin.js +5517 -0
  15. package/dist/cli/telemetry_bin.js.map +1 -0
  16. package/dist/cli/telemetry_cli.cjs +5523 -0
  17. package/dist/cli/telemetry_cli.cjs.map +1 -0
  18. package/dist/cli/telemetry_cli.d.cts +92 -0
  19. package/dist/cli/telemetry_cli.d.ts +92 -0
  20. package/dist/cli/telemetry_cli.js +5497 -0
  21. package/dist/cli/telemetry_cli.js.map +1 -0
  22. package/dist/client_defaults-B5tC-TgG.d.ts +8 -0
  23. package/dist/client_defaults-C9LnSX4j.d.cts +8 -0
  24. package/dist/core/index.cjs +2354 -0
  25. package/dist/core/index.cjs.map +1 -0
  26. package/dist/core/index.d.cts +168 -0
  27. package/dist/core/index.d.ts +168 -0
  28. package/dist/core/index.js +2318 -0
  29. package/dist/core/index.js.map +1 -0
  30. package/dist/electron/index.cjs +1379 -0
  31. package/dist/electron/index.cjs.map +1 -0
  32. package/dist/electron/index.d.cts +31 -0
  33. package/dist/electron/index.d.ts +31 -0
  34. package/dist/electron/index.js +1353 -0
  35. package/dist/electron/index.js.map +1 -0
  36. package/dist/envelope.types-rOLpWXRC.d.cts +42 -0
  37. package/dist/envelope.types-rOLpWXRC.d.ts +42 -0
  38. package/dist/in_memory_batch_transport-DKW9EZnU.d.cts +16 -0
  39. package/dist/in_memory_batch_transport-oOwNxXnA.d.ts +16 -0
  40. package/dist/index.cjs +3325 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.d.cts +66 -0
  43. package/dist/index.d.ts +66 -0
  44. package/dist/index.js +3285 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/maintenance_coordinator.types-B-bZUNvw.d.cts +127 -0
  47. package/dist/maintenance_coordinator.types-CBA5y74b.d.ts +127 -0
  48. package/dist/metric_definition_contract-BR6a_GzF.d.cts +12 -0
  49. package/dist/metric_definition_contract-l4i4SaAp.d.ts +12 -0
  50. package/dist/node/index.cjs +7157 -0
  51. package/dist/node/index.cjs.map +1 -0
  52. package/dist/node/index.d.cts +74 -0
  53. package/dist/node/index.d.ts +74 -0
  54. package/dist/node/index.js +7122 -0
  55. package/dist/node/index.js.map +1 -0
  56. package/dist/node/producer/index.cjs +1322 -0
  57. package/dist/node/producer/index.cjs.map +1 -0
  58. package/dist/node/producer/index.d.cts +21 -0
  59. package/dist/node/producer/index.d.ts +21 -0
  60. package/dist/node/producer/index.js +1294 -0
  61. package/dist/node/producer/index.js.map +1 -0
  62. package/dist/query.types-Bntwh6KF.d.cts +186 -0
  63. package/dist/query.types-DySoqYop.d.ts +186 -0
  64. package/dist/result.types-171Huujb.d.cts +9 -0
  65. package/dist/result.types-171Huujb.d.ts +9 -0
  66. package/dist/sqlite/index.cjs +3409 -0
  67. package/dist/sqlite/index.cjs.map +1 -0
  68. package/dist/sqlite/index.d.cts +77 -0
  69. package/dist/sqlite/index.d.ts +77 -0
  70. package/dist/sqlite/index.js +3382 -0
  71. package/dist/sqlite/index.js.map +1 -0
  72. package/dist/storage.types-BTCGVxOM.d.ts +76 -0
  73. package/dist/storage.types-DjuUMinz.d.cts +76 -0
  74. package/dist/telemetry_client-BXw8WH_F.d.ts +141 -0
  75. package/dist/telemetry_client-CYaPYfOl.d.cts +141 -0
  76. package/dist/telemetry_configuration_parser-C7Et_gwG.d.ts +39 -0
  77. package/dist/telemetry_configuration_parser-R-niZQRZ.d.cts +39 -0
  78. package/dist/testing/index.cjs +215 -0
  79. package/dist/testing/index.cjs.map +1 -0
  80. package/dist/testing/index.d.cts +32 -0
  81. package/dist/testing/index.d.ts +32 -0
  82. package/dist/testing/index.js +187 -0
  83. package/dist/testing/index.js.map +1 -0
  84. package/dist/trace-adapter/index.cjs +1034 -0
  85. package/dist/trace-adapter/index.cjs.map +1 -0
  86. package/dist/trace-adapter/index.d.cts +72 -0
  87. package/dist/trace-adapter/index.d.ts +72 -0
  88. package/dist/trace-adapter/index.js +1007 -0
  89. package/dist/trace-adapter/index.js.map +1 -0
  90. package/dist/transport.types-BAl_TRtU.d.cts +99 -0
  91. package/dist/transport.types-DDnZoKWi.d.ts +99 -0
  92. package/migrations/1783695629569_raw_events.down.sql +1 -0
  93. package/migrations/1783695629569_raw_events.up.sql +30 -0
  94. package/migrations/1783695630053_batch_acknowledgements.down.sql +1 -0
  95. package/migrations/1783695630053_batch_acknowledgements.up.sql +13 -0
  96. package/migrations/1783695630960_ingest_watermarks.down.sql +1 -0
  97. package/migrations/1783695630960_ingest_watermarks.up.sql +9 -0
  98. package/migrations/1783695631522_metric_definitions.down.sql +1 -0
  99. package/migrations/1783695631522_metric_definitions.up.sql +10 -0
  100. package/migrations/1783695631966_metric_samples.down.sql +1 -0
  101. package/migrations/1783695631966_metric_samples.up.sql +15 -0
  102. package/migrations/1783695632417_metric_rollups.down.sql +1 -0
  103. package/migrations/1783695632417_metric_rollups.up.sql +22 -0
  104. package/migrations/1783695632860_rollup_completions.down.sql +1 -0
  105. package/migrations/1783695632860_rollup_completions.up.sql +17 -0
  106. package/migrations/1783695633302_extraction_failures.down.sql +1 -0
  107. package/migrations/1783695633302_extraction_failures.up.sql +10 -0
  108. package/migrations/1783695633748_maintenance_runs.down.sql +1 -0
  109. package/migrations/1783695633748_maintenance_runs.up.sql +12 -0
  110. package/migrations/1783695634221_reader_leases.down.sql +1 -0
  111. package/migrations/1783695634221_reader_leases.up.sql +9 -0
  112. package/migrations/1783702703104_committed_drop_counters.down.sql +1 -0
  113. package/migrations/1783702703104_committed_drop_counters.up.sql +11 -0
  114. package/migrations/1783705542684_rollup_completion_state.down.sql +2 -0
  115. package/migrations/1783705542684_rollup_completion_state.up.sql +6 -0
  116. package/migrations/1784309799539_metric_samples_event_index.down.sql +1 -0
  117. package/migrations/1784309799539_metric_samples_event_index.up.sql +2 -0
  118. package/native/noego_telemetry_native.node +0 -0
  119. package/package.json +137 -0
  120. package/proper.json +8 -0
@@ -0,0 +1,1007 @@
1
+ /* @noego/telemetry */
2
+
3
+ // src/adapters/trace/trace_telemetry_adapter.ts
4
+ var TraceTelemetryAdapter = class {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ client;
9
+ attachTraceManager(manager) {
10
+ return manager.registerSink((event) => {
11
+ this.admitTraceEvent(event);
12
+ });
13
+ }
14
+ admitTraceEvent(input) {
15
+ const parsed = this.parseTraceEvent(input);
16
+ if (!parsed.ok) {
17
+ return this.client.admit(this.invalidAdmission("trace.invalid", parsed.error));
18
+ }
19
+ return this.client.admit({
20
+ source: parsed.value.source,
21
+ processKind: parsed.value.process,
22
+ level: this.numericLevel(parsed.value.level),
23
+ label: parsed.value.label,
24
+ occurredAtMs: parsed.value.occurredAtMs,
25
+ monotonicNs: null,
26
+ conversationId: parsed.value.conversationId,
27
+ correlationId: parsed.value.correlationId,
28
+ metadata: parsed.value.metadata
29
+ });
30
+ }
31
+ admitWoodEvent(input) {
32
+ const parsed = this.parseWoodEvent(input);
33
+ if (!parsed.ok) {
34
+ return this.client.admit(this.invalidAdmission("wood.invalid", parsed.error));
35
+ }
36
+ return this.client.admit({
37
+ source: parsed.value.source,
38
+ processKind: parsed.value.process,
39
+ level: parsed.value.level,
40
+ label: parsed.value.label,
41
+ occurredAtMs: parsed.value.occurredAtMs,
42
+ monotonicNs: null,
43
+ conversationId: parsed.value.conversationId,
44
+ correlationId: parsed.value.correlationId,
45
+ metadata: parsed.value.metadata
46
+ });
47
+ }
48
+ admitScoped(input) {
49
+ const correlation = this.correlationFromMetadata(input.metadata);
50
+ return this.client.admit({
51
+ source: input.source,
52
+ processKind: input.processKind,
53
+ level: input.level,
54
+ label: input.label,
55
+ occurredAtMs: input.occurredAtMs,
56
+ monotonicNs: null,
57
+ conversationId: correlation.conversationId,
58
+ correlationId: correlation.correlationId,
59
+ metadata: input.metadata
60
+ });
61
+ }
62
+ parseTraceEvent(input) {
63
+ if (!this.isRecord(input)) {
64
+ return { ok: false, error: "Trace event must be an object" };
65
+ }
66
+ const timestamp = input.timestamp;
67
+ const source = input.source;
68
+ const label = input.event;
69
+ const level = input.level;
70
+ if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
71
+ return { ok: false, error: "Trace event timestamp is invalid" };
72
+ }
73
+ if (typeof source !== "string" || typeof label !== "string" || typeof level !== "number") {
74
+ return { ok: false, error: "Trace event identity is invalid" };
75
+ }
76
+ const metadata = this.mergeMessage(input.context, input.message);
77
+ const correlation = this.correlationFromMetadata(metadata);
78
+ return {
79
+ ok: true,
80
+ value: {
81
+ source,
82
+ process: typeof input.process === "string" ? input.process : "unknown",
83
+ level,
84
+ label,
85
+ occurredAtMs: timestamp,
86
+ conversationId: correlation.conversationId,
87
+ correlationId: correlation.correlationId,
88
+ metadata
89
+ }
90
+ };
91
+ }
92
+ parseWoodEvent(input) {
93
+ if (!this.isRecord(input)) {
94
+ return { ok: false, error: "Wood trace event must be an object" };
95
+ }
96
+ const source = input.source;
97
+ const label = input.type;
98
+ const level = input.level;
99
+ const timestamp = input.timestamp;
100
+ if (typeof source !== "string" || typeof label !== "string" || typeof level !== "string") {
101
+ return { ok: false, error: "Wood trace event identity is invalid" };
102
+ }
103
+ const occurredAtMs = typeof timestamp === "string" ? Date.parse(timestamp) : Number.NaN;
104
+ if (!Number.isFinite(occurredAtMs)) {
105
+ return { ok: false, error: "Wood trace event timestamp is invalid" };
106
+ }
107
+ const metadata = this.copyRecord(input.payload);
108
+ if (typeof input.message === "string") {
109
+ metadata.message = input.message;
110
+ }
111
+ if (typeof input.traceSeq === "number") {
112
+ metadata.woodTraceSeq = input.traceSeq;
113
+ }
114
+ const topConversation = this.scalarConversationId(input.conversationId);
115
+ const correlation = this.correlationFromMetadata(metadata);
116
+ return {
117
+ ok: true,
118
+ value: {
119
+ source,
120
+ process: typeof input.process === "string" ? input.process : "unknown",
121
+ level,
122
+ label,
123
+ occurredAtMs,
124
+ conversationId: topConversation ?? correlation.conversationId,
125
+ correlationId: correlation.correlationId,
126
+ metadata
127
+ }
128
+ };
129
+ }
130
+ correlationFromMetadata(input) {
131
+ if (!this.isRecord(input)) {
132
+ return { conversationId: null, correlationId: null };
133
+ }
134
+ const conversationId = this.scalarConversationId(input.conversationId) ?? this.scalarConversationId(input.threadId);
135
+ const correlationId = typeof input.correlationId === "string" ? input.correlationId : null;
136
+ return { conversationId, correlationId };
137
+ }
138
+ scalarConversationId(value) {
139
+ return typeof value === "string" || typeof value === "number" ? value : null;
140
+ }
141
+ mergeMessage(context, message) {
142
+ const metadata = this.copyRecord(context);
143
+ if (typeof message === "string") {
144
+ metadata.message = message;
145
+ }
146
+ return metadata;
147
+ }
148
+ copyRecord(input) {
149
+ if (!this.isRecord(input)) {
150
+ return {};
151
+ }
152
+ let keys;
153
+ try {
154
+ keys = Object.keys(input);
155
+ } catch {
156
+ return { __telemetryAdapter: "[property-enumeration-failed]" };
157
+ }
158
+ const output = {};
159
+ for (const key of keys) {
160
+ try {
161
+ output[key] = Reflect.get(input, key);
162
+ } catch {
163
+ output[key] = "[property-read-failed]";
164
+ }
165
+ }
166
+ return output;
167
+ }
168
+ numericLevel(level) {
169
+ switch (level) {
170
+ case 0:
171
+ return "debug";
172
+ case 1:
173
+ return "info";
174
+ case 2:
175
+ return "warn";
176
+ case 3:
177
+ return "error";
178
+ default:
179
+ return "debug";
180
+ }
181
+ }
182
+ invalidAdmission(label, error) {
183
+ return {
184
+ source: "telemetry-adapter",
185
+ processKind: "unknown",
186
+ level: "warn",
187
+ label,
188
+ occurredAtMs: Date.now(),
189
+ monotonicNs: null,
190
+ conversationId: null,
191
+ correlationId: null,
192
+ metadata: { error }
193
+ };
194
+ }
195
+ isRecord(value) {
196
+ try {
197
+ return typeof value === "object" && value !== null && !Array.isArray(value);
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+ };
203
+
204
+ // src/core/helper/canonical_json.ts
205
+ var UTF8_ENCODER = new TextEncoder();
206
+ function compareCanonicalKeys(left, right) {
207
+ if (left === right) return 0;
208
+ if (/^[\x00-\x7f]*$/.test(left) && /^[\x00-\x7f]*$/.test(right)) {
209
+ return left < right ? -1 : 1;
210
+ }
211
+ const leftBytes = UTF8_ENCODER.encode(left);
212
+ const rightBytes = UTF8_ENCODER.encode(right);
213
+ const length = Math.min(leftBytes.length, rightBytes.length);
214
+ for (let index = 0; index < length; index += 1) {
215
+ const difference = (leftBytes[index] ?? 0) - (rightBytes[index] ?? 0);
216
+ if (difference !== 0) return difference;
217
+ }
218
+ return leftBytes.length - rightBytes.length;
219
+ }
220
+ function canonicalJson(value) {
221
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
222
+ return JSON.stringify(value);
223
+ }
224
+ if (typeof value === "number") {
225
+ if (!Number.isFinite(value)) {
226
+ throw new Error("Canonical telemetry JSON cannot encode a non-finite number");
227
+ }
228
+ return JSON.stringify(value);
229
+ }
230
+ if (Array.isArray(value)) {
231
+ const items = value.map((item) => canonicalJson(item));
232
+ return `[${items.join(",")}]`;
233
+ }
234
+ if (typeof value !== "object") {
235
+ throw new Error(`Canonical telemetry JSON cannot encode ${typeof value}`);
236
+ }
237
+ const entries = Object.entries(value).sort(([left], [right]) => compareCanonicalKeys(left, right));
238
+ const properties = entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`);
239
+ return `{${properties.join(",")}}`;
240
+ }
241
+ function telemetryUtf8Length(value) {
242
+ return new TextEncoder().encode(value).byteLength;
243
+ }
244
+ function telemetryChecksum(value) {
245
+ const bytes = new TextEncoder().encode(canonicalJson(value));
246
+ let hash = 0xcbf29ce484222325n;
247
+ const prime = 0x100000001b3n;
248
+ for (const byte of bytes) {
249
+ hash ^= BigInt(byte);
250
+ hash = BigInt.asUintN(64, hash * prime);
251
+ }
252
+ return hash.toString(16).padStart(16, "0");
253
+ }
254
+
255
+ // src/core/bounded_metadata_snapshotter.ts
256
+ var SENTINEL_CIRCULAR = "[telemetry:circular]";
257
+ var SENTINEL_TRUNCATED = "[telemetry:truncated]";
258
+ var BoundedMetadataSnapshotter = class {
259
+ constructor(limits) {
260
+ this.limits = limits;
261
+ this.validateLimits();
262
+ }
263
+ limits;
264
+ snapshot(input) {
265
+ const state = {
266
+ bytes: 0,
267
+ properties: 0,
268
+ truncatedValues: 0,
269
+ redactedValues: 0,
270
+ serializationFailures: 0,
271
+ seen: /* @__PURE__ */ new WeakSet()
272
+ };
273
+ let normalized;
274
+ try {
275
+ normalized = this.normalize(input, "$", 0, state);
276
+ } catch {
277
+ state.serializationFailures += 1;
278
+ normalized = { __telemetry: "[telemetry:snapshot-failed]" };
279
+ }
280
+ const root = this.ensureObject(normalized);
281
+ const canonical = canonicalJson(root);
282
+ const metadata = telemetryUtf8Length(canonical) <= this.limits.maxBytes ? root : Object.freeze({ __telemetry: SENTINEL_TRUNCATED });
283
+ if (metadata !== root) {
284
+ state.truncatedValues += 1;
285
+ }
286
+ const stats = Object.freeze({
287
+ estimatedBytes: Math.min(telemetryUtf8Length(canonical), this.limits.maxBytes),
288
+ truncatedValues: state.truncatedValues,
289
+ redactedValues: state.redactedValues,
290
+ serializationFailures: state.serializationFailures
291
+ });
292
+ return Object.freeze({ metadata, stats });
293
+ }
294
+ normalize(input, path, depth, state) {
295
+ const replacement = this.redactionFor(path);
296
+ if (replacement !== null) {
297
+ state.redactedValues += 1;
298
+ return replacement;
299
+ }
300
+ if (depth > this.limits.maxDepth || state.bytes >= this.limits.maxBytes) {
301
+ state.truncatedValues += 1;
302
+ return SENTINEL_TRUNCATED;
303
+ }
304
+ if (input === null || typeof input === "boolean") {
305
+ return input;
306
+ }
307
+ if (typeof input === "string") {
308
+ return this.normalizeString(input, state);
309
+ }
310
+ if (typeof input === "number") {
311
+ return Number.isFinite(input) ? input : `[telemetry:number:${String(input)}]`;
312
+ }
313
+ if (typeof input === "bigint") {
314
+ return `[telemetry:bigint:${input.toString()}]`;
315
+ }
316
+ if (typeof input === "undefined") {
317
+ return "[telemetry:undefined]";
318
+ }
319
+ if (typeof input === "symbol") {
320
+ return `[telemetry:symbol:${input.description ?? ""}]`;
321
+ }
322
+ if (typeof input === "function") {
323
+ return "[telemetry:function]";
324
+ }
325
+ if (input instanceof Error) {
326
+ return this.normalizeError(input, path, depth, state);
327
+ }
328
+ if (typeof input !== "object") {
329
+ return `[telemetry:unsupported:${typeof input}]`;
330
+ }
331
+ if (state.seen.has(input)) {
332
+ return SENTINEL_CIRCULAR;
333
+ }
334
+ state.seen.add(input);
335
+ try {
336
+ return Array.isArray(input) ? this.normalizeArray(input, path, depth, state) : this.normalizeObject(input, path, depth, state);
337
+ } finally {
338
+ state.seen.delete(input);
339
+ }
340
+ }
341
+ normalizeString(input, state) {
342
+ const stringLimit = Math.min(this.limits.maxStringLength, Math.max(0, this.limits.maxBytes - state.bytes));
343
+ const truncated = input.length > stringLimit;
344
+ const normalized = truncated ? input.slice(0, stringLimit) : input;
345
+ state.bytes += telemetryUtf8Length(normalized);
346
+ if (truncated) {
347
+ state.truncatedValues += 1;
348
+ }
349
+ return normalized;
350
+ }
351
+ normalizeArray(input, path, depth, state) {
352
+ const length = Math.min(input.length, this.limits.maxArrayLength);
353
+ const values = [];
354
+ for (let index = 0; index < length; index += 1) {
355
+ let item;
356
+ try {
357
+ item = input[index];
358
+ } catch {
359
+ state.serializationFailures += 1;
360
+ item = "[telemetry:property-read-failed]";
361
+ }
362
+ values.push(this.normalize(item, `${path}[${index}]`, depth + 1, state));
363
+ }
364
+ if (input.length > length) {
365
+ values.push(SENTINEL_TRUNCATED);
366
+ state.truncatedValues += 1;
367
+ }
368
+ return Object.freeze(values);
369
+ }
370
+ normalizeObject(input, path, depth, state) {
371
+ let keys;
372
+ try {
373
+ keys = Object.keys(input).sort((left, right) => left.localeCompare(right));
374
+ } catch {
375
+ state.serializationFailures += 1;
376
+ return Object.freeze({ __telemetry: "[telemetry:keys-failed]" });
377
+ }
378
+ const output = {};
379
+ for (const key of keys) {
380
+ if (state.properties >= this.limits.maxProperties) {
381
+ output.__telemetry = SENTINEL_TRUNCATED;
382
+ state.truncatedValues += 1;
383
+ break;
384
+ }
385
+ state.properties += 1;
386
+ state.bytes += telemetryUtf8Length(key);
387
+ const childPath = path === "$" ? key : `${path}.${key}`;
388
+ const redaction = this.redactionFor(childPath);
389
+ if (redaction !== null) {
390
+ output[key] = redaction;
391
+ state.redactedValues += 1;
392
+ continue;
393
+ }
394
+ let property;
395
+ try {
396
+ property = Reflect.get(input, key);
397
+ } catch {
398
+ state.serializationFailures += 1;
399
+ property = "[telemetry:property-read-failed]";
400
+ }
401
+ output[key] = this.normalize(property, childPath, depth + 1, state);
402
+ }
403
+ return Object.freeze(output);
404
+ }
405
+ normalizeError(error, path, depth, state) {
406
+ const name = this.readErrorField(error, "name", state);
407
+ const message = this.readErrorField(error, "message", state);
408
+ const stack = this.readErrorField(error, "stack", state).slice(0, this.limits.maxErrorStackLength);
409
+ return Object.freeze({
410
+ name: this.normalize(name, `${path}.name`, depth + 1, state),
411
+ message: this.normalize(message, `${path}.message`, depth + 1, state),
412
+ stack: this.normalize(stack, `${path}.stack`, depth + 1, state)
413
+ });
414
+ }
415
+ readErrorField(error, field, state) {
416
+ try {
417
+ return typeof error[field] === "string" ? error[field] : "";
418
+ } catch {
419
+ state.serializationFailures += 1;
420
+ return "[telemetry:error-field-read-failed]";
421
+ }
422
+ }
423
+ ensureObject(value) {
424
+ return this.isJsonObject(value) ? value : Object.freeze({ value });
425
+ }
426
+ isJsonObject(value) {
427
+ return typeof value === "object" && value !== null && !Array.isArray(value);
428
+ }
429
+ redactionFor(path) {
430
+ const matchingRule = this.limits.redactions.find((rule) => rule.path === path);
431
+ return matchingRule?.replacement ?? null;
432
+ }
433
+ validateLimits() {
434
+ const limits = [
435
+ this.limits.maxBytes,
436
+ this.limits.maxDepth,
437
+ this.limits.maxProperties,
438
+ this.limits.maxArrayLength,
439
+ this.limits.maxStringLength,
440
+ this.limits.maxErrorStackLength
441
+ ];
442
+ const hasInvalidLimit = limits.some((limit) => !Number.isInteger(limit) || limit <= 0);
443
+ if (hasInvalidLimit) {
444
+ throw new Error("Metadata snapshot limits must be positive integers");
445
+ }
446
+ }
447
+ };
448
+
449
+ // src/core/helper/client_defaults.ts
450
+ var DEFAULT_TELEMETRY_ADMISSION_POLICY = Object.freeze({
451
+ maxQueuedEvents: 2e3,
452
+ maxQueuedBytes: 2e6,
453
+ maxBatchEvents: 128,
454
+ maxBatchBytes: 256e3,
455
+ maxInFlightBatches: 1,
456
+ retryLimit: 3,
457
+ retryBaseDelayMs: 25,
458
+ sampleRates: Object.freeze({
459
+ low: 1,
460
+ normal: 1,
461
+ high: 1
462
+ })
463
+ });
464
+ var DEFAULT_METADATA_SNAPSHOT_LIMITS = Object.freeze({
465
+ maxBytes: 32768,
466
+ maxDepth: 8,
467
+ maxProperties: 256,
468
+ maxArrayLength: 128,
469
+ maxStringLength: 4096,
470
+ maxErrorStackLength: 8192,
471
+ redactions: Object.freeze([])
472
+ });
473
+ var DEFAULT_TELEMETRY_BATCH_VALIDATION_LIMITS = Object.freeze({
474
+ maxBatchEvents: 1024,
475
+ maxBatchBytes: 1e6,
476
+ maxEventBytes: 256e3,
477
+ maxMetadataBytes: 131072,
478
+ maxMetadataDepth: 16,
479
+ maxMetadataProperties: 1024,
480
+ maxMetadataArrayLength: 1024,
481
+ maxMetadataStringBytes: 65536,
482
+ maxDropCounters: 15,
483
+ maxIdentityBytes: 1024
484
+ });
485
+
486
+ // src/core/telemetry_batch_contract.ts
487
+ var BATCH_KEYS = Object.freeze([
488
+ "schemaVersion",
489
+ "producerId",
490
+ "sequenceStart",
491
+ "sequenceEnd",
492
+ "idempotencyKey",
493
+ "checksum",
494
+ "envelopes",
495
+ "dropCounters"
496
+ ]);
497
+ var ENVELOPE_KEYS = Object.freeze([
498
+ "schemaVersion",
499
+ "eventId",
500
+ "producerId",
501
+ "sequence",
502
+ "occurredAtMs",
503
+ "monotonicNs",
504
+ "source",
505
+ "processKind",
506
+ "level",
507
+ "label",
508
+ "conversationId",
509
+ "correlationId",
510
+ "metadata"
511
+ ]);
512
+ var DROP_COUNTER_KEYS = Object.freeze(["reason", "priority", "count"]);
513
+ var DROP_REASONS = /* @__PURE__ */ new Set(["capacity", "sampled", "stopped", "invalid", "transport"]);
514
+ var DROP_PRIORITIES = /* @__PURE__ */ new Set(["low", "normal", "high"]);
515
+ var TelemetryBatchContract = class _TelemetryBatchContract {
516
+ static schemaVersion = 1;
517
+ static checksumAlgorithm = "fnv1a64-canonical-json-v1";
518
+ limits;
519
+ constructor(limits = {}) {
520
+ this.limits = Object.freeze({
521
+ ...DEFAULT_TELEMETRY_BATCH_VALIDATION_LIMITS,
522
+ ...limits
523
+ });
524
+ this.validateLimits();
525
+ }
526
+ create(envelopes, dropCounters) {
527
+ try {
528
+ return this.createChecked(envelopes, dropCounters);
529
+ } catch {
530
+ return { ok: false, error: "Telemetry batch creation failed safe validation" };
531
+ }
532
+ }
533
+ validate(batch) {
534
+ try {
535
+ return this.validateChecked(batch);
536
+ } catch {
537
+ return { ok: false, error: "Telemetry batch validation failed safely" };
538
+ }
539
+ }
540
+ createChecked(envelopes, dropCounters) {
541
+ const payloadError = this.validatePayload(envelopes, dropCounters);
542
+ if (payloadError !== null) {
543
+ return { ok: false, error: payloadError };
544
+ }
545
+ const payloadBytesError = this.payloadBytesError(envelopes, dropCounters);
546
+ if (payloadBytesError !== null) {
547
+ return { ok: false, error: payloadBytesError };
548
+ }
549
+ const first = envelopes[0];
550
+ const last = envelopes[envelopes.length - 1];
551
+ if (!first || !last) {
552
+ return { ok: false, error: "A telemetry batch must contain a first and last envelope" };
553
+ }
554
+ const producerId = first.producerId;
555
+ const sequenceStart = first.sequence;
556
+ const sequenceEnd = last.sequence;
557
+ const checksumPayload = this.checksumPayload(
558
+ producerId,
559
+ sequenceStart,
560
+ sequenceEnd,
561
+ envelopes,
562
+ dropCounters
563
+ );
564
+ const checksum = telemetryChecksum(checksumPayload);
565
+ const idempotencyKey = `tb1:${producerId}:${sequenceStart}-${sequenceEnd}:${checksum}`;
566
+ const batch = Object.freeze({
567
+ schemaVersion: _TelemetryBatchContract.schemaVersion,
568
+ producerId,
569
+ sequenceStart,
570
+ sequenceEnd,
571
+ idempotencyKey,
572
+ checksum,
573
+ envelopes: Object.freeze([...envelopes]),
574
+ dropCounters: Object.freeze([...dropCounters])
575
+ });
576
+ const framingError = this.validateFraming(batch);
577
+ if (framingError !== null) {
578
+ return { ok: false, error: framingError };
579
+ }
580
+ const byteError = this.serializedByteError(batch, this.limits.maxBatchBytes, "batch");
581
+ return byteError === null ? { ok: true, value: this.detachBatch(batch) } : { ok: false, error: byteError };
582
+ }
583
+ validateChecked(batch) {
584
+ if (!this.isRecord(batch)) {
585
+ return { ok: false, error: "Telemetry batch must be a plain object" };
586
+ }
587
+ const schemaVersion = batch.schemaVersion;
588
+ if (!Number.isSafeInteger(schemaVersion)) {
589
+ return { ok: false, error: "Telemetry batch schema version must be a safe integer" };
590
+ }
591
+ if (schemaVersion !== _TelemetryBatchContract.schemaVersion) {
592
+ return { ok: false, error: `Unsupported telemetry schema version ${String(schemaVersion)}` };
593
+ }
594
+ if (!this.hasExactKeys(batch, BATCH_KEYS)) {
595
+ return { ok: false, error: "Telemetry batch fields do not match the schema" };
596
+ }
597
+ const framingError = this.validateFraming(batch);
598
+ if (framingError !== null) {
599
+ return { ok: false, error: framingError };
600
+ }
601
+ const recreated = this.create(
602
+ batch.envelopes,
603
+ batch.dropCounters
604
+ );
605
+ if (!recreated.ok) {
606
+ return recreated;
607
+ }
608
+ const identityError = this.compareFraming(batch, recreated.value);
609
+ return identityError === null ? { ok: true, value: recreated.value } : { ok: false, error: identityError };
610
+ }
611
+ validatePayload(envelopes, dropCounters) {
612
+ if (!Array.isArray(envelopes) || envelopes.length === 0) {
613
+ return "A telemetry batch must contain at least one envelope";
614
+ }
615
+ if (envelopes.length > this.limits.maxBatchEvents) {
616
+ return `Telemetry batch exceeds ${this.limits.maxBatchEvents} envelopes`;
617
+ }
618
+ const envelopeError = this.validateEnvelopes(envelopes);
619
+ return envelopeError ?? this.validateDropCounters(dropCounters);
620
+ }
621
+ validateEnvelopes(envelopes) {
622
+ let previousSequence = -1;
623
+ let producerId = null;
624
+ for (const envelope of envelopes) {
625
+ const envelopeError = this.validateEnvelope(envelope, producerId, previousSequence);
626
+ if (envelopeError !== null) {
627
+ return envelopeError;
628
+ }
629
+ const typedEnvelope = envelope;
630
+ producerId = typedEnvelope.producerId;
631
+ previousSequence = typedEnvelope.sequence;
632
+ }
633
+ return null;
634
+ }
635
+ validateEnvelope(envelope, expectedProducerId, previousSequence) {
636
+ if (!this.isRecord(envelope) || !this.hasExactKeys(envelope, ENVELOPE_KEYS)) {
637
+ return "Telemetry envelope fields do not match the schema";
638
+ }
639
+ const identityError = this.validateEnvelopeIdentity(envelope, expectedProducerId, previousSequence);
640
+ if (identityError !== null) {
641
+ return identityError;
642
+ }
643
+ const valueError = this.validateEnvelopeValues(envelope);
644
+ if (valueError !== null) {
645
+ return valueError;
646
+ }
647
+ const metadataError = this.validateMetadata(envelope.metadata);
648
+ return metadataError ?? this.serializedByteError(envelope, this.limits.maxEventBytes, "event");
649
+ }
650
+ validateEnvelopeIdentity(envelope, expectedProducerId, previousSequence) {
651
+ if (envelope.schemaVersion !== _TelemetryBatchContract.schemaVersion) {
652
+ return "Telemetry envelope schema version does not match its batch";
653
+ }
654
+ if (!this.isIdentity(envelope.producerId)) {
655
+ return "Telemetry envelope producer identity is invalid";
656
+ }
657
+ if (!this.isSequence(envelope.sequence) || envelope.sequence <= previousSequence) {
658
+ return "Telemetry envelope sequences must be nonnegative safe integers in increasing order";
659
+ }
660
+ if (expectedProducerId !== null && envelope.producerId !== expectedProducerId) {
661
+ return "A telemetry batch cannot mix producer identities";
662
+ }
663
+ const eventId = `${envelope.producerId}:${envelope.sequence}`;
664
+ if (envelope.eventId !== eventId || telemetryUtf8Length(eventId) > this.limits.maxIdentityBytes) {
665
+ return "Telemetry envelope event identity is invalid";
666
+ }
667
+ return null;
668
+ }
669
+ validateEnvelopeValues(envelope) {
670
+ if (!Number.isSafeInteger(envelope.occurredAtMs) || Number(envelope.occurredAtMs) < 0) {
671
+ return "Telemetry envelope occurredAtMs must be a nonnegative safe integer";
672
+ }
673
+ if (!this.isMonotonicTimestamp(envelope.monotonicNs)) {
674
+ return "Telemetry envelope monotonicNs is invalid";
675
+ }
676
+ if (!this.isIdentity(envelope.source) || !this.isIdentity(envelope.processKind)) {
677
+ return "Telemetry envelope source and process kind are invalid";
678
+ }
679
+ if (!this.isIdentity(envelope.level)) {
680
+ return "Telemetry envelope level is invalid";
681
+ }
682
+ if (!this.isLabel(envelope.label)) {
683
+ return "Telemetry envelope label is invalid";
684
+ }
685
+ if (!this.isConversationId(envelope.conversationId)) {
686
+ return "Telemetry envelope conversation identity is invalid";
687
+ }
688
+ if (!this.isOptionalBoundedString(envelope.correlationId)) {
689
+ return "Telemetry envelope correlation identity is invalid";
690
+ }
691
+ return null;
692
+ }
693
+ validateMetadata(metadata) {
694
+ if (!this.isRecord(metadata)) {
695
+ return "Telemetry envelope metadata must be a plain JSON object";
696
+ }
697
+ const state = { properties: 0, bytes: 0, active: /* @__PURE__ */ new WeakSet() };
698
+ const jsonError = this.validateJsonValue(metadata, 0, state);
699
+ return jsonError ?? this.serializedByteError(metadata, this.limits.maxMetadataBytes, "metadata");
700
+ }
701
+ validateJsonValue(value, depth, state) {
702
+ if (value === null || typeof value === "boolean") {
703
+ state.bytes += value === null ? 4 : 5;
704
+ return null;
705
+ }
706
+ if (typeof value === "number") {
707
+ if (!Number.isFinite(value)) {
708
+ return "Telemetry metadata contains a non-finite number";
709
+ }
710
+ state.bytes += String(value).length;
711
+ return this.metadataBudgetError(state);
712
+ }
713
+ if (typeof value === "string") {
714
+ if (!this.isWithinUtf8Limit(value, this.limits.maxMetadataStringBytes)) {
715
+ return "Telemetry metadata string exceeds the receiver limit";
716
+ }
717
+ state.bytes += telemetryUtf8Length(value);
718
+ return this.metadataBudgetError(state);
719
+ }
720
+ if (typeof value !== "object") {
721
+ return "Telemetry metadata contains a non-JSON value";
722
+ }
723
+ if (depth > this.limits.maxMetadataDepth) {
724
+ return "Telemetry metadata exceeds the receiver depth limit";
725
+ }
726
+ return Array.isArray(value) ? this.validateJsonArray(value, depth, state) : this.validateJsonObject(value, depth, state);
727
+ }
728
+ validateJsonArray(value, depth, state) {
729
+ if (value.length > this.limits.maxMetadataArrayLength) {
730
+ return "Telemetry metadata array exceeds the receiver length limit";
731
+ }
732
+ const keys = Object.keys(value);
733
+ if (keys.length !== value.length || Object.getOwnPropertySymbols(value).length > 0) {
734
+ return "Telemetry metadata arrays must be dense JSON arrays";
735
+ }
736
+ return this.validateJsonChildren(value, value, depth, state);
737
+ }
738
+ validateJsonObject(value, depth, state) {
739
+ if (!this.isRecord(value)) {
740
+ return "Telemetry metadata contains a non-plain object";
741
+ }
742
+ const keys = Object.keys(value);
743
+ if (Object.getOwnPropertySymbols(value).length > 0) {
744
+ return "Telemetry metadata objects cannot contain symbol keys";
745
+ }
746
+ state.properties += keys.length;
747
+ if (state.properties > this.limits.maxMetadataProperties) {
748
+ return "Telemetry metadata exceeds the receiver property limit";
749
+ }
750
+ if (keys.some((key) => !this.isWithinUtf8Limit(key, this.limits.maxMetadataStringBytes))) {
751
+ return "Telemetry metadata property name exceeds the receiver string limit";
752
+ }
753
+ for (const key of keys) {
754
+ state.bytes += telemetryUtf8Length(key);
755
+ }
756
+ const budgetError = this.metadataBudgetError(state);
757
+ if (budgetError !== null) {
758
+ return budgetError;
759
+ }
760
+ return this.validateJsonChildren(value, keys.map((key) => Reflect.get(value, key)), depth, state);
761
+ }
762
+ validateJsonChildren(owner, values, depth, state) {
763
+ if (state.active.has(owner)) {
764
+ return "Telemetry metadata cannot contain a cycle";
765
+ }
766
+ state.active.add(owner);
767
+ try {
768
+ for (const value of values) {
769
+ const error = this.validateJsonValue(value, depth + 1, state);
770
+ if (error !== null) {
771
+ return error;
772
+ }
773
+ }
774
+ return null;
775
+ } finally {
776
+ state.active.delete(owner);
777
+ }
778
+ }
779
+ validateDropCounters(dropCounters) {
780
+ if (!Array.isArray(dropCounters) || dropCounters.length > this.limits.maxDropCounters) {
781
+ return "Telemetry drop counters exceed the fixed receiver limit";
782
+ }
783
+ const identities = /* @__PURE__ */ new Set();
784
+ let total = 0;
785
+ for (const counter of dropCounters) {
786
+ const error = this.validateDropCounter(counter, identities, total);
787
+ if (error !== null) {
788
+ return error;
789
+ }
790
+ total += counter.count;
791
+ }
792
+ return null;
793
+ }
794
+ validateDropCounter(counter, identities, currentTotal) {
795
+ if (!this.isRecord(counter) || !this.hasExactKeys(counter, DROP_COUNTER_KEYS)) {
796
+ return "Telemetry drop counter fields do not match the schema";
797
+ }
798
+ if (!DROP_REASONS.has(String(counter.reason)) || !DROP_PRIORITIES.has(String(counter.priority))) {
799
+ return "Telemetry drop counter identity is invalid";
800
+ }
801
+ if (!Number.isSafeInteger(counter.count) || Number(counter.count) <= 0) {
802
+ return "Telemetry drop counter count must be a positive safe integer";
803
+ }
804
+ if (currentTotal > Number.MAX_SAFE_INTEGER - Number(counter.count)) {
805
+ return "Telemetry drop counter total exceeds the safe integer range";
806
+ }
807
+ const identity = `${counter.reason}:${counter.priority}`;
808
+ if (identities.has(identity)) {
809
+ return "Telemetry drop counter identities must be unique within a batch";
810
+ }
811
+ identities.add(identity);
812
+ return null;
813
+ }
814
+ validateFraming(batch) {
815
+ if (!this.isIdentity(batch.producerId)) {
816
+ return "Telemetry batch producer identity is invalid";
817
+ }
818
+ if (!this.isSequence(batch.sequenceStart) || !this.isSequence(batch.sequenceEnd)) {
819
+ return "Telemetry batch sequence range must use nonnegative safe integers";
820
+ }
821
+ if (Number(batch.sequenceEnd) < Number(batch.sequenceStart)) {
822
+ return "Telemetry batch sequence range is reversed";
823
+ }
824
+ if (typeof batch.checksum !== "string" || !/^[a-f0-9]{16}$/.test(batch.checksum)) {
825
+ return "Telemetry batch checksum is invalid";
826
+ }
827
+ if (typeof batch.idempotencyKey !== "string" || !this.isWithinUtf8Limit(batch.idempotencyKey, this.limits.maxIdentityBytes)) {
828
+ return "Telemetry batch idempotency identity is invalid";
829
+ }
830
+ return null;
831
+ }
832
+ compareFraming(batch, recreated) {
833
+ const matches = recreated.checksum === batch.checksum && recreated.idempotencyKey === batch.idempotencyKey && recreated.sequenceStart === batch.sequenceStart && recreated.sequenceEnd === batch.sequenceEnd && recreated.producerId === batch.producerId;
834
+ return matches ? null : "Telemetry batch framing or checksum is invalid";
835
+ }
836
+ checksumPayload(producerId, sequenceStart, sequenceEnd, envelopes, dropCounters) {
837
+ return {
838
+ schemaVersion: _TelemetryBatchContract.schemaVersion,
839
+ producerId,
840
+ sequenceStart,
841
+ sequenceEnd,
842
+ envelopes,
843
+ dropCounters
844
+ };
845
+ }
846
+ serializedByteError(value, maximum, kind) {
847
+ const bytes = telemetryUtf8Length(canonicalJson(value));
848
+ return bytes <= maximum ? null : `Telemetry ${kind} exceeds ${maximum} bytes`;
849
+ }
850
+ payloadBytesError(envelopes, dropCounters) {
851
+ let bytes = 0;
852
+ for (const envelope of envelopes) {
853
+ bytes += telemetryUtf8Length(canonicalJson(envelope));
854
+ if (bytes > this.limits.maxBatchBytes) {
855
+ return `Telemetry batch exceeds ${this.limits.maxBatchBytes} bytes`;
856
+ }
857
+ }
858
+ bytes += telemetryUtf8Length(canonicalJson(dropCounters));
859
+ return bytes > this.limits.maxBatchBytes ? `Telemetry batch exceeds ${this.limits.maxBatchBytes} bytes` : null;
860
+ }
861
+ metadataBudgetError(state) {
862
+ return state.bytes > this.limits.maxMetadataBytes ? `Telemetry metadata exceeds ${this.limits.maxMetadataBytes} bytes` : null;
863
+ }
864
+ detachBatch(batch) {
865
+ const detached = JSON.parse(canonicalJson(batch));
866
+ return this.deepFreeze(detached);
867
+ }
868
+ deepFreeze(value) {
869
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
870
+ return value;
871
+ }
872
+ for (const child of Object.values(value)) {
873
+ this.deepFreeze(child);
874
+ }
875
+ return Object.freeze(value);
876
+ }
877
+ isRecord(value) {
878
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
879
+ return false;
880
+ }
881
+ const prototype = Object.getPrototypeOf(value);
882
+ return prototype === null || prototype.constructor?.name === "Object";
883
+ }
884
+ hasExactKeys(value, expected) {
885
+ const keys = Object.keys(value);
886
+ return Object.getOwnPropertySymbols(value).length === 0 && keys.length === expected.length && expected.every((key) => Object.prototype.hasOwnProperty.call(value, key));
887
+ }
888
+ isSequence(value) {
889
+ return Number.isSafeInteger(value) && Number(value) >= 0;
890
+ }
891
+ isIdentity(value) {
892
+ return typeof value === "string" && value.length <= this.limits.maxIdentityBytes && value.trim().length > 0 && this.isWithinUtf8Limit(value, this.limits.maxIdentityBytes) && !/[\u0000-\u001f\u007f]/.test(value);
893
+ }
894
+ isLabel(value) {
895
+ return typeof value === "string" && value.length <= Math.min(256, this.limits.maxIdentityBytes) && /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/.test(value) && this.isWithinUtf8Limit(value, Math.min(256, this.limits.maxIdentityBytes));
896
+ }
897
+ isMonotonicTimestamp(value) {
898
+ return value === null || typeof value === "string" && value.length <= this.limits.maxIdentityBytes && /^\d+$/.test(value) && this.isWithinUtf8Limit(value, this.limits.maxIdentityBytes);
899
+ }
900
+ isConversationId(value) {
901
+ return value === null || typeof value === "number" && Number.isSafeInteger(value) || typeof value === "string" && this.isWithinUtf8Limit(value, this.limits.maxIdentityBytes) && !/[\u0000-\u001f\u007f]/.test(value);
902
+ }
903
+ isOptionalBoundedString(value) {
904
+ return value === null || typeof value === "string" && this.isWithinUtf8Limit(value, this.limits.maxIdentityBytes) && !/[\u0000-\u001f\u007f]/.test(value);
905
+ }
906
+ isWithinUtf8Limit(value, maximum) {
907
+ return value.length <= maximum && telemetryUtf8Length(value) <= maximum;
908
+ }
909
+ validateLimits() {
910
+ const values = Object.values(this.limits);
911
+ if (values.some((value) => !Number.isSafeInteger(value) || value <= 0)) {
912
+ throw new Error("Telemetry batch validation limits must be positive safe integers");
913
+ }
914
+ if (this.limits.maxMetadataBytes > this.limits.maxEventBytes || this.limits.maxEventBytes > this.limits.maxBatchBytes) {
915
+ throw new Error("Telemetry receiver byte limits must satisfy metadata <= event <= batch");
916
+ }
917
+ }
918
+ };
919
+
920
+ // src/adapters/trace/wood_telemetry_batch_adapter.ts
921
+ var WoodTelemetryBatchAdapter = class {
922
+ constructor(metadataLimits, producerIdPrefix = "wood-renderer:") {
923
+ this.producerIdPrefix = producerIdPrefix;
924
+ this.snapshotter = new BoundedMetadataSnapshotter(metadataLimits);
925
+ }
926
+ producerIdPrefix;
927
+ batchContract = new TelemetryBatchContract();
928
+ snapshotter;
929
+ create(batch, context = {}) {
930
+ try {
931
+ const identityError = this.validateBatchIdentity(batch);
932
+ if (identityError !== null) {
933
+ return { ok: false, error: identityError };
934
+ }
935
+ const producerId = `${this.producerIdPrefix}${batch.producerId}`;
936
+ const envelopes = batch.events.map((event) => {
937
+ return this.createEnvelope(producerId, batch, event, context);
938
+ });
939
+ return this.batchContract.create(envelopes, []);
940
+ } catch (cause) {
941
+ return { ok: false, error: this.errorMessage(cause) };
942
+ }
943
+ }
944
+ createEnvelope(producerId, batch, event, context) {
945
+ const sequence = event.traceSeq - 1;
946
+ const occurredAtMs = Date.parse(event.timestamp);
947
+ if (!Number.isSafeInteger(sequence) || sequence < 0 || !Number.isFinite(occurredAtMs)) {
948
+ throw new Error("Wood trace event timing is invalid");
949
+ }
950
+ if (!event.source.trim() || !event.type.trim() || !event.level.trim() || !event.process.trim()) {
951
+ throw new Error("Wood trace event identity is invalid");
952
+ }
953
+ const payload = this.snapshotter.snapshot(event.payload ?? {}).metadata;
954
+ const metadata = this.snapshotter.snapshot({
955
+ ...payload,
956
+ ...typeof event.message === "string" ? { message: event.message } : {},
957
+ woodTraceSeq: event.traceSeq,
958
+ __telemetryWoodBatchId: batch.batchId,
959
+ woodRendererProducerId: batch.producerId,
960
+ woodRendererSequenceStart: batch.sequenceStart,
961
+ woodRendererSequenceEnd: batch.sequenceEnd,
962
+ ...context
963
+ }).metadata;
964
+ const metadataConversationId = this.scalarConversationId(metadata.conversationId) ?? this.scalarConversationId(metadata.threadId);
965
+ const conversationId = this.scalarConversationId(event.conversationId) ?? metadataConversationId;
966
+ const correlationId = typeof metadata.correlationId === "string" ? metadata.correlationId : null;
967
+ return Object.freeze({
968
+ schemaVersion: 1,
969
+ eventId: `${producerId}:${sequence}`,
970
+ producerId,
971
+ sequence,
972
+ occurredAtMs,
973
+ monotonicNs: null,
974
+ source: event.source,
975
+ processKind: event.process,
976
+ level: event.level,
977
+ label: event.type,
978
+ conversationId,
979
+ correlationId,
980
+ metadata
981
+ });
982
+ }
983
+ validateBatchIdentity(batch) {
984
+ if (!batch.producerId.trim() || !batch.batchId.trim() || batch.events.length === 0) {
985
+ return "Wood trace batch identity is invalid";
986
+ }
987
+ const first = batch.events[0];
988
+ const last = batch.events[batch.events.length - 1];
989
+ const rangeMatches = first?.traceSeq === batch.sequenceStart + 1 && last?.traceSeq === batch.sequenceEnd + 1;
990
+ const sequencesIncrease = batch.events.every((event, index) => {
991
+ const previous = batch.events[index - 1];
992
+ return previous === void 0 || event.traceSeq > previous.traceSeq;
993
+ });
994
+ return rangeMatches && sequencesIncrease ? null : "Wood trace batch sequence range is invalid";
995
+ }
996
+ scalarConversationId(value) {
997
+ return typeof value === "string" || typeof value === "number" ? value : null;
998
+ }
999
+ errorMessage(cause) {
1000
+ return cause instanceof Error ? cause.message : String(cause);
1001
+ }
1002
+ };
1003
+ export {
1004
+ TraceTelemetryAdapter,
1005
+ WoodTelemetryBatchAdapter
1006
+ };
1007
+ //# sourceMappingURL=index.js.map