@softistx/telemetry 0.0.0-stage → 0.4.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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +977 -2
  3. package/dist/attributes/attributes.d.ts +43 -0
  4. package/dist/attributes/attributes.d.ts.map +1 -0
  5. package/dist/context/current.d.ts +43 -0
  6. package/dist/context/current.d.ts.map +1 -0
  7. package/dist/export/console.d.ts +20 -0
  8. package/dist/export/console.d.ts.map +1 -0
  9. package/dist/export/exporter.d.ts +39 -0
  10. package/dist/export/exporter.d.ts.map +1 -0
  11. package/dist/export/file.d.ts +43 -0
  12. package/dist/export/file.d.ts.map +1 -0
  13. package/dist/export/json-lines.d.ts +17 -0
  14. package/dist/export/json-lines.d.ts.map +1 -0
  15. package/dist/export/memory.d.ts +30 -0
  16. package/dist/export/memory.d.ts.map +1 -0
  17. package/dist/export/pipeline.d.ts +71 -0
  18. package/dist/export/pipeline.d.ts.map +1 -0
  19. package/dist/export/rotation.d.ts +46 -0
  20. package/dist/export/rotation.d.ts.map +1 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +1180 -0
  24. package/dist/index.js.map +29 -0
  25. package/dist/logger/event.d.ts +15 -0
  26. package/dist/logger/event.d.ts.map +1 -0
  27. package/dist/logger/logger.d.ts +46 -0
  28. package/dist/logger/logger.d.ts.map +1 -0
  29. package/dist/logger/standard-schema.d.ts +32 -0
  30. package/dist/logger/standard-schema.d.ts.map +1 -0
  31. package/dist/model/error.d.ts +21 -0
  32. package/dist/model/error.d.ts.map +1 -0
  33. package/dist/model/signal.d.ts +90 -0
  34. package/dist/model/signal.d.ts.map +1 -0
  35. package/dist/span/begin.d.ts +17 -0
  36. package/dist/span/begin.d.ts.map +1 -0
  37. package/dist/span/handle.d.ts +40 -0
  38. package/dist/span/handle.d.ts.map +1 -0
  39. package/dist/span/scope.d.ts +71 -0
  40. package/dist/span/scope.d.ts.map +1 -0
  41. package/dist/span/span.d.ts +15 -0
  42. package/dist/span/span.d.ts.map +1 -0
  43. package/dist/span/sync.d.ts +5 -0
  44. package/dist/span/sync.d.ts.map +1 -0
  45. package/dist/telemetry/telemetry.d.ts +89 -0
  46. package/dist/telemetry/telemetry.d.ts.map +1 -0
  47. package/dist/trace/ids.d.ts +60 -0
  48. package/dist/trace/ids.d.ts.map +1 -0
  49. package/dist/trace/sampler.d.ts +31 -0
  50. package/dist/trace/sampler.d.ts.map +1 -0
  51. package/package.json +57 -5
package/dist/index.js ADDED
@@ -0,0 +1,1180 @@
1
+ // src/attributes/attributes.ts
2
+ var EMPTY_ATTRIBUTES = Object.freeze({});
3
+ var UNREADABLE = "[unreadable]";
4
+ function coerceAttribute(value) {
5
+ try {
6
+ return coerce(value);
7
+ } catch {
8
+ return UNREADABLE;
9
+ }
10
+ }
11
+ function coerce(value) {
12
+ if (value === null || value === undefined)
13
+ return null;
14
+ switch (typeof value) {
15
+ case "string":
16
+ case "boolean":
17
+ return value;
18
+ case "number":
19
+ return Number.isFinite(value) ? value : String(value);
20
+ case "bigint":
21
+ return String(value);
22
+ case "symbol":
23
+ case "function":
24
+ return null;
25
+ }
26
+ if (value instanceof Date) {
27
+ const at = value.getTime();
28
+ return Number.isNaN(at) ? String(value) : value.toISOString();
29
+ }
30
+ if (Array.isArray(value))
31
+ return value.map(coerceScalar);
32
+ return render(value);
33
+ }
34
+ function attributesOf(input) {
35
+ if (input === undefined || input === null)
36
+ return EMPTY_ATTRIBUTES;
37
+ let keys;
38
+ try {
39
+ keys = Object.keys(input);
40
+ } catch {
41
+ return EMPTY_ATTRIBUTES;
42
+ }
43
+ const attributes = {};
44
+ let any = false;
45
+ for (const key of keys) {
46
+ let value;
47
+ try {
48
+ value = input[key];
49
+ } catch {
50
+ attributes[key] = UNREADABLE;
51
+ any = true;
52
+ continue;
53
+ }
54
+ if (value === undefined)
55
+ continue;
56
+ attributes[key] = coerceAttribute(value);
57
+ any = true;
58
+ }
59
+ return any ? attributes : EMPTY_ATTRIBUTES;
60
+ }
61
+ function mergeAttributes(left, right) {
62
+ if (left === right)
63
+ return left;
64
+ if (isEmpty(left))
65
+ return right;
66
+ if (isEmpty(right))
67
+ return left;
68
+ return { ...left, ...right };
69
+ }
70
+ function isEmptyAttributes(attributes) {
71
+ return isEmpty(attributes);
72
+ }
73
+ function isEmpty(attributes) {
74
+ for (const _ in attributes)
75
+ return false;
76
+ return true;
77
+ }
78
+ function coerceScalar(value) {
79
+ const coerced = coerceAttribute(value);
80
+ return Array.isArray(coerced) ? render(value) : coerced;
81
+ }
82
+ function render(value) {
83
+ try {
84
+ const json = JSON.stringify(value);
85
+ if (json !== undefined)
86
+ return json;
87
+ } catch {}
88
+ try {
89
+ return String(value);
90
+ } catch {
91
+ return UNREADABLE;
92
+ }
93
+ }
94
+ // src/context/current.ts
95
+ import * as asyncHooks from "node:async_hooks";
96
+
97
+ // src/export/pipeline.ts
98
+ class Pipeline {
99
+ options;
100
+ buffer = [];
101
+ timer;
102
+ draining = Promise.resolve();
103
+ closed = false;
104
+ closing;
105
+ constructor(options) {
106
+ this.options = options;
107
+ }
108
+ post(signal) {
109
+ if (this.closed)
110
+ return false;
111
+ this.buffer.push(signal);
112
+ if (this.buffer.length >= this.options.batch) {
113
+ this.flush();
114
+ } else if (this.timer === undefined) {
115
+ this.timer = setTimeout(() => {
116
+ this.timer = undefined;
117
+ this.flush();
118
+ }, this.options.linger);
119
+ this.timer.unref?.();
120
+ }
121
+ return true;
122
+ }
123
+ close() {
124
+ this.closing ??= this.drainAndClose();
125
+ return this.closing;
126
+ }
127
+ async drain() {
128
+ this.flush();
129
+ const deadline = timeout(this.options.drainTimeout);
130
+ let drained;
131
+ try {
132
+ drained = await Promise.race([
133
+ this.draining.then(() => true),
134
+ deadline.promise.then(() => false)
135
+ ]);
136
+ } finally {
137
+ deadline.cancel();
138
+ }
139
+ if (!drained) {
140
+ this.report(new Error(`[telemetry] the backlog did not ship within ${this.options.drainTimeout}ms; flush gave up waiting`));
141
+ }
142
+ }
143
+ flush() {
144
+ this.clearTimer();
145
+ if (this.buffer.length === 0)
146
+ return;
147
+ const batch = this.buffer;
148
+ this.buffer = [];
149
+ this.draining = this.draining.then(() => this.ship(batch));
150
+ }
151
+ clearTimer() {
152
+ if (this.timer === undefined)
153
+ return;
154
+ clearTimeout(this.timer);
155
+ this.timer = undefined;
156
+ }
157
+ async ship(batch) {
158
+ for (const exporter of this.options.exporters) {
159
+ try {
160
+ await exporter.export(this.options.resource, batch);
161
+ } catch (failure) {
162
+ this.report(failure);
163
+ }
164
+ }
165
+ }
166
+ async drainAndClose() {
167
+ this.closed = true;
168
+ this.flush();
169
+ const deadline = timeout(this.options.drainTimeout);
170
+ try {
171
+ const drained = await Promise.race([
172
+ this.draining.then(() => true),
173
+ deadline.promise.then(() => false)
174
+ ]);
175
+ if (!drained) {
176
+ this.report(new Error(`[telemetry] the backlog did not ship within ${this.options.drainTimeout}ms; closing anyway`));
177
+ }
178
+ await Promise.race([this.closeExporters(), deadline.promise]);
179
+ } finally {
180
+ deadline.cancel();
181
+ }
182
+ }
183
+ async closeExporters() {
184
+ for (const exporter of this.options.exporters) {
185
+ try {
186
+ await exporter.close?.();
187
+ } catch (failure) {
188
+ this.report(failure);
189
+ }
190
+ }
191
+ }
192
+ report(failure) {
193
+ try {
194
+ this.options.onExportError(failure);
195
+ } catch {}
196
+ }
197
+ }
198
+ function timeout(milliseconds) {
199
+ let timer;
200
+ const promise = new Promise((resolve) => {
201
+ timer = setTimeout(resolve, milliseconds);
202
+ timer.unref?.();
203
+ });
204
+ return {
205
+ promise,
206
+ cancel: () => {
207
+ if (timer !== undefined)
208
+ clearTimeout(timer);
209
+ }
210
+ };
211
+ }
212
+
213
+ // src/trace/ids.ts
214
+ var INVALID_TRACE_ID = "0".repeat(32);
215
+ var INVALID_SPAN_ID = "0".repeat(16);
216
+ var TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
217
+ var SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;
218
+ var HEX_PATTERN = /^[0-9a-f]+$/;
219
+ function isValidTraceId(hex) {
220
+ return TRACE_ID_PATTERN.test(hex) && hex !== INVALID_TRACE_ID;
221
+ }
222
+ function isValidSpanId(hex) {
223
+ return SPAN_ID_PATTERN.test(hex) && hex !== INVALID_SPAN_ID;
224
+ }
225
+ function randomTraceId() {
226
+ return randomHex(16);
227
+ }
228
+ function randomSpanId() {
229
+ return randomHex(8);
230
+ }
231
+ var DETACHED_SPAN_CONTEXT = Object.freeze({
232
+ traceId: INVALID_TRACE_ID,
233
+ spanId: INVALID_SPAN_ID,
234
+ sampled: false,
235
+ remote: false
236
+ });
237
+ function isDetached(context) {
238
+ return !isValidTraceId(context.traceId);
239
+ }
240
+ function renderTraceparent(context) {
241
+ return `00-${context.traceId}-${context.spanId}-${context.sampled ? "01" : "00"}`;
242
+ }
243
+ function parseTraceparent(header) {
244
+ if (!header)
245
+ return null;
246
+ const parts = header.trim().toLowerCase().split("-");
247
+ if (parts.length < 4)
248
+ return null;
249
+ const [version, traceId, spanId, flags] = parts;
250
+ if (version.length !== 2 || !HEX_PATTERN.test(version) || version === "ff") {
251
+ return null;
252
+ }
253
+ if (!isValidTraceId(traceId) || !isValidSpanId(spanId))
254
+ return null;
255
+ if (!HEX_PATTERN.test(flags))
256
+ return null;
257
+ const parsed = Number.parseInt(flags, 16);
258
+ if (Number.isNaN(parsed))
259
+ return null;
260
+ return {
261
+ traceId,
262
+ spanId,
263
+ sampled: (parsed & 1) === 1,
264
+ remote: true
265
+ };
266
+ }
267
+ var HEX = "0123456789abcdef";
268
+ function randomHex(bytes) {
269
+ const buffer = new Uint8Array(bytes);
270
+ crypto.getRandomValues(buffer);
271
+ let hex = "";
272
+ for (const byte of buffer) {
273
+ hex += HEX[byte >> 4];
274
+ hex += HEX[byte & 15];
275
+ }
276
+ return hex;
277
+ }
278
+
279
+ // src/trace/sampler.ts
280
+ var alwaysSample = { sample: () => true };
281
+ var neverSample = { sample: () => false };
282
+ var MAX_UINT64 = (1n << 64n) - 1n;
283
+ var SCALE = 1n << 53n;
284
+ function ratioSampler(ratio) {
285
+ if (!Number.isFinite(ratio) || ratio < 0 || ratio > 1) {
286
+ throw new RangeError(`A sampling ratio is between 0 and 1, not ${ratio}`);
287
+ }
288
+ if (ratio === 0)
289
+ return neverSample;
290
+ if (ratio === 1)
291
+ return alwaysSample;
292
+ const threshold = BigInt(Math.round(ratio * Number(SCALE))) * MAX_UINT64 / SCALE;
293
+ return {
294
+ sample(traceId) {
295
+ if (!isValidTraceId(traceId))
296
+ return false;
297
+ return BigInt(`0x${traceId.slice(-16)}`) < threshold;
298
+ }
299
+ };
300
+ }
301
+
302
+ // src/telemetry/telemetry.ts
303
+ var TELEMETRY_DEFAULTS = Object.freeze({
304
+ minimum: "info",
305
+ stackTraces: true,
306
+ batch: 512,
307
+ linger: 1000,
308
+ drainTimeout: 1e4
309
+ });
310
+ var installed;
311
+
312
+ class Telemetry {
313
+ resource;
314
+ sampler;
315
+ minimum;
316
+ stackTraces;
317
+ pipeline;
318
+ constructor(options) {
319
+ this.resource = {
320
+ service: options.service,
321
+ ...options.version === undefined ? {} : { version: options.version },
322
+ ...options.environment === undefined ? {} : { environment: options.environment },
323
+ attributes: attributesOf(options.attributes)
324
+ };
325
+ this.sampler = options.sampler ?? alwaysSample;
326
+ this.minimum = options.minimum ?? TELEMETRY_DEFAULTS.minimum;
327
+ this.stackTraces = options.stackTraces ?? TELEMETRY_DEFAULTS.stackTraces;
328
+ this.pipeline = new Pipeline({
329
+ resource: this.resource,
330
+ exporters: options.exporters ?? [],
331
+ batch: options.batch ?? TELEMETRY_DEFAULTS.batch,
332
+ linger: options.linger ?? TELEMETRY_DEFAULTS.linger,
333
+ drainTimeout: options.drainTimeout ?? TELEMETRY_DEFAULTS.drainTimeout,
334
+ onExportError: options.onExportError ?? defaultOnExportError
335
+ });
336
+ }
337
+ emit(signal) {
338
+ return this.pipeline.post(signal);
339
+ }
340
+ flush() {
341
+ return this.pipeline.drain();
342
+ }
343
+ install() {
344
+ installed = this;
345
+ return this;
346
+ }
347
+ async close() {
348
+ if (installed === this)
349
+ installed = undefined;
350
+ await this.pipeline.close();
351
+ }
352
+ async[Symbol.asyncDispose]() {
353
+ await this.close();
354
+ }
355
+ }
356
+ function createTelemetry(service, options = {}) {
357
+ return new Telemetry({ ...options, service });
358
+ }
359
+ function installedTelemetry() {
360
+ return installed;
361
+ }
362
+ function uninstallTelemetry(telemetry) {
363
+ if (telemetry === undefined || installed === telemetry)
364
+ installed = undefined;
365
+ }
366
+ function defaultOnExportError(failure) {
367
+ console.error("[telemetry] export failed", failure);
368
+ }
369
+
370
+ // src/context/current.ts
371
+ var storage = createStorage();
372
+ function currentContext() {
373
+ return storage.getStore();
374
+ }
375
+ function runWithContext(context, fn) {
376
+ return storage.run(context, fn);
377
+ }
378
+ function resolveTelemetry() {
379
+ return currentContext()?.telemetry ?? installedTelemetry();
380
+ }
381
+ function withTelemetry(telemetry, fn) {
382
+ const context = currentContext();
383
+ return runWithContext({
384
+ telemetry,
385
+ ...context?.span === undefined ? {} : { span: context.span },
386
+ attributes: context?.attributes ?? EMPTY_ATTRIBUTES
387
+ }, fn);
388
+ }
389
+ function withAttributes(attributes, fn) {
390
+ const given = attributesOf(attributes);
391
+ const context = currentContext();
392
+ if (context === undefined) {
393
+ const telemetry = installedTelemetry();
394
+ if (telemetry === undefined)
395
+ return fn();
396
+ return runWithContext({ telemetry, attributes: given }, fn);
397
+ }
398
+ return runWithContext({ ...context, attributes: mergeAttributes(context.attributes, given) }, fn);
399
+ }
400
+ function currentSpan() {
401
+ return currentContext()?.span;
402
+ }
403
+ function currentTraceparent() {
404
+ const span = currentSpan();
405
+ return span === undefined ? undefined : renderTraceparent(span);
406
+ }
407
+ function currentAttributes() {
408
+ return currentContext()?.attributes ?? EMPTY_ATTRIBUTES;
409
+ }
410
+ function createStorage() {
411
+ const AsyncLocalStorage2 = asyncHooks.AsyncLocalStorage;
412
+ if (typeof AsyncLocalStorage2 === "function") {
413
+ return new AsyncLocalStorage2;
414
+ }
415
+ let current;
416
+ return {
417
+ getStore: () => current,
418
+ run(context, fn) {
419
+ const previous = current;
420
+ current = context;
421
+ try {
422
+ return fn();
423
+ } finally {
424
+ current = previous;
425
+ }
426
+ }
427
+ };
428
+ }
429
+ // src/export/console.ts
430
+ function consoleExporter(options = {}) {
431
+ const write = options.write ?? ((line) => console.log(line));
432
+ const stackTraces = options.stackTraces ?? true;
433
+ return {
434
+ export(_resource, batch) {
435
+ for (const signal of batch) {
436
+ write(signal.type === "log" ? renderLog(signal) : renderSpan(signal));
437
+ const error = signal.error;
438
+ if (stackTraces && error?.stackTrace)
439
+ write(error.stackTrace);
440
+ }
441
+ }
442
+ };
443
+ }
444
+ function renderLog(log) {
445
+ return [
446
+ clock(log.at),
447
+ log.severity.toUpperCase().padEnd(5),
448
+ log.source,
449
+ log.name,
450
+ renderAttributes(log.attributes),
451
+ renderError(log.error),
452
+ renderTrace(log)
453
+ ].filter(Boolean).join(" ");
454
+ }
455
+ function renderSpan(span) {
456
+ return [
457
+ clock(span.endedAt),
458
+ "SPAN ",
459
+ span.name,
460
+ `${span.endedAt - span.startedAt}ms`,
461
+ span.status === "ok" ? "" : span.status.toUpperCase(),
462
+ renderAttributes(span.attributes),
463
+ renderError(span.error),
464
+ renderTrace(span)
465
+ ].filter(Boolean).join(" ");
466
+ }
467
+ function clock(at) {
468
+ if (!Number.isFinite(at) || Math.abs(at) > 8640000000000000)
469
+ return String(at);
470
+ return new Date(at).toISOString().slice(11, 23);
471
+ }
472
+ function renderAttributes(attributes) {
473
+ return Object.entries(attributes).map(([key, value]) => `${key}=${renderValue(value)}`).join(" ");
474
+ }
475
+ function renderValue(value) {
476
+ return Array.isArray(value) ? `[${value.join(",")}]` : String(value);
477
+ }
478
+ function renderError(error) {
479
+ if (error === undefined)
480
+ return "";
481
+ return error.message ? `${error.type}: ${error.message}` : error.type;
482
+ }
483
+ function renderTrace(signal) {
484
+ const span = signal.type === "log" ? signal.span : signal.context;
485
+ if (span === undefined)
486
+ return "";
487
+ return `[${span.traceId.slice(0, 8)}/${span.spanId.slice(0, 8)}]`;
488
+ }
489
+ // src/export/file.ts
490
+ import {
491
+ appendFile,
492
+ mkdir,
493
+ readdir,
494
+ readFile,
495
+ rename,
496
+ rm,
497
+ stat,
498
+ writeFile
499
+ } from "node:fs/promises";
500
+ import { dirname, join } from "node:path";
501
+ import { promisify } from "node:util";
502
+ import { gzip } from "node:zlib";
503
+
504
+ // src/export/rotation.ts
505
+ import { basename } from "node:path";
506
+ function rotationDue(size, openedAt, now, policy) {
507
+ if (size <= 0)
508
+ return false;
509
+ if (policy.maxSize > 0 && size >= policy.maxSize)
510
+ return true;
511
+ return policy.every > 0 && period(openedAt, policy) !== period(now, policy);
512
+ }
513
+ function rolledName(path, at, taken = 0) {
514
+ const file = basename(path);
515
+ const directory = path.slice(0, path.length - file.length);
516
+ const dot = file.lastIndexOf(".");
517
+ const base = dot <= 0 ? file : file.slice(0, dot);
518
+ const extension = dot <= 0 ? "" : file.slice(dot);
519
+ const suffix = taken === 0 ? "" : `-${taken}`;
520
+ return `${directory}${base}-${stamp(at)}${suffix}${extension}`;
521
+ }
522
+ function rolledOf(path, names) {
523
+ const found = new Map;
524
+ for (const name of names) {
525
+ const rolled = parse(path, name);
526
+ if (rolled === undefined)
527
+ continue;
528
+ const key = `${rolled.at}-${rolled.taken}`;
529
+ const seen = found.get(key);
530
+ if (seen === undefined || name.endsWith(".gz")) {
531
+ found.set(key, { ...rolled, name });
532
+ }
533
+ }
534
+ return [...found.values()].sort((one, other) => other.at.localeCompare(one.at) || other.taken - one.taken).map((rolled) => rolled.name);
535
+ }
536
+ function prunable(path, names, keep) {
537
+ const kept = new Set(rolledOf(path, names).slice(0, Math.max(keep, 0)));
538
+ return names.filter((name) => parse(path, name) !== undefined && !kept.has(name));
539
+ }
540
+ function period(at, policy) {
541
+ return Math.floor(at / policy.every);
542
+ }
543
+ function parse(path, name) {
544
+ const file = basename(path);
545
+ const dot = file.lastIndexOf(".");
546
+ const base = dot <= 0 ? file : file.slice(0, dot);
547
+ const extension = dot <= 0 ? "" : file.slice(dot);
548
+ const pattern = new RegExp(`^${escapeRegex(base)}-(\\d{8}-\\d{6})(?:-(\\d+))?${escapeRegex(extension)}(\\.gz)?$`);
549
+ const found = pattern.exec(name);
550
+ if (found === null)
551
+ return;
552
+ return { at: found[1], taken: Number(found[2] ?? 0) };
553
+ }
554
+ function stamp(at) {
555
+ const iso = new Date(at).toISOString();
556
+ return `${iso.slice(0, 10).replaceAll("-", "")}-${iso.slice(11, 19).replaceAll(":", "")}`;
557
+ }
558
+ function escapeRegex(text) {
559
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
560
+ }
561
+
562
+ // src/export/file.ts
563
+ var compressed = promisify(gzip);
564
+ var DEFAULT_MAX_SIZE = 64 * 1024 * 1024;
565
+ var DEFAULT_ROTATION_PERIOD = 24 * 60 * 60 * 1000;
566
+ var MAX_COLLISIONS = 1000;
567
+ function fileExporter(options) {
568
+ const policy = {
569
+ maxSize: options.maxSize ?? DEFAULT_MAX_SIZE,
570
+ every: options.every ?? DEFAULT_ROTATION_PERIOD,
571
+ keep: options.keep ?? 7,
572
+ compress: options.compress ?? false
573
+ };
574
+ const now = options.now ?? Date.now;
575
+ const path = options.path;
576
+ let state;
577
+ let queue = Promise.resolve();
578
+ const write = async (batch) => {
579
+ const text = render2(batch);
580
+ if (text.length === 0)
581
+ return;
582
+ try {
583
+ state ??= await currentState(path, now());
584
+ if (rotationDue(state.size, state.openedAt, now(), policy)) {
585
+ await roll(path, now(), policy);
586
+ state = { size: 0, openedAt: now() };
587
+ }
588
+ await appendFile(path, text, "utf8");
589
+ state.size += Buffer.byteLength(text, "utf8");
590
+ } catch (failure) {
591
+ state = undefined;
592
+ throw failure;
593
+ }
594
+ };
595
+ return {
596
+ export(_resource, batch) {
597
+ const next = queue.then(() => write(batch));
598
+ queue = next.catch(() => {
599
+ return;
600
+ });
601
+ return next;
602
+ }
603
+ };
604
+ }
605
+ function render2(batch) {
606
+ let text = "";
607
+ for (const signal of batch) {
608
+ try {
609
+ text += `${JSON.stringify(signal)}
610
+ `;
611
+ } catch {}
612
+ }
613
+ return text;
614
+ }
615
+ async function currentState(path, fallback) {
616
+ await mkdir(dirname(path), { recursive: true });
617
+ try {
618
+ const found = await stat(path);
619
+ return { size: found.size, openedAt: found.mtimeMs };
620
+ } catch {
621
+ return { size: 0, openedAt: fallback };
622
+ }
623
+ }
624
+ async function roll(path, at, policy) {
625
+ const target = await freeName(path, at);
626
+ await rename(path, target);
627
+ if (policy.compress)
628
+ await compress(target);
629
+ await prune(path, policy.keep);
630
+ }
631
+ async function freeName(path, at) {
632
+ for (let taken = 0;taken < MAX_COLLISIONS; taken++) {
633
+ const candidate = rolledName(path, at, taken);
634
+ if (!await exists(candidate) && !await exists(`${candidate}.gz`)) {
635
+ return candidate;
636
+ }
637
+ }
638
+ throw new Error(`[telemetry] ${MAX_COLLISIONS} archives of ${path} already share this second`);
639
+ }
640
+ async function compress(path) {
641
+ const pending = `${path}.gz.pending`;
642
+ await writeFile(pending, await compressed(await readFile(path)));
643
+ await rename(pending, `${path}.gz`);
644
+ await rm(path, { force: true });
645
+ }
646
+ async function prune(path, keep) {
647
+ const directory = dirname(path);
648
+ const names = await readdir(directory);
649
+ for (const name of prunable(path, names, keep)) {
650
+ await rm(join(directory, name), { force: true });
651
+ }
652
+ }
653
+ async function exists(path) {
654
+ return stat(path).then(() => true, () => false);
655
+ }
656
+ // src/export/json-lines.ts
657
+ function jsonLinesExporter(options = {}) {
658
+ const write = options.write ?? ((line) => console.log(line));
659
+ return {
660
+ export(_resource, batch) {
661
+ for (const signal of batch) {
662
+ const line = render3(signal);
663
+ if (line !== undefined)
664
+ write(line);
665
+ }
666
+ }
667
+ };
668
+ }
669
+ function render3(signal) {
670
+ try {
671
+ return JSON.stringify(signal);
672
+ } catch {
673
+ return;
674
+ }
675
+ }
676
+ // src/export/memory.ts
677
+ function memoryExporter() {
678
+ const spans = [];
679
+ const logs = [];
680
+ return {
681
+ spans,
682
+ logs,
683
+ export(_resource, batch) {
684
+ for (const signal of batch) {
685
+ if (signal.type === "span")
686
+ spans.push(signal);
687
+ else
688
+ logs.push(signal);
689
+ }
690
+ },
691
+ clear() {
692
+ spans.length = 0;
693
+ logs.length = 0;
694
+ },
695
+ flush: () => Promise.resolve()
696
+ };
697
+ }
698
+ // src/logger/event.ts
699
+ var INVALID_EVENT_ATTRIBUTE = "telemetry.event.invalid";
700
+ function event(name, schema) {
701
+ return (input) => {
702
+ if (schema === undefined)
703
+ return { name, attributes: attributesOf(input) };
704
+ let result;
705
+ try {
706
+ result = schema["~standard"].validate(input);
707
+ } catch {
708
+ return invalid(name, input);
709
+ }
710
+ if (isThenable(result)) {
711
+ Promise.resolve(result).catch(() => {
712
+ return;
713
+ });
714
+ return invalid(name, input);
715
+ }
716
+ const checked = result;
717
+ if (checked.issues !== undefined)
718
+ return invalid(name, input);
719
+ return { name, attributes: fields(checked.value) };
720
+ };
721
+ }
722
+ function isTelemetryEvent(value) {
723
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.attributes === "object";
724
+ }
725
+ function invalid(name, input) {
726
+ return {
727
+ name,
728
+ attributes: { ...attributesOf(input), [INVALID_EVENT_ATTRIBUTE]: true },
729
+ invalid: true
730
+ };
731
+ }
732
+ function fields(value) {
733
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
734
+ return attributesOf(value);
735
+ }
736
+ return { value: coerceAttribute(value) };
737
+ }
738
+ function isThenable(value) {
739
+ return typeof value === "object" && value !== null && typeof value.then === "function";
740
+ }
741
+ // src/model/error.ts
742
+ function errorInfo(failure, stackTraces = true) {
743
+ try {
744
+ return flatten(failure, stackTraces);
745
+ } catch {
746
+ return { type: "Error", message: UNREADABLE };
747
+ }
748
+ }
749
+ function isAbort(failure) {
750
+ if (typeof failure !== "object" || failure === null)
751
+ return false;
752
+ const name = read(failure, "name");
753
+ return name === "AbortError" || name === "TimeoutError";
754
+ }
755
+ function flatten(failure, stackTraces) {
756
+ if (isError(failure)) {
757
+ const message = read(failure, "message");
758
+ const stack = stackTraces ? read(failure, "stack") : undefined;
759
+ return {
760
+ type: errorType(failure),
761
+ ...typeof message === "string" && message ? { message } : {},
762
+ ...typeof stack === "string" && stack ? { stackTrace: stack } : {}
763
+ };
764
+ }
765
+ return { type: typeName(failure), message: describe(failure) };
766
+ }
767
+ function isError(value) {
768
+ try {
769
+ if (value instanceof Error)
770
+ return true;
771
+ return typeof value === "object" && value !== null && Object.prototype.toString.call(value) === "[object Error]";
772
+ } catch {
773
+ return false;
774
+ }
775
+ }
776
+ function errorType(failure) {
777
+ const name = read(failure, "name");
778
+ const named = typeof name === "string" && name ? name : undefined;
779
+ if (named !== undefined && named !== "Error")
780
+ return named;
781
+ const constructed = constructorName(failure);
782
+ if (constructed !== undefined && constructed !== "Object")
783
+ return constructed;
784
+ return named ?? "Error";
785
+ }
786
+ function typeName(failure) {
787
+ if (failure === null)
788
+ return "null";
789
+ if (typeof failure !== "object")
790
+ return typeof failure;
791
+ return constructorName(failure) ?? "Object";
792
+ }
793
+ function constructorName(value) {
794
+ const name = read(value, "constructor");
795
+ if (typeof name !== "function" && typeof name !== "object")
796
+ return;
797
+ if (name === null)
798
+ return;
799
+ const own = read(name, "name");
800
+ return typeof own === "string" && own ? own : undefined;
801
+ }
802
+ function read(value, key) {
803
+ try {
804
+ return value[key];
805
+ } catch {
806
+ return;
807
+ }
808
+ }
809
+ function describe(failure) {
810
+ try {
811
+ return typeof failure === "object" && failure !== null ? JSON.stringify(failure) || String(failure) : String(failure);
812
+ } catch {
813
+ return UNREADABLE;
814
+ }
815
+ }
816
+
817
+ // src/model/signal.ts
818
+ var SEVERITY_NUMBER = Object.freeze({
819
+ debug: 5,
820
+ info: 9,
821
+ warn: 13,
822
+ error: 17
823
+ });
824
+ var SEVERITIES = Object.freeze([
825
+ "debug",
826
+ "info",
827
+ "warn",
828
+ "error"
829
+ ]);
830
+ function meetsSeverity(severity, minimum) {
831
+ return SEVERITY_NUMBER[severity] >= SEVERITY_NUMBER[minimum];
832
+ }
833
+ var SPAN_KIND_NUMBER = Object.freeze({
834
+ internal: 1,
835
+ server: 2,
836
+ client: 3,
837
+ producer: 4,
838
+ consumer: 5
839
+ });
840
+ function signalAt(signal) {
841
+ return signal.type === "log" ? signal.at : signal.startedAt;
842
+ }
843
+ function signalSpan(signal) {
844
+ return signal.type === "log" ? signal.span : signal.context;
845
+ }
846
+
847
+ // src/logger/logger.ts
848
+ function createLogger(source) {
849
+ const write = (severity, input, second, third) => {
850
+ const telemetry = resolveTelemetry();
851
+ if (telemetry === undefined)
852
+ return;
853
+ if (!meetsSeverity(severity, telemetry.minimum))
854
+ return;
855
+ const [failure, fields] = split(second, third);
856
+ const span = currentSpan();
857
+ const named = name(input);
858
+ const record = {
859
+ type: "log",
860
+ at: Date.now(),
861
+ severity,
862
+ name: named.name,
863
+ source,
864
+ attributes: mergeAttributes(mergeAttributes(currentAttributes(), named.attributes), attributesOf(fields)),
865
+ ...span === undefined ? {} : { span },
866
+ ...failure === undefined ? {} : { error: errorInfo(failure, telemetry.stackTraces) }
867
+ };
868
+ telemetry.emit(record);
869
+ };
870
+ return {
871
+ enabled(severity) {
872
+ const telemetry = resolveTelemetry();
873
+ return telemetry !== undefined && meetsSeverity(severity, telemetry.minimum);
874
+ },
875
+ debug: (input, attributes) => write("debug", input, attributes),
876
+ info: (input, attributes) => write("info", input, attributes),
877
+ warn: (input, second, third) => write("warn", input, second, third),
878
+ error: (input, second, third) => write("error", input, second, third)
879
+ };
880
+ }
881
+ function split(second, third) {
882
+ if (third !== undefined)
883
+ return [second, third];
884
+ if (second === undefined)
885
+ return [undefined, undefined];
886
+ return isFields(second) ? [undefined, second] : [second, undefined];
887
+ }
888
+ function isFields(value) {
889
+ if (typeof value !== "object" || value === null)
890
+ return false;
891
+ try {
892
+ if (value instanceof Error || Array.isArray(value))
893
+ return false;
894
+ const prototype = Object.getPrototypeOf(value);
895
+ if (prototype === null || prototype === Object.prototype)
896
+ return true;
897
+ return Object.getPrototypeOf(prototype) === null && prototype.constructor?.name === "Object";
898
+ } catch {
899
+ return false;
900
+ }
901
+ }
902
+ function name(input) {
903
+ if (typeof input === "string") {
904
+ return { name: input, attributes: EMPTY_ATTRIBUTES };
905
+ }
906
+ if (isTelemetryEvent(input)) {
907
+ return { name: input.name, attributes: input.attributes };
908
+ }
909
+ try {
910
+ return { name: input(), attributes: EMPTY_ATTRIBUTES };
911
+ } catch (failure) {
912
+ return {
913
+ name: "[message failed to build]",
914
+ attributes: {
915
+ "telemetry.message.invalid": errorInfo(failure, false).type
916
+ }
917
+ };
918
+ }
919
+ }
920
+ // src/span/scope.ts
921
+ class Span {
922
+ name;
923
+ status = "ok";
924
+ context;
925
+ kind;
926
+ stackTraces;
927
+ own = {};
928
+ happened = [];
929
+ error;
930
+ constructor(context, name, kind, stackTraces = true) {
931
+ this.context = context;
932
+ this.name = name;
933
+ this.kind = kind;
934
+ this.stackTraces = stackTraces;
935
+ }
936
+ get traceId() {
937
+ return this.context.traceId;
938
+ }
939
+ get spanId() {
940
+ return this.context.spanId;
941
+ }
942
+ traceparent() {
943
+ return renderTraceparent(this.context);
944
+ }
945
+ attribute(name, value) {
946
+ this.own[name] = coerceAttribute(value);
947
+ }
948
+ attributes(record) {
949
+ Object.assign(this.own, attributesOf(record));
950
+ }
951
+ event(input, attributes) {
952
+ const declared = isTelemetryEvent(input);
953
+ this.happened.push({
954
+ name: declared ? input.name : input,
955
+ at: Date.now(),
956
+ attributes: declared ? input.attributes : attributesOf(attributes)
957
+ });
958
+ }
959
+ fail(failure) {
960
+ if (this.error !== undefined)
961
+ return;
962
+ const cancelled = isAbort(failure);
963
+ this.status = cancelled ? "cancelled" : "error";
964
+ this.error = errorInfo(failure, !cancelled && this.stackTraces);
965
+ }
966
+ record(startedAt, endedAt, parent, inherited) {
967
+ return {
968
+ type: "span",
969
+ name: this.name,
970
+ context: this.context,
971
+ ...parent === undefined ? {} : { parent },
972
+ kind: this.kind,
973
+ startedAt,
974
+ endedAt,
975
+ status: this.status,
976
+ attributes: { ...mergeAttributes(inherited, this.own) },
977
+ events: [...this.happened],
978
+ ...this.error === undefined ? {} : { error: this.error }
979
+ };
980
+ }
981
+ }
982
+ // src/span/begin.ts
983
+ function begin(name, options, remote, fallbackKind, create) {
984
+ const parent = currentContext();
985
+ const telemetry = parent?.telemetry ?? installedTelemetry();
986
+ const kind = options.kind ?? fallbackKind;
987
+ if (telemetry === undefined) {
988
+ return {
989
+ scope: create(DETACHED_SPAN_CONTEXT, name, kind, undefined),
990
+ context: undefined,
991
+ finish: () => {}
992
+ };
993
+ }
994
+ const parentSpan = remote ?? parent?.span;
995
+ const traceId = parentSpan?.traceId ?? randomTraceId();
996
+ const context = {
997
+ traceId,
998
+ spanId: randomSpanId(),
999
+ sampled: parentSpan?.sampled ?? decide(telemetry, traceId),
1000
+ remote: false
1001
+ };
1002
+ const inherited = mergeAttributes(parent?.attributes ?? EMPTY_ATTRIBUTES, attributesOf(options.attributes));
1003
+ const scope = create(context, name, kind, telemetry.stackTraces);
1004
+ const startedAt = Date.now();
1005
+ return {
1006
+ scope,
1007
+ context: { telemetry, span: context, attributes: inherited },
1008
+ finish() {
1009
+ if (!context.sampled)
1010
+ return;
1011
+ try {
1012
+ telemetry.emit(scope.record(startedAt, Date.now(), parentSpan?.spanId, inherited));
1013
+ } catch {}
1014
+ }
1015
+ };
1016
+ }
1017
+ function record(scope, failure) {
1018
+ try {
1019
+ scope.fail(failure);
1020
+ } catch {
1021
+ scope.status = "error";
1022
+ }
1023
+ }
1024
+ function decide(telemetry, traceId) {
1025
+ try {
1026
+ return telemetry.sampler.sample(traceId);
1027
+ } catch {
1028
+ return false;
1029
+ }
1030
+ }
1031
+ function read2(optionsOrBlock, maybeBlock) {
1032
+ return typeof optionsOrBlock === "function" ? [{}, optionsOrBlock] : [optionsOrBlock, maybeBlock];
1033
+ }
1034
+
1035
+ // src/span/handle.ts
1036
+ class Handle extends Span {
1037
+ ended = false;
1038
+ started;
1039
+ bind(started) {
1040
+ this.started = started;
1041
+ }
1042
+ end() {
1043
+ if (this.ended)
1044
+ return;
1045
+ this.ended = true;
1046
+ try {
1047
+ this.started?.finish();
1048
+ } catch {}
1049
+ }
1050
+ run(fn) {
1051
+ const context = this.started?.context;
1052
+ return context === undefined ? fn() : runWithContext(context, fn);
1053
+ }
1054
+ }
1055
+ function startSpan(name, options = {}) {
1056
+ const remote = options.traceparent === undefined || options.traceparent === null ? undefined : parseTraceparent(options.traceparent) ?? undefined;
1057
+ const started = begin(name, options, remote, options.traceparent == null ? "internal" : "server", (context, n, kind, stackTraces) => new Handle(context, n, kind, stackTraces));
1058
+ started.scope.bind(started);
1059
+ return started.scope;
1060
+ }
1061
+ // src/span/sync.ts
1062
+ function spanSync(name, optionsOrBlock, maybeBlock) {
1063
+ const [options, block] = read2(optionsOrBlock, maybeBlock);
1064
+ const started = begin(name, options, undefined, "internal", (context, n, kind, stackTraces) => new Span(context, n, kind, stackTraces));
1065
+ const { scope, context } = started;
1066
+ if (context === undefined)
1067
+ return block(scope);
1068
+ let result;
1069
+ try {
1070
+ result = runWithContext(context, () => block(scope));
1071
+ } catch (failure) {
1072
+ record(scope, failure);
1073
+ started.finish();
1074
+ throw failure;
1075
+ }
1076
+ if (isThenable2(result)) {
1077
+ return result.then((value) => {
1078
+ started.finish();
1079
+ return value;
1080
+ }, (failure) => {
1081
+ record(scope, failure);
1082
+ started.finish();
1083
+ throw failure;
1084
+ });
1085
+ }
1086
+ started.finish();
1087
+ return result;
1088
+ }
1089
+ function isThenable2(value) {
1090
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
1091
+ }
1092
+
1093
+ // src/span/span.ts
1094
+ function span(name, optionsOrBlock, maybeBlock) {
1095
+ const [options, block] = read2(optionsOrBlock, maybeBlock);
1096
+ return open(name, options, block, undefined, "internal");
1097
+ }
1098
+ function continuing(traceparent, name, optionsOrBlock, maybeBlock) {
1099
+ const [options, block] = read2(optionsOrBlock, maybeBlock);
1100
+ const remote = parseTraceparent(traceparent) ?? undefined;
1101
+ return open(name, options, block, remote, "server");
1102
+ }
1103
+ async function open(name, options, block, remote, fallbackKind) {
1104
+ const started = begin(name, options, remote, fallbackKind, (context, n, kind, stackTraces) => new Span(context, n, kind, stackTraces));
1105
+ const { scope, context } = started;
1106
+ if (context === undefined)
1107
+ return block(scope);
1108
+ try {
1109
+ return await runWithContext(context, () => block(scope));
1110
+ } catch (failure) {
1111
+ record(scope, failure);
1112
+ throw failure;
1113
+ } finally {
1114
+ started.finish();
1115
+ }
1116
+ }
1117
+ export {
1118
+ DEFAULT_MAX_SIZE,
1119
+ DEFAULT_ROTATION_PERIOD,
1120
+ DETACHED_SPAN_CONTEXT,
1121
+ EMPTY_ATTRIBUTES,
1122
+ INVALID_EVENT_ATTRIBUTE,
1123
+ INVALID_SPAN_ID,
1124
+ INVALID_TRACE_ID,
1125
+ SEVERITIES,
1126
+ SEVERITY_NUMBER,
1127
+ SPAN_KIND_NUMBER,
1128
+ Span,
1129
+ TELEMETRY_DEFAULTS,
1130
+ Telemetry,
1131
+ UNREADABLE,
1132
+ alwaysSample,
1133
+ attributesOf,
1134
+ coerceAttribute,
1135
+ consoleExporter,
1136
+ continuing,
1137
+ createLogger,
1138
+ createTelemetry,
1139
+ currentAttributes,
1140
+ currentContext,
1141
+ currentSpan,
1142
+ currentTraceparent,
1143
+ errorInfo,
1144
+ event,
1145
+ fileExporter,
1146
+ installedTelemetry,
1147
+ isAbort,
1148
+ isDetached,
1149
+ isEmptyAttributes,
1150
+ isTelemetryEvent,
1151
+ isValidSpanId,
1152
+ isValidTraceId,
1153
+ jsonLinesExporter,
1154
+ meetsSeverity,
1155
+ memoryExporter,
1156
+ mergeAttributes,
1157
+ neverSample,
1158
+ parseTraceparent,
1159
+ prunable,
1160
+ randomSpanId,
1161
+ randomTraceId,
1162
+ ratioSampler,
1163
+ renderTraceparent,
1164
+ resolveTelemetry,
1165
+ rolledName,
1166
+ rolledOf,
1167
+ rotationDue,
1168
+ runWithContext,
1169
+ signalAt,
1170
+ signalSpan,
1171
+ span,
1172
+ spanSync,
1173
+ startSpan,
1174
+ uninstallTelemetry,
1175
+ withAttributes,
1176
+ withTelemetry
1177
+ };
1178
+
1179
+ //# debugId=58B4AD1A2ABF643F64756E2164756E21
1180
+ //# sourceMappingURL=index.js.map