@sypnia/telemetry 0.0.0-stage → 0.3.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.
@@ -0,0 +1,1849 @@
1
+ import { cutChars, routeOf, formatTraceparent, parseTraceparent, redactMessage, baseUrl, pathnameOf, matchesRoute, errorFingerprint } from '../chunk-P5DK2OU7.js';
2
+ import { AsyncLocalStorage } from 'async_hooks';
3
+ import { promisify } from 'util';
4
+ import { gzip as gzip$1 } from 'zlib';
5
+ import diagnostics from 'diagnostics_channel';
6
+ import { randomFillSync } from 'crypto';
7
+ import { createRequire } from 'module';
8
+ import { join } from 'path';
9
+
10
+ // ../node/src/limits.ts
11
+ var LIMITS = {
12
+ /** Spans kept per request besides its server span; the rest are counted in `sypnia.dropped_spans`. */
13
+ spansPerRequest: 200,
14
+ attributesPerSpan: 64,
15
+ attributeChars: 256,
16
+ stackChars: 4e3,
17
+ messageChars: 500,
18
+ /** A failed database call's message, as the database wrote it, is kept up to this many characters. */
19
+ dbMessageChars: 2e3,
20
+ /** Of a failed PostgREST answer, at most this many bytes of its body are read. */
21
+ dbBodyBytes: 4096,
22
+ /** At its end, a request waits at most this long for the failed answers still being read. */
23
+ dbDetailWaitMs: 50,
24
+ spanNameChars: 120,
25
+ serviceChars: 80,
26
+ releaseChars: 40,
27
+ environmentChars: 40,
28
+ idChars: 128,
29
+ digestChars: 100,
30
+ urlPathChars: 500,
31
+ failuresPerRequest: 5,
32
+ logFailuresPerRequest: 3,
33
+ exportIntervalMs: 2e3,
34
+ exportMaxSpans: 512,
35
+ /** Spans waiting in memory; past it the oldest requests without a failure are let go first. */
36
+ queueMaxSpans: 5120,
37
+ /** Waits before each retry of a failed export (the browser SDK uses the same). */
38
+ retryDelaysMs: [1e3, 4e3, 15e3],
39
+ /** The longest `Retry-After` the SDK honours. */
40
+ retryAfterMaxMs: 6e4,
41
+ /** At most one warning a minute. */
42
+ warnEveryMs: 6e4
43
+ };
44
+
45
+ // ../node/src/attributes.ts
46
+ function charsFor(name) {
47
+ if (name === "exception.stacktrace") return LIMITS.stackChars;
48
+ if (name === "exception.message" || name === "status.message") return LIMITS.messageChars;
49
+ if (name === "sypnia.db.message") return LIMITS.dbMessageChars;
50
+ return LIMITS.attributeChars;
51
+ }
52
+ function setAttribute(attributes, name, value) {
53
+ if (value === null || value === void 0) return;
54
+ if (typeof value === "number" && !Number.isFinite(value)) return;
55
+ if (!(name in attributes) && Object.keys(attributes).length >= LIMITS.attributesPerSpan) return;
56
+ attributes[name] = typeof value === "string" ? cutChars(value, charsFor(name)) : value;
57
+ }
58
+ function setAttributes(attributes, values) {
59
+ if (!values) return;
60
+ for (const [name, value] of Object.entries(values)) {
61
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
62
+ setAttribute(attributes, name, value);
63
+ }
64
+ }
65
+ }
66
+ var STORAGE_KEY = /* @__PURE__ */ Symbol.for("sypnia.node.scope");
67
+ var storage = globalThis[STORAGE_KEY] ??= new AsyncLocalStorage();
68
+ function currentScope() {
69
+ return storage.getStore();
70
+ }
71
+ function enterScope(scope) {
72
+ storage.enterWith(scope);
73
+ }
74
+ function runInScope(scope, fn) {
75
+ return storage.run(scope, fn);
76
+ }
77
+ function runOutside(fn) {
78
+ return storage.exit(fn);
79
+ }
80
+
81
+ // ../node/src/clock.ts
82
+ var ORIGIN_MS = performance.timeOrigin;
83
+ function nowNs() {
84
+ return msToNs(ORIGIN_MS + performance.now());
85
+ }
86
+ function msToNs(ms) {
87
+ return BigInt(Math.round(ms * 1e3)) * 1000n;
88
+ }
89
+ function nsToMs(ns) {
90
+ return Number(ns / 1000n) / 1e3;
91
+ }
92
+
93
+ // ../node/src/exception.ts
94
+ function text(value) {
95
+ try {
96
+ if (typeof value === "string") return value;
97
+ return JSON.stringify(value) ?? String(value);
98
+ } catch {
99
+ return String(value);
100
+ }
101
+ }
102
+ function errorParts(error) {
103
+ const record = error && typeof error === "object" ? error : null;
104
+ const message = record && typeof record.message === "string" ? record.message : text(error);
105
+ const type = record && typeof record.name === "string" && record.name ? record.name : "Error";
106
+ const stack = record && typeof record.stack === "string" ? record.stack : null;
107
+ const rawDigest = record?.digest;
108
+ const digest = typeof rawDigest === "string" || typeof rawDigest === "number" ? String(rawDigest) : null;
109
+ return { type, message, stack, digest: digest || null };
110
+ }
111
+ function exceptionEvent(parts, source) {
112
+ const type = cutChars(parts.type || "Error", 100);
113
+ const message = cutChars(parts.message, LIMITS.messageChars);
114
+ const stack = parts.stack ? cutChars(parts.stack, LIMITS.stackChars) : null;
115
+ const digest = parts.digest ? cutChars(parts.digest, LIMITS.digestChars) : null;
116
+ const fingerprint = errorFingerprint({ name: type, message, stack, digest });
117
+ const attributes = {};
118
+ setAttribute(attributes, "exception.type", type);
119
+ setAttribute(attributes, "exception.message", message);
120
+ setAttribute(attributes, "exception.stacktrace", stack);
121
+ setAttribute(attributes, "sypnia.error.source", source);
122
+ setAttribute(attributes, "sypnia.error.fingerprint", fingerprint);
123
+ setAttribute(attributes, "sypnia.error.digest", digest);
124
+ return { event: { timeNs: nowNs(), attributes }, fingerprint };
125
+ }
126
+ var OWN_PREFIX = "[sypnia]";
127
+ function loggedError(args) {
128
+ const parts = [];
129
+ let firstError = null;
130
+ let usedString = false;
131
+ for (const arg of args) {
132
+ if (typeof arg === "string") {
133
+ if (usedString) continue;
134
+ usedString = true;
135
+ if (arg.startsWith(OWN_PREFIX)) return null;
136
+ parts.push(arg.replace(/%[sdifoOjc]/g, "").trim());
137
+ } else if (arg instanceof Error) {
138
+ const error = errorParts(arg);
139
+ parts.push(error.message);
140
+ firstError ??= error;
141
+ }
142
+ }
143
+ const message = parts.filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
144
+ if (!message) return null;
145
+ return { type: firstError?.type ?? "console.error", message, stack: firstError?.stack ?? null, digest: null };
146
+ }
147
+
148
+ // ../node/src/otlp/protobuf.ts
149
+ var WIRE_VARINT = 0;
150
+ var WIRE_FIXED64 = 1;
151
+ var WIRE_BYTES = 2;
152
+ var encoder = new TextEncoder();
153
+ var ProtoWriter = class _ProtoWriter {
154
+ constructor() {
155
+ this.chunks = [];
156
+ this.size = 0;
157
+ }
158
+ push(bytes) {
159
+ this.chunks.push(bytes);
160
+ this.size += bytes.length;
161
+ }
162
+ tag(field, wire) {
163
+ this.varint(field << 3 | wire);
164
+ }
165
+ /** An unsigned varint; negative numbers as 64-bit two's complement, as protobuf writes int64 and int32. */
166
+ varint(value) {
167
+ if (typeof value === "number") {
168
+ const out2 = [];
169
+ let rest2 = value;
170
+ while (rest2 > 127) {
171
+ out2.push(rest2 & 127 | 128);
172
+ rest2 >>>= 7;
173
+ }
174
+ out2.push(rest2);
175
+ this.push(Uint8Array.from(out2));
176
+ return;
177
+ }
178
+ let rest = BigInt.asUintN(64, value);
179
+ const out = [];
180
+ while (rest > 0x7fn) {
181
+ out.push(Number(rest & 0x7fn) | 128);
182
+ rest >>= 7n;
183
+ }
184
+ out.push(Number(rest));
185
+ this.push(Uint8Array.from(out));
186
+ }
187
+ /** int32, int64, enum and bool fields. Zero is the default and is not written. */
188
+ int(field, value) {
189
+ if (value === 0 || value === 0n || value === false) return this;
190
+ return this.intAlways(field, value);
191
+ }
192
+ /** A varint field written even when it is zero (a `oneof` member). */
193
+ intAlways(field, value) {
194
+ this.tag(field, WIRE_VARINT);
195
+ if (typeof value === "boolean") this.varint(value ? 1 : 0);
196
+ else if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2147483647) this.varint(value);
197
+ else this.varint(BigInt(value));
198
+ return this;
199
+ }
200
+ fixed64(field, value) {
201
+ if (value === 0n) return this;
202
+ this.tag(field, WIRE_FIXED64);
203
+ const bytes = new Uint8Array(8);
204
+ new DataView(bytes.buffer).setBigUint64(0, BigInt.asUintN(64, value), true);
205
+ this.push(bytes);
206
+ return this;
207
+ }
208
+ double(field, value) {
209
+ this.tag(field, WIRE_FIXED64);
210
+ const bytes = new Uint8Array(8);
211
+ new DataView(bytes.buffer).setFloat64(0, value, true);
212
+ this.push(bytes);
213
+ return this;
214
+ }
215
+ bytes(field, value) {
216
+ if (value.length === 0) return this;
217
+ this.tag(field, WIRE_BYTES);
218
+ this.varint(value.length);
219
+ this.push(value);
220
+ return this;
221
+ }
222
+ /** A string field written even when it is empty (a `oneof` member). */
223
+ stringAlways(field, value) {
224
+ const bytes = encoder.encode(value);
225
+ this.tag(field, WIRE_BYTES);
226
+ this.varint(bytes.length);
227
+ this.push(bytes);
228
+ return this;
229
+ }
230
+ string(field, value) {
231
+ return value ? this.stringAlways(field, value) : this;
232
+ }
233
+ /** A nested message, written as bytes (written even when empty, so a present message stays present). */
234
+ message(field, write) {
235
+ const nested = new _ProtoWriter();
236
+ write(nested);
237
+ const bytes = nested.finish();
238
+ this.tag(field, WIRE_BYTES);
239
+ this.varint(bytes.length);
240
+ this.push(bytes);
241
+ return this;
242
+ }
243
+ finish() {
244
+ const out = new Uint8Array(this.size);
245
+ let at2 = 0;
246
+ for (const chunk of this.chunks) {
247
+ out.set(chunk, at2);
248
+ at2 += chunk.length;
249
+ }
250
+ return out;
251
+ }
252
+ };
253
+ function readFields(input) {
254
+ const fields = [];
255
+ let at2 = 0;
256
+ const readVarint = () => {
257
+ let result = 0n;
258
+ let shift = 0n;
259
+ for (; ; ) {
260
+ const byte = input[at2++];
261
+ if (byte === void 0) throw new Error("truncated varint");
262
+ result |= BigInt(byte & 127) << shift;
263
+ if ((byte & 128) === 0) return result;
264
+ shift += 7n;
265
+ }
266
+ };
267
+ while (at2 < input.length) {
268
+ const key = Number(readVarint());
269
+ const field = key >> 3;
270
+ const wire = key & 7;
271
+ if (wire === WIRE_VARINT) fields.push({ field, wire, varint: readVarint() });
272
+ else if (wire === WIRE_FIXED64) {
273
+ fields.push({ field, wire, bytes: input.slice(at2, at2 + 8) });
274
+ at2 += 8;
275
+ } else if (wire === WIRE_BYTES) {
276
+ const length = Number(readVarint());
277
+ fields.push({ field, wire, bytes: input.slice(at2, at2 + length) });
278
+ at2 += length;
279
+ } else if (wire === 5) at2 += 4;
280
+ else throw new Error(`unsupported wire type ${wire}`);
281
+ }
282
+ if (at2 !== input.length) throw new Error("truncated message");
283
+ return fields;
284
+ }
285
+
286
+ // ../node/src/otlp/encode.ts
287
+ var decoder = new TextDecoder();
288
+ function hexBytes(hex) {
289
+ const out = new Uint8Array(hex.length / 2);
290
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
291
+ return out;
292
+ }
293
+ function anyValue(writer, value) {
294
+ if (typeof value === "string") writer.stringAlways(1, value);
295
+ else if (typeof value === "boolean") writer.intAlways(2, value);
296
+ else if (Number.isInteger(value)) writer.intAlways(3, value);
297
+ else writer.double(4, value);
298
+ }
299
+ function keyValues(writer, field, attributes) {
300
+ for (const [key, value] of Object.entries(attributes)) {
301
+ writer.message(field, (kv) => kv.string(1, key).message(2, (v) => anyValue(v, value)));
302
+ }
303
+ }
304
+ function span(writer, data) {
305
+ writer.bytes(1, hexBytes(data.traceId)).bytes(2, hexBytes(data.spanId)).bytes(4, data.parentSpanId ? hexBytes(data.parentSpanId) : new Uint8Array()).string(5, data.name).int(6, data.kind).fixed64(7, data.startNs).fixed64(8, data.endNs ?? data.startNs);
306
+ keyValues(writer, 9, data.attributes);
307
+ for (const event of data.events) {
308
+ writer.message(11, (e) => {
309
+ e.fixed64(1, event.timeNs).string(2, "exception");
310
+ keyValues(e, 3, event.attributes);
311
+ });
312
+ }
313
+ if (data.status.code !== 0 || data.status.message) {
314
+ writer.message(15, (s) => s.string(2, data.status.message).int(3, data.status.code));
315
+ }
316
+ }
317
+ function encodeTraces(resource, spans2) {
318
+ return new ProtoWriter().message(1, (rs) => {
319
+ rs.message(1, (r) => keyValues(r, 1, resource.attributes));
320
+ rs.message(2, (ss) => {
321
+ ss.message(1, (scope) => scope.string(1, resource.scope.name).string(2, resource.scope.version));
322
+ for (const data of spans2) ss.message(2, (w) => span(w, data));
323
+ });
324
+ }).finish();
325
+ }
326
+ function readPartialSuccess(body) {
327
+ try {
328
+ const partial = readFields(body).find((f) => f.field === 1)?.bytes;
329
+ if (!partial) return null;
330
+ let rejectedSpans = 0;
331
+ let errorMessage = "";
332
+ for (const f of readFields(partial)) {
333
+ if (f.field === 1 && f.varint !== void 0) rejectedSpans = Number(BigInt.asIntN(64, f.varint));
334
+ if (f.field === 2 && f.bytes) errorMessage = decoder.decode(f.bytes);
335
+ }
336
+ return rejectedSpans > 0 || errorMessage ? { rejectedSpans, errorMessage } : null;
337
+ } catch {
338
+ return null;
339
+ }
340
+ }
341
+
342
+ // ../node/src/export/slow-down.ts
343
+ var MODES = ["all", "failures", "none"];
344
+ function parseSlowDown(header) {
345
+ if (!header) return null;
346
+ let send = null;
347
+ let until = Number.NaN;
348
+ for (const part of header.split(";")) {
349
+ const [rawKey, ...rest] = part.split("=");
350
+ const key = rawKey?.trim().toLowerCase();
351
+ const value = rest.join("=").trim();
352
+ if (key === "send" && MODES.includes(value)) send = value;
353
+ if (key === "until") until = Date.parse(value);
354
+ }
355
+ if (!send) return null;
356
+ return { send, until: Number.isFinite(until) ? until : send === "all" ? 0 : Number.NaN };
357
+ }
358
+ function sendModeAt(slowDown, now) {
359
+ if (!slowDown || slowDown.send === "all") return "all";
360
+ if (!Number.isFinite(slowDown.until) || now >= slowDown.until) return "all";
361
+ return slowDown.send;
362
+ }
363
+
364
+ // ../node/src/export/exporter.ts
365
+ var gzip = promisify(gzip$1);
366
+ var RETRYABLE = /* @__PURE__ */ new Set([429, 502, 503, 504]);
367
+ var Exporter = class {
368
+ constructor(options) {
369
+ this.options = options;
370
+ this.queue = [];
371
+ this.queuedSpans = 0;
372
+ this.slowDown = null;
373
+ this.inFlight = /* @__PURE__ */ new Set();
374
+ this.interval = null;
375
+ this.url = `${options.endpoint}/v1/otlp/v1/traces`;
376
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
377
+ this.now = options.now ?? Date.now;
378
+ this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
379
+ }
380
+ /** The address the SDK sends to: calls to it are never traced. */
381
+ get target() {
382
+ return this.url;
383
+ }
384
+ get pending() {
385
+ return this.queuedSpans;
386
+ }
387
+ start() {
388
+ if (this.interval) return;
389
+ this.interval = setInterval(() => void this.exportQueued(), LIMITS.exportIntervalMs);
390
+ this.interval.unref?.();
391
+ }
392
+ stop() {
393
+ if (this.interval) clearInterval(this.interval);
394
+ this.interval = null;
395
+ }
396
+ /** Queues a request's spans, unless the «slow down» in force says not to send them. */
397
+ enqueue(group) {
398
+ const mode = sendModeAt(this.slowDown, this.now());
399
+ if (mode === "none" || mode === "failures" && !group.failure) {
400
+ this.options.log.debug(`not sent (slow down: ${mode}): ${group.spans[0]?.name ?? ""}`);
401
+ return;
402
+ }
403
+ this.queue.push(group);
404
+ this.queuedSpans += group.spans.length;
405
+ while (this.queuedSpans > LIMITS.queueMaxSpans && this.queue.length > 1) {
406
+ const index = this.queue.findIndex((item) => !item.failure);
407
+ const [dropped] = this.queue.splice(index >= 0 ? index : 0, 1);
408
+ this.queuedSpans -= dropped?.spans.length ?? 0;
409
+ this.options.log.warn("too many spans waiting to be sent: the oldest were dropped");
410
+ }
411
+ }
412
+ /** Sends everything queued; resolves when sent, or after `timeoutMs`. */
413
+ async flush(timeoutMs = 2e3) {
414
+ const work = this.exportQueued().then(() => Promise.all([...this.inFlight])).then(() => void 0);
415
+ let timer;
416
+ const timeout = new Promise((resolve) => {
417
+ timer = setTimeout(resolve, timeoutMs);
418
+ timer.unref?.();
419
+ });
420
+ await Promise.race([work, timeout]);
421
+ if (timer) clearTimeout(timer);
422
+ }
423
+ /** Takes whole requests from the queue, at most 512 spans per export, and sends them. */
424
+ exportQueued() {
425
+ const sends = [];
426
+ while (this.queue.length > 0) {
427
+ const batch = [];
428
+ while (this.queue.length > 0) {
429
+ const next = this.queue[0];
430
+ if (!next || batch.length > 0 && batch.length + next.spans.length > LIMITS.exportMaxSpans) break;
431
+ this.queue.shift();
432
+ this.queuedSpans -= next.spans.length;
433
+ batch.push(...next.spans);
434
+ }
435
+ sends.push(this.track(this.send(batch)));
436
+ }
437
+ return Promise.all(sends).then(() => void 0);
438
+ }
439
+ track(work) {
440
+ this.inFlight.add(work);
441
+ return work.finally(() => this.inFlight.delete(work));
442
+ }
443
+ async send(spans2) {
444
+ if (spans2.length === 0) return;
445
+ let body;
446
+ try {
447
+ body = new Uint8Array(await gzip(encodeTraces(this.options.resource, spans2)));
448
+ } catch {
449
+ this.options.log.warn("export failed: the spans could not be encoded");
450
+ return;
451
+ }
452
+ await this.attempt(body, spans2.length, 0);
453
+ }
454
+ async attempt(body, count, retry) {
455
+ let status = 0;
456
+ let retryAfter = null;
457
+ try {
458
+ const response = await runOutside(
459
+ () => this.fetch(this.url, {
460
+ method: "POST",
461
+ headers: {
462
+ authorization: `Bearer ${this.options.project}`,
463
+ "content-type": "application/x-protobuf",
464
+ "content-encoding": "gzip"
465
+ },
466
+ body
467
+ })
468
+ );
469
+ status = response.status;
470
+ this.noteSlowDown(response.headers.get("sypnia-slow-down"));
471
+ if (response.ok) {
472
+ const partial = readPartialSuccess(new Uint8Array(await response.arrayBuffer()));
473
+ if (partial) this.options.log.debug(`${partial.rejectedSpans} spans not stored: ${partial.errorMessage}`);
474
+ this.options.log.debug(`exported ${count} spans (${status})`);
475
+ return;
476
+ }
477
+ if (status === 429 && this.slowDown?.send === "none") {
478
+ this.options.log.warn("export refused: the usage limit was reached (429 limit_reached)");
479
+ return;
480
+ }
481
+ if (!RETRYABLE.has(status)) {
482
+ this.options.log.warn(`export failed (${status})`);
483
+ return;
484
+ }
485
+ retryAfter = retryAfterMs(response.headers.get("retry-after"), this.now());
486
+ } catch {
487
+ status = 0;
488
+ }
489
+ const delay = LIMITS.retryDelaysMs[retry];
490
+ if (delay === void 0) {
491
+ this.options.log.warn(`export failed (${status || "no answer"}), ${count} spans dropped`);
492
+ return;
493
+ }
494
+ this.options.log.debug(`export failed (${status || "no answer"}), retrying`);
495
+ const wait = Math.min(LIMITS.retryAfterMaxMs, retryAfter ?? delay);
496
+ await new Promise((resolve) => this.setTimer(resolve, wait).unref?.());
497
+ await this.attempt(body, count, retry + 1);
498
+ }
499
+ noteSlowDown(header) {
500
+ const parsed = parseSlowDown(header);
501
+ if (!parsed) return;
502
+ this.slowDown = parsed;
503
+ this.options.log.debug(`slow down: send=${parsed.send}${parsed.until ? ` until ${new Date(parsed.until).toISOString()}` : ""}`);
504
+ }
505
+ };
506
+ function retryAfterMs(value, now) {
507
+ if (!value) return null;
508
+ const seconds = Number(value);
509
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
510
+ const date = Date.parse(value);
511
+ return Number.isFinite(date) ? Math.max(0, date - now) : null;
512
+ }
513
+ var POOL = Buffer.alloc(4096);
514
+ var at = POOL.length;
515
+ function randomHex(bytes) {
516
+ if (at + bytes > POOL.length) {
517
+ randomFillSync(POOL);
518
+ at = 0;
519
+ }
520
+ const hex = POOL.toString("hex", at, at + bytes);
521
+ at += bytes;
522
+ return hex;
523
+ }
524
+ function newTraceId() {
525
+ const id = randomHex(16);
526
+ return /^0+$/.test(id) ? newTraceId() : id;
527
+ }
528
+ function newSpanId() {
529
+ const id = randomHex(8);
530
+ return /^0+$/.test(id) ? newSpanId() : id;
531
+ }
532
+
533
+ // ../node/src/span.ts
534
+ var SpanKind = { internal: 1, server: 2, client: 3 };
535
+ var StatusCode = { unset: 0, ok: 1, error: 2 };
536
+ function startSpan(input) {
537
+ return {
538
+ traceId: input.traceId,
539
+ spanId: newSpanId(),
540
+ parentSpanId: input.parentSpanId,
541
+ name: cutChars(input.name, LIMITS.spanNameChars),
542
+ kind: input.kind,
543
+ startNs: input.startNs ?? nowNs(),
544
+ endNs: null,
545
+ attributes: {},
546
+ events: [],
547
+ status: { code: StatusCode.unset, message: "" }
548
+ };
549
+ }
550
+ function endSpan(span3, at2 = nowNs()) {
551
+ if (span3.endNs === null) span3.endNs = at2 < span3.startNs ? span3.startNs : at2;
552
+ }
553
+ function failSpan(span3, message, errorType, maxChars = LIMITS.messageChars) {
554
+ span3.status = { code: StatusCode.error, message: cutChars(message, maxChars) };
555
+ if (errorType) setAttribute(span3.attributes, "error.type", errorType);
556
+ }
557
+ function isFailedStatus(status) {
558
+ return status === 0 || status === 400 || status >= 500;
559
+ }
560
+ function hasFailure(span3) {
561
+ return span3.status.code === StatusCode.error || span3.events.length > 0;
562
+ }
563
+ function copySpan(span3) {
564
+ return { ...span3, attributes: { ...span3.attributes }, events: span3.events.map((e) => ({ ...e, attributes: { ...e.attributes } })), status: { ...span3.status } };
565
+ }
566
+
567
+ // ../node/src/debug.ts
568
+ function duration(span3) {
569
+ const ms = span3.endNs === null ? 0 : nsToMs(span3.endNs - span3.startNs);
570
+ return `${Math.round(ms).toLocaleString("en-US")} ms`;
571
+ }
572
+ function line(span3) {
573
+ const status = span3.attributes["http.response.status_code"];
574
+ const failed = span3.status.code === StatusCode.error ? " \xB7 failed" : "";
575
+ const running = span3.attributes["sypnia.running"] === true ? " \xB7 running" : "";
576
+ return `${span3.name}${status !== void 0 ? ` ${status}` : ""} \xB7 ${duration(span3)}${failed}${running}`;
577
+ }
578
+ function spanTree(spans2) {
579
+ const [root] = spans2;
580
+ if (!root) return "";
581
+ const children = /* @__PURE__ */ new Map();
582
+ for (const span3 of spans2.slice(1)) {
583
+ const parent = span3.parentSpanId ?? root.spanId;
584
+ children.set(parent, [...children.get(parent) ?? [], span3]);
585
+ }
586
+ const lines = [];
587
+ const walk = (span3, depth) => {
588
+ lines.push(`${" ".repeat(depth)}${line(span3)}`);
589
+ for (const event of span3.events) lines.push(`${" ".repeat(depth + 1)}! ${String(event.attributes["exception.type"])}: ${String(event.attributes["exception.message"])}`);
590
+ for (const child of children.get(span3.spanId) ?? []) walk(child, depth + 1);
591
+ };
592
+ walk(root, 0);
593
+ return lines.join("\n");
594
+ }
595
+
596
+ // ../node/src/request.ts
597
+ var RequestTrace = class {
598
+ constructor(server) {
599
+ this.server = server;
600
+ this.children = [];
601
+ this.dropped = 0;
602
+ this.finished = false;
603
+ /** A partial copy was exported: the full one must replace it. */
604
+ this.partialSent = false;
605
+ this.slowTimer = null;
606
+ /** A request of an anonymous route: `identify()` is ignored in it. */
607
+ this.anonymous = false;
608
+ /** Failed answers still being read (db-errors.ts): the end waits for them, briefly. */
609
+ this.pending = /* @__PURE__ */ new Set();
610
+ this.fingerprints = /* @__PURE__ */ new Set();
611
+ this.failures = 0;
612
+ this.logFailures = 0;
613
+ }
614
+ get traceId() {
615
+ return this.server.traceId;
616
+ }
617
+ /** Work the request's export waits for, at most `dbDetailWaitMs`. */
618
+ track(work) {
619
+ this.pending.add(work);
620
+ void work.finally(() => this.pending.delete(work));
621
+ }
622
+ /** Keeps the span if there is room; false when it was only counted. */
623
+ addChild(span3) {
624
+ if (this.children.length >= LIMITS.spansPerRequest) {
625
+ this.dropped++;
626
+ return false;
627
+ }
628
+ this.children.push(span3);
629
+ return true;
630
+ }
631
+ /** Adds an `exception` event to `span` within the per-request limits; false when it was left out. */
632
+ addException(span3, event, fingerprint, source) {
633
+ if (this.failures >= LIMITS.failuresPerRequest || this.fingerprints.has(fingerprint)) return false;
634
+ if (source === "log" && this.logFailures >= LIMITS.logFailuresPerRequest) return false;
635
+ this.fingerprints.add(fingerprint);
636
+ this.failures++;
637
+ if (source === "log") this.logFailures++;
638
+ span3.events.push(event);
639
+ return true;
640
+ }
641
+ /** Something in the request failed: it is exported even when only failures are being sent. */
642
+ hasFailure() {
643
+ const status = this.server.attributes["http.response.status_code"];
644
+ if (typeof status === "number" && status >= 500) return true;
645
+ return hasFailure(this.server) || this.children.some(hasFailure);
646
+ }
647
+ /** Ends the request with the status it answered. Calls still running are ended now and marked. */
648
+ finish(status) {
649
+ if (this.finished) return;
650
+ this.finished = true;
651
+ if (this.slowTimer) clearTimeout(this.slowTimer);
652
+ const at2 = nowNs();
653
+ if (status !== null) setAttribute(this.server.attributes, "http.response.status_code", status);
654
+ for (const child of this.children) {
655
+ if (child.endNs === null) {
656
+ endSpan(child, at2);
657
+ setAttribute(child.attributes, "sypnia.running", true);
658
+ }
659
+ }
660
+ if (this.dropped > 0) setAttribute(this.server.attributes, "sypnia.dropped_spans", this.dropped);
661
+ endSpan(this.server, at2);
662
+ }
663
+ /** The spans of the request as they stand, for a request still running (`sypnia.partial`). */
664
+ partialSpans() {
665
+ const at2 = nowNs();
666
+ const server = copySpan(this.server);
667
+ server.endNs = at2;
668
+ setAttribute(server.attributes, "sypnia.partial", true);
669
+ delete server.attributes["http.response.status_code"];
670
+ if (this.dropped > 0) setAttribute(server.attributes, "sypnia.dropped_spans", this.dropped);
671
+ const children = this.children.map((child) => {
672
+ const copy = copySpan(child);
673
+ if (copy.endNs === null) {
674
+ copy.endNs = at2;
675
+ setAttribute(copy.attributes, "sypnia.running", true);
676
+ }
677
+ return copy;
678
+ });
679
+ return [server, ...children];
680
+ }
681
+ /** Every span of the finished request, the server span first. */
682
+ spans() {
683
+ return [this.server, ...this.children];
684
+ }
685
+ };
686
+
687
+ // ../node/src/instrument/skip.ts
688
+ var STATIC_FILE_RE = /\.(?:js|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|txt|xml|webmanifest)$/i;
689
+ function isIgnoredRequest(options, method, path) {
690
+ if (method.toUpperCase() === "OPTIONS") return true;
691
+ if (STATIC_FILE_RE.test(path)) return true;
692
+ const route = pathnameOf(path);
693
+ if (options.allowRoutes.length > 0 && !matchesRoute(route, options.allowRoutes) && !isAnonymousRoute(options, route)) return true;
694
+ return matchesRoute(route, options.ignoreRoutes);
695
+ }
696
+ function isAnonymousRoute(options, path) {
697
+ return options.anonymousRoutes.length > 0 && matchesRoute(pathnameOf(path), options.anonymousRoutes);
698
+ }
699
+
700
+ // ../node/src/sdk.ts
701
+ var KEY = /* @__PURE__ */ Symbol.for("sypnia.node.sdk");
702
+ function getSdk() {
703
+ return globalThis[KEY] ?? null;
704
+ }
705
+ function setSdk(sdk) {
706
+ if (sdk) globalThis[KEY] = sdk;
707
+ else delete globalThis[KEY];
708
+ }
709
+ function startRequest(sdk, request) {
710
+ const parent = parseTraceparent(request.header("traceparent"));
711
+ const method = request.method.toUpperCase();
712
+ const server = startSpan({
713
+ traceId: parent?.traceId ?? newTraceId(),
714
+ parentSpanId: parent?.spanId ?? null,
715
+ name: method,
716
+ kind: SpanKind.server
717
+ });
718
+ setAttribute(server.attributes, "http.request.method", method);
719
+ setAttribute(server.attributes, "url.path", request.path);
720
+ const session = request.header("x-sypnia-session")?.trim().toLowerCase();
721
+ if (session && /^[0-9a-f]{32}$/.test(session)) setAttribute(server.attributes, "session.id", session);
722
+ const trace = startTrace(sdk, server);
723
+ if (isAnonymousRoute(sdk.options, request.path)) {
724
+ trace.anonymous = true;
725
+ setAttribute(server.attributes, "sypnia.anonymous", true);
726
+ }
727
+ return trace;
728
+ }
729
+ function startTrace(sdk, server) {
730
+ if (sdk.cold) {
731
+ sdk.cold = false;
732
+ setAttribute(server.attributes, "faas.coldstart", true);
733
+ }
734
+ const trace = new RequestTrace(server);
735
+ if (sdk.options.slowRequestMs > 0) {
736
+ trace.slowTimer = setTimeout(() => exportPartial(sdk, trace), sdk.options.slowRequestMs);
737
+ trace.slowTimer.unref?.();
738
+ }
739
+ return trace;
740
+ }
741
+ function routeFor(sdk, path, frameworkRoute2) {
742
+ try {
743
+ if (sdk.options.routeFor) return sdk.options.routeFor(path) || routeOf(path);
744
+ } catch {
745
+ }
746
+ return frameworkRoute2 || routeOf(path);
747
+ }
748
+ function nameRoute(trace, route) {
749
+ const method = trace.server.attributes["http.request.method"];
750
+ setAttribute(trace.server.attributes, "http.route", route);
751
+ trace.server.name = method ? `${String(method)} ${route}` : route;
752
+ }
753
+ function exportPartial(sdk, trace) {
754
+ try {
755
+ if (trace.finished || getSdk() !== sdk) return;
756
+ if (!trace.server.attributes["http.route"]) nameRoute(trace, routeFor(sdk, String(trace.server.attributes["url.path"] ?? "/"), null));
757
+ trace.partialSent = true;
758
+ const spans2 = trace.partialSpans();
759
+ if (sdk.log.debugOn) sdk.log.debug(`still running after ${sdk.options.slowRequestMs} ms, exported as partial:
760
+ ${spanTree(spans2)}`);
761
+ sdk.exporter.enqueue({ spans: spans2, failure: true });
762
+ } catch {
763
+ }
764
+ }
765
+ function finishRequest(sdk, trace, status, route) {
766
+ if (trace.finished) return Promise.resolve();
767
+ nameRoute(trace, route);
768
+ trace.finish(status);
769
+ if (status !== null && status >= 500 && trace.server.status.code === StatusCode.unset) {
770
+ trace.server.status = { code: StatusCode.error, message: "" };
771
+ }
772
+ if (trace.pending.size === 0) {
773
+ queueRequest(sdk, trace);
774
+ return Promise.resolve();
775
+ }
776
+ let timer;
777
+ const waited = new Promise((resolve) => {
778
+ timer = setTimeout(resolve, LIMITS.dbDetailWaitMs);
779
+ timer.unref?.();
780
+ });
781
+ return Promise.race([Promise.allSettled([...trace.pending]), waited]).then(() => {
782
+ if (timer) clearTimeout(timer);
783
+ queueRequest(sdk, trace);
784
+ });
785
+ }
786
+ function queueRequest(sdk, trace) {
787
+ const spans2 = review(sdk, trace.spans());
788
+ if (!spans2) return;
789
+ if (sdk.log.debugOn) sdk.log.debug(spanTree(spans2));
790
+ sdk.exporter.enqueue({ spans: spans2, failure: trace.hasFailure() || trace.partialSent });
791
+ }
792
+ var KIND_NAMES = { [SpanKind.internal]: "internal", [SpanKind.server]: "server", [SpanKind.client]: "client" };
793
+ var STATUS_NAMES = { [StatusCode.unset]: "unset", [StatusCode.ok]: "ok", [StatusCode.error]: "error" };
794
+ var STATUS_CODES = { unset: StatusCode.unset, ok: StatusCode.ok, error: StatusCode.error };
795
+ function review(sdk, spans2) {
796
+ const beforeSend = sdk.options.beforeSend;
797
+ if (!beforeSend) return spans2;
798
+ const kept = [];
799
+ for (const [index, span3] of spans2.entries()) {
800
+ let reviewed;
801
+ try {
802
+ reviewed = beforeSend({
803
+ name: span3.name,
804
+ kind: KIND_NAMES[span3.kind],
805
+ attributes: { ...span3.attributes },
806
+ status: { code: STATUS_NAMES[span3.status.code], message: span3.status.message }
807
+ });
808
+ } catch {
809
+ reviewed = { name: span3.name, kind: KIND_NAMES[span3.kind], attributes: span3.attributes, status: { code: STATUS_NAMES[span3.status.code], message: span3.status.message } };
810
+ }
811
+ if (!reviewed) {
812
+ if (index === 0) {
813
+ sdk.log.debug(`dropped by beforeSend: ${span3.name}`);
814
+ return null;
815
+ }
816
+ continue;
817
+ }
818
+ span3.name = String(reviewed.name || span3.name);
819
+ span3.attributes = {};
820
+ for (const [key, value] of Object.entries(reviewed.attributes ?? {})) setAttribute(span3.attributes, key, value);
821
+ span3.status = { code: STATUS_CODES[reviewed.status?.code] ?? span3.status.code, message: String(reviewed.status?.message ?? "") };
822
+ kept.push(span3);
823
+ }
824
+ return kept;
825
+ }
826
+ function startCall(name, kind, scope = currentScope()) {
827
+ if (!scope || scope.request.finished) return null;
828
+ const span3 = startSpan({ traceId: scope.request.traceId, parentSpanId: scope.parent.spanId, name, kind });
829
+ return scope.request.addChild(span3) ? span3 : null;
830
+ }
831
+ function reportException(sdk, error, source, parts = errorParts(error)) {
832
+ const { event, fingerprint } = exceptionEvent(parts, source);
833
+ const scope = currentScope();
834
+ if (scope && !scope.request.finished) {
835
+ scope.request.addException(scope.parent, event, fingerprint, source);
836
+ return;
837
+ }
838
+ const span3 = startSpan({ traceId: newTraceId(), parentSpanId: null, name: "uncaught", kind: SpanKind.internal });
839
+ setAttribute(span3.attributes, "sypnia.error.standalone", true);
840
+ span3.events.push(event);
841
+ endSpan(span3);
842
+ const spans2 = review(sdk, [span3]);
843
+ if (!spans2) return;
844
+ if (sdk.log.debugOn) sdk.log.debug(spanTree(spans2));
845
+ sdk.exporter.enqueue({ spans: spans2, failure: true });
846
+ }
847
+
848
+ // ../node/src/instrument/call.ts
849
+ var POSTGREST_OPERATIONS = {
850
+ GET: "SELECT",
851
+ HEAD: "SELECT",
852
+ POST: "INSERT",
853
+ PUT: "INSERT",
854
+ PATCH: "UPDATE",
855
+ DELETE: "DELETE"
856
+ };
857
+ function segment(value) {
858
+ if (!value) return null;
859
+ try {
860
+ return decodeURIComponent(value).slice(0, 80) || null;
861
+ } catch {
862
+ return value.slice(0, 80);
863
+ }
864
+ }
865
+ function postgrestCall(method, path) {
866
+ const parts = pathnameOf(path).split("/").filter(Boolean);
867
+ if (parts[0] !== "rest" || parts[1] !== "v1") return null;
868
+ if (parts[2] === "rpc") return { operation: "CALL", collection: segment(parts[3]) };
869
+ const operation = POSTGREST_OPERATIONS[method.toUpperCase()];
870
+ return operation ? { operation, collection: segment(parts[2]) } : null;
871
+ }
872
+ function describeCall(span3, target) {
873
+ const method = target.method.toUpperCase();
874
+ const route = routeOf(target.path);
875
+ setAttribute(span3.attributes, "http.request.method", method);
876
+ setAttribute(span3.attributes, "server.address", target.host);
877
+ setAttribute(span3.attributes, "url.path", route);
878
+ const postgrest = postgrestCall(method, target.path);
879
+ if (!postgrest) {
880
+ span3.name = `${method} ${route}`;
881
+ return;
882
+ }
883
+ span3.name = postgrest.collection ? `${postgrest.operation} ${postgrest.collection}` : postgrest.operation;
884
+ setAttribute(span3.attributes, "db.system.name", "postgresql");
885
+ setAttribute(span3.attributes, "db.operation.name", postgrest.operation);
886
+ setAttribute(span3.attributes, "db.collection.name", postgrest.collection);
887
+ setAttribute(span3.attributes, "sypnia.db.via", "postgrest");
888
+ }
889
+ var DB_CODE_RE = /^(?:[0-9A-Z]{5}|[A-Za-z][A-Za-z0-9_.-]{0,39})$/;
890
+ function applyDbError(span3, detail) {
891
+ if (detail.code && DB_CODE_RE.test(detail.code)) setAttribute(span3.attributes, "db.response.status_code", detail.code);
892
+ if (!detail.message) return;
893
+ setAttribute(span3.attributes, "sypnia.db.message", detail.message);
894
+ if (span3.status.code === StatusCode.error) span3.status.message = cutChars(detail.message, LIMITS.dbMessageChars);
895
+ }
896
+ function answerCall(span3, status, end = true) {
897
+ setAttribute(span3.attributes, "http.response.status_code", status);
898
+ if (isFailedStatus(status)) {
899
+ failSpan(span3, "", String(status));
900
+ if (span3.attributes["sypnia.db.via"] === "postgrest") setAttribute(span3.attributes, "db.response.status_code", String(status));
901
+ }
902
+ if (end) endSpan(span3);
903
+ }
904
+ function failCall(span3, error) {
905
+ const record = error && typeof error === "object" ? error : {};
906
+ const cause = record.cause && typeof record.cause === "object" ? record.cause : null;
907
+ const code = [cause?.code, record.code, record.name].find((value) => typeof value === "string" && value !== "");
908
+ const message = [cause?.message, record.message].find((value) => typeof value === "string" && value !== "") ?? "";
909
+ failSpan(span3, redactMessage(message), code ?? "Error");
910
+ endSpan(span3);
911
+ }
912
+ var SLOT_KEY = /* @__PURE__ */ Symbol.for("sypnia.node.fetchSlot");
913
+ var WRAPPED = /* @__PURE__ */ Symbol.for("sypnia.node.fetchWrapped");
914
+ var slots = globalThis[SLOT_KEY] ??= new AsyncLocalStorage();
915
+ function noteFetchSpan(span3) {
916
+ const slot = slots.getStore();
917
+ if (slot && !slot.span) slot.span = span3;
918
+ }
919
+ function stringField(text2, name) {
920
+ const match = new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(text2);
921
+ if (!match) return null;
922
+ try {
923
+ return JSON.parse(`"${match[1] ?? ""}"`);
924
+ } catch {
925
+ return null;
926
+ }
927
+ }
928
+ function dbErrorOfBody(text2) {
929
+ let body = null;
930
+ try {
931
+ const parsed = JSON.parse(text2);
932
+ if (parsed && typeof parsed === "object") body = parsed;
933
+ } catch {
934
+ }
935
+ const pick = (...names) => {
936
+ for (const name of names) {
937
+ const value = body ? body[name] : stringField(text2, name);
938
+ if (typeof value === "string" && value) return value;
939
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
940
+ }
941
+ return null;
942
+ };
943
+ const code = pick("code", "error_code");
944
+ const message = fullDbMessage(pick("message", "msg", "error_description"), pick("details"), pick("hint"));
945
+ return code || message ? { code, message } : null;
946
+ }
947
+ function fullDbMessage(message, details, hint) {
948
+ const parts = [message, details ? `Detail: ${details}` : null, hint ? `Hint: ${hint}` : null].filter((p) => !!p);
949
+ return parts.length ? parts.join("\n") : null;
950
+ }
951
+ async function readBounded(body, max = LIMITS.dbBodyBytes) {
952
+ const reader = body.getReader();
953
+ const decoder2 = new TextDecoder();
954
+ let text2 = "";
955
+ let bytes = 0;
956
+ try {
957
+ while (bytes < max) {
958
+ const { done, value } = await reader.read();
959
+ if (done || !value) break;
960
+ const room = max - bytes;
961
+ const piece = value.byteLength > room ? value.subarray(0, room) : value;
962
+ bytes += piece.byteLength;
963
+ text2 += decoder2.decode(piece, { stream: true });
964
+ }
965
+ text2 += decoder2.decode();
966
+ } finally {
967
+ void reader.cancel().catch(() => void 0);
968
+ }
969
+ return text2;
970
+ }
971
+ function readFailure(response, span3) {
972
+ if (response.status < 400 || span3.attributes["sypnia.db.via"] !== "postgrest") return null;
973
+ if (!(response.headers.get("content-type") ?? "").includes("json")) return null;
974
+ const copy = response.clone().body;
975
+ if (!copy) return null;
976
+ return readBounded(copy).then(
977
+ (text2) => {
978
+ const detail = dbErrorOfBody(text2);
979
+ if (detail) applyDbError(span3, detail);
980
+ },
981
+ () => void 0
982
+ );
983
+ }
984
+ function captureFetchDbErrors() {
985
+ const original = globalThis.fetch;
986
+ if (typeof original !== "function" || original[WRAPPED]) return () => void 0;
987
+ const wrapped = function(...args) {
988
+ const scope = currentScope();
989
+ if (!scope) return original.apply(this, args);
990
+ const slot = { span: null };
991
+ const promise = slots.run(slot, () => original.apply(this, args));
992
+ promise.then(
993
+ (response) => {
994
+ try {
995
+ const reading = slot.span ? readFailure(response, slot.span) : null;
996
+ if (reading) scope.request.track(reading);
997
+ } catch {
998
+ }
999
+ },
1000
+ () => void 0
1001
+ );
1002
+ return promise;
1003
+ };
1004
+ Object.assign(wrapped, original);
1005
+ wrapped[WRAPPED] = true;
1006
+ globalThis.fetch = wrapped;
1007
+ return () => {
1008
+ if (globalThis.fetch === wrapped) globalThis.fetch = original;
1009
+ };
1010
+ }
1011
+
1012
+ // ../node/src/instrument/client.ts
1013
+ var spans = /* @__PURE__ */ new WeakMap();
1014
+ function isOwnExport(sdk, origin, path) {
1015
+ return `${origin}${path.split("?")[0] ?? ""}` === sdk.exporter.target;
1016
+ }
1017
+ function begin(origin, host, method, path) {
1018
+ const sdk = getSdk();
1019
+ if (!sdk || !sdk.options.capture.outgoing || isOwnExport(sdk, origin, path)) return null;
1020
+ const scope = currentScope();
1021
+ const span3 = startCall(method, SpanKind.client, scope);
1022
+ if (!span3) return null;
1023
+ describeCall(span3, { method, host, path });
1024
+ return span3;
1025
+ }
1026
+ function traceparentOf(span3) {
1027
+ return formatTraceparent(span3.traceId, span3.spanId);
1028
+ }
1029
+ function onHttpCreated(message) {
1030
+ try {
1031
+ const { request } = message;
1032
+ if (!request || spans.has(request)) return;
1033
+ const protocol = request.protocol || "http:";
1034
+ const host = request.host || "localhost";
1035
+ const span3 = begin(`${protocol}//${host}`, host, request.method || "GET", request.path || "/");
1036
+ if (!span3) return;
1037
+ spans.set(request, span3);
1038
+ if (getSdk()?.options.propagate && !request.headersSent && !request.hasHeader("traceparent")) {
1039
+ request.setHeader("traceparent", traceparentOf(span3));
1040
+ }
1041
+ } catch {
1042
+ }
1043
+ }
1044
+ function onHttpResponse(message) {
1045
+ try {
1046
+ const { request, response } = message;
1047
+ const span3 = spans.get(request);
1048
+ if (span3 && span3.endNs === null) answerCall(span3, response.statusCode ?? 0);
1049
+ } catch {
1050
+ }
1051
+ }
1052
+ function onHttpError(message) {
1053
+ try {
1054
+ const { request, error } = message;
1055
+ const span3 = spans.get(request);
1056
+ if (span3 && span3.endNs === null) failCall(span3, error);
1057
+ } catch {
1058
+ }
1059
+ }
1060
+ function hasHeader(headers, name) {
1061
+ if (typeof headers === "string") return headers.toLowerCase().split("\r\n").some((line2) => line2.startsWith(`${name}:`));
1062
+ if (Array.isArray(headers)) return headers.some((value, index) => index % 2 === 0 && String(value).toLowerCase() === name);
1063
+ return false;
1064
+ }
1065
+ function onUndiciCreate(message) {
1066
+ try {
1067
+ const { request } = message;
1068
+ if (!request || spans.has(request)) return;
1069
+ const origin = String(request.origin ?? "");
1070
+ let host = "";
1071
+ try {
1072
+ host = new URL(origin).host;
1073
+ } catch {
1074
+ host = origin;
1075
+ }
1076
+ const span3 = begin(origin.replace(/\/+$/, ""), host, request.method || "GET", request.path || "/");
1077
+ if (!span3) return;
1078
+ spans.set(request, span3);
1079
+ noteFetchSpan(span3);
1080
+ if (getSdk()?.options.propagate && !hasHeader(request.headers, "traceparent")) {
1081
+ request.addHeader?.("traceparent", traceparentOf(span3));
1082
+ }
1083
+ } catch {
1084
+ }
1085
+ }
1086
+ function onUndiciHeaders(message) {
1087
+ try {
1088
+ const { request, response } = message;
1089
+ const span3 = spans.get(request);
1090
+ if (span3 && span3.endNs === null) answerCall(span3, response.statusCode ?? 0);
1091
+ } catch {
1092
+ }
1093
+ }
1094
+ function onUndiciTrailers(message) {
1095
+ try {
1096
+ const { request } = message;
1097
+ const span3 = spans.get(request);
1098
+ if (span3 && span3.endNs !== null) span3.endNs = nowNs();
1099
+ } catch {
1100
+ }
1101
+ }
1102
+ function onUndiciError(message) {
1103
+ try {
1104
+ const { request, error } = message;
1105
+ const span3 = spans.get(request);
1106
+ if (span3 && span3.endNs === null) failCall(span3, error);
1107
+ } catch {
1108
+ }
1109
+ }
1110
+ var SUBSCRIPTIONS = [
1111
+ // `created` lets the SDK add `traceparent` before the headers leave; a Node without it only has `start`.
1112
+ ["http.client.request.created", onHttpCreated],
1113
+ ["http.client.request.start", onHttpCreated],
1114
+ ["http.client.response.finish", onHttpResponse],
1115
+ ["http.client.request.error", onHttpError],
1116
+ ["undici:request:create", onUndiciCreate],
1117
+ ["undici:request:headers", onUndiciHeaders],
1118
+ ["undici:request:trailers", onUndiciTrailers],
1119
+ ["undici:request:error", onUndiciError]
1120
+ ];
1121
+ function instrumentClient() {
1122
+ for (const [name, handler] of SUBSCRIPTIONS) diagnostics.subscribe(name, handler);
1123
+ return () => {
1124
+ for (const [name, handler] of SUBSCRIPTIONS) diagnostics.unsubscribe(name, handler);
1125
+ };
1126
+ }
1127
+
1128
+ // ../node/src/instrument/sql.ts
1129
+ var OPERATION_RE = /^\s*(?:\/\*[\s\S]*?\*\/\s*|--[^\n]*\n\s*)*([A-Za-z]+)/;
1130
+ var TABLE_RE = {
1131
+ SELECT: /\bfrom\s+((?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))?)/i,
1132
+ DELETE: /\bfrom\s+((?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))?)/i,
1133
+ INSERT: /\binto\s+((?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))?)/i,
1134
+ UPDATE: /\bupdate\s+(?:only\s+)?((?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))?)/i
1135
+ };
1136
+ function sqlName(statement) {
1137
+ const operation = (OPERATION_RE.exec(statement)?.[1] ?? "QUERY").toUpperCase();
1138
+ const pattern = TABLE_RE[operation];
1139
+ const raw = pattern ? pattern.exec(statement)?.[1] : void 0;
1140
+ const table = raw ? (raw.split(".").pop() ?? raw).replace(/"/g, "").slice(0, 80) : null;
1141
+ return { operation, table };
1142
+ }
1143
+
1144
+ // ../node/src/instrument/pg.ts
1145
+ var WRAPPED2 = /* @__PURE__ */ Symbol.for("sypnia.node.pg");
1146
+ function statementOf(first) {
1147
+ if (typeof first === "string") return first;
1148
+ if (first && typeof first === "object" && typeof first.text === "string") return first.text;
1149
+ return null;
1150
+ }
1151
+ function startQuery(client, statement) {
1152
+ const sdk = getSdk();
1153
+ if (!sdk || !sdk.options.capture.db) return null;
1154
+ const { operation, table } = sqlName(statement);
1155
+ const span3 = startCall(table ? `${operation} ${table}` : operation, SpanKind.client);
1156
+ if (!span3) return null;
1157
+ const database = client.database ?? client.connectionParameters?.database;
1158
+ const host = client.host ?? client.connectionParameters?.host;
1159
+ setAttribute(span3.attributes, "db.system.name", "postgresql");
1160
+ setAttribute(span3.attributes, "db.operation.name", operation);
1161
+ setAttribute(span3.attributes, "db.collection.name", table);
1162
+ if (typeof database === "string") setAttribute(span3.attributes, "db.namespace", database);
1163
+ if (typeof host === "string") setAttribute(span3.attributes, "server.address", host);
1164
+ return span3;
1165
+ }
1166
+ function endQuery(span3, error) {
1167
+ if (error) {
1168
+ const record = error;
1169
+ const code = typeof record.code === "string" ? record.code : null;
1170
+ failSpan(span3, "", code ?? "Error");
1171
+ const text2 = (v) => typeof v === "string" && v ? v : null;
1172
+ const message = getSdk()?.options.captureDbErrors ? fullDbMessage(text2(record.message), text2(record.detail), text2(record.hint)) : null;
1173
+ applyDbError(span3, { code, message });
1174
+ }
1175
+ endSpan(span3);
1176
+ }
1177
+ function wrapPg(pg) {
1178
+ const proto = pg.Client?.prototype;
1179
+ if (!proto || typeof proto.query !== "function" || proto[WRAPPED2]) return () => void 0;
1180
+ const original = proto.query;
1181
+ const wrapped = function(...args) {
1182
+ let span3 = null;
1183
+ try {
1184
+ const statement = statementOf(args[0]);
1185
+ const submittable = !!args[0] && typeof args[0].submit === "function";
1186
+ if (statement && !submittable) span3 = startQuery(this, statement);
1187
+ } catch {
1188
+ span3 = null;
1189
+ }
1190
+ if (!span3) return original.apply(this, args);
1191
+ const active = span3;
1192
+ const callbackAt = args.findIndex((arg) => typeof arg === "function");
1193
+ if (callbackAt >= 0) {
1194
+ const callback = args[callbackAt];
1195
+ args[callbackAt] = function(error, result2) {
1196
+ try {
1197
+ endQuery(active, error);
1198
+ } catch {
1199
+ }
1200
+ return callback.call(this, error, result2);
1201
+ };
1202
+ return original.apply(this, args);
1203
+ }
1204
+ const result = original.apply(this, args);
1205
+ if (result && typeof result.then === "function") {
1206
+ result.then(
1207
+ () => endQuery(active, null),
1208
+ (error) => endQuery(active, error ?? new Error("query failed"))
1209
+ );
1210
+ }
1211
+ return result;
1212
+ };
1213
+ proto[WRAPPED2] = original;
1214
+ proto.query = wrapped;
1215
+ return () => {
1216
+ if (proto.query === wrapped) proto.query = original;
1217
+ delete proto[WRAPPED2];
1218
+ };
1219
+ }
1220
+ function findPg(from = process.cwd()) {
1221
+ try {
1222
+ return createRequire(join(from, "package.json"))("pg");
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ }
1227
+
1228
+ // ../node/src/instrument/process.ts
1229
+ function onUncaught(error) {
1230
+ try {
1231
+ const sdk = getSdk();
1232
+ if (!sdk || !sdk.options.capture.uncaught) return;
1233
+ reportException(sdk, error, "uncaught");
1234
+ const scope = currentScope();
1235
+ if (scope && !scope.request.finished) exportPartial(sdk, scope.request);
1236
+ void sdk.exporter.flush(sdk.options.flushBudgetMs);
1237
+ } catch {
1238
+ }
1239
+ }
1240
+ function instrumentUncaught() {
1241
+ process.on("uncaughtExceptionMonitor", onUncaught);
1242
+ return () => process.off("uncaughtExceptionMonitor", onUncaught);
1243
+ }
1244
+ var PATCHED = /* @__PURE__ */ Symbol.for("sypnia.node.console");
1245
+ function instrumentConsole() {
1246
+ const target = console;
1247
+ if (target[PATCHED]) return () => void 0;
1248
+ const original = target.error;
1249
+ const wrapped = function(...args) {
1250
+ try {
1251
+ const sdk = getSdk();
1252
+ if (sdk?.options.capture.consoleErrors && currentScope()) {
1253
+ const parts = loggedError(args);
1254
+ if (parts) reportException(sdk, null, "log", parts);
1255
+ }
1256
+ } catch {
1257
+ }
1258
+ return original.apply(this, args);
1259
+ };
1260
+ target[PATCHED] = original;
1261
+ target.error = wrapped;
1262
+ return () => {
1263
+ if (target.error === wrapped) target.error = original;
1264
+ delete target[PATCHED];
1265
+ };
1266
+ }
1267
+ var CHANNEL = "http.server.request.start";
1268
+ function headerOf(request, name) {
1269
+ const value = request.headers[name];
1270
+ const first = Array.isArray(value) ? value[0] : value;
1271
+ return typeof first === "string" && first ? first : null;
1272
+ }
1273
+ function frameworkRoute(request) {
1274
+ const express = request;
1275
+ const path = express.route?.path;
1276
+ if (typeof path !== "string" || !path) return null;
1277
+ const base = typeof express.baseUrl === "string" ? express.baseUrl : "";
1278
+ return `${base}${path}` || "/";
1279
+ }
1280
+ function onRequestStart(message) {
1281
+ try {
1282
+ const sdk = getSdk();
1283
+ const { request, response } = message;
1284
+ if (!sdk || !request || !response) {
1285
+ enterScope(void 0);
1286
+ return;
1287
+ }
1288
+ const method = request.method ?? "GET";
1289
+ const path = cutChars(pathnameOf(request.url ?? "/"), LIMITS.urlPathChars);
1290
+ if (isIgnoredRequest(sdk.options, method, path)) {
1291
+ enterScope(void 0);
1292
+ return;
1293
+ }
1294
+ const trace = startRequest(sdk, { method, path, header: (name) => headerOf(request, name) });
1295
+ enterScope({ request: trace, parent: trace.server });
1296
+ const end = () => finish(sdk, request, response, path, trace);
1297
+ response.once("finish", end);
1298
+ response.once("close", end);
1299
+ } catch {
1300
+ }
1301
+ }
1302
+ function finish(sdk, request, response, path, trace) {
1303
+ try {
1304
+ void finishRequest(sdk, trace, response.statusCode || null, routeFor(sdk, path, frameworkRoute(request)));
1305
+ } catch {
1306
+ }
1307
+ }
1308
+ function instrumentServer() {
1309
+ diagnostics.subscribe(CHANNEL, onRequestStart);
1310
+ return () => diagnostics.unsubscribe(CHANNEL, onRequestStart);
1311
+ }
1312
+
1313
+ // ../node/src/log.ts
1314
+ var Log = class {
1315
+ constructor(debugging, now = Date.now) {
1316
+ this.debugging = debugging;
1317
+ this.now = now;
1318
+ this.lastWarnAt = -Infinity;
1319
+ }
1320
+ get debugOn() {
1321
+ return this.debugging;
1322
+ }
1323
+ debug(message) {
1324
+ if (this.debugging) console.log(`[sypnia] ${message}`);
1325
+ }
1326
+ warn(message) {
1327
+ const now = this.now();
1328
+ if (!this.debugging && now - this.lastWarnAt < LIMITS.warnEveryMs) return;
1329
+ this.lastWarnAt = now;
1330
+ console.warn(`[sypnia] ${message}`);
1331
+ }
1332
+ };
1333
+ function warnOnce(message) {
1334
+ const key = /* @__PURE__ */ Symbol.for("sypnia.node.warned");
1335
+ const store = globalThis;
1336
+ const seen = store[key] ??= /* @__PURE__ */ new Set();
1337
+ if (seen.has(message)) return;
1338
+ seen.add(message);
1339
+ console.warn(`[sypnia] ${message}`);
1340
+ }
1341
+
1342
+ // ../node/src/options.ts
1343
+ function env(name) {
1344
+ const value = typeof process !== "undefined" ? process.env[name] : void 0;
1345
+ return value && value.trim() ? value.trim() : void 0;
1346
+ }
1347
+ function nonNegative(value, fallback) {
1348
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
1349
+ }
1350
+ function resolveOptions(options) {
1351
+ const project = options.project ?? env("SYPNIA_PROJECT_KEY");
1352
+ if (!project) return null;
1353
+ const environment = cutChars(options.environment || env("SYPNIA_ENVIRONMENT") || "production", LIMITS.environmentChars);
1354
+ const release = options.release ?? env("SYPNIA_RELEASE");
1355
+ return {
1356
+ project,
1357
+ endpoint: baseUrl(options.endpoint ?? env("SYPNIA_ENDPOINT")),
1358
+ service: cutChars(options.service || env("SYPNIA_SERVICE") || "server", LIMITS.serviceChars),
1359
+ environment,
1360
+ release: release ? cutChars(release, LIMITS.releaseChars) : null,
1361
+ debug: options.debug === true,
1362
+ ignoreRoutes: options.ignoreRoutes ?? [],
1363
+ allowRoutes: options.allowRoutes ?? [],
1364
+ anonymousRoutes: options.anonymousRoutes ?? [],
1365
+ captureDbErrors: options.captureDbErrors !== false,
1366
+ routeFor: typeof options.routeFor === "function" ? options.routeFor : null,
1367
+ pg: options.pg && typeof options.pg === "object" ? options.pg : null,
1368
+ capture: {
1369
+ outgoing: options.capture?.outgoing !== false,
1370
+ db: options.capture?.db !== false,
1371
+ consoleErrors: options.capture?.consoleErrors !== false,
1372
+ uncaught: options.capture?.uncaught !== false
1373
+ },
1374
+ propagate: options.propagate !== false,
1375
+ slowRequestMs: nonNegative(options.slowRequestMs, 2e4),
1376
+ flushBudgetMs: nonNegative(options.flushBudgetMs, 50),
1377
+ beforeSend: typeof options.beforeSend === "function" ? options.beforeSend : null
1378
+ };
1379
+ }
1380
+
1381
+ // ../node/src/version.ts
1382
+ var SDK_NAME = "@sypnia/telemetry/node" ;
1383
+ var SDK_VERSION = "0.3.0" ;
1384
+
1385
+ // ../node/src/api.ts
1386
+ var BRIDGE_MARKER = /* @__PURE__ */ Symbol.for("sypnia.otel.bridge");
1387
+ function init(options = {}) {
1388
+ try {
1389
+ if (getSdk() || options.enabled === false) return;
1390
+ if (globalThis[BRIDGE_MARKER]) {
1391
+ if (options.debug) console.log("[sypnia] the OpenTelemetry bridge is registered: @sypnia/node stands down");
1392
+ return;
1393
+ }
1394
+ const resolved = resolveOptions(options);
1395
+ if (!resolved) {
1396
+ warnOnce("off: no project (set SYPNIA_PROJECT_KEY or the option `project`)");
1397
+ return;
1398
+ }
1399
+ const log = new Log(resolved.debug);
1400
+ const resource = {
1401
+ attributes: {
1402
+ "service.name": resolved.service,
1403
+ "deployment.environment.name": resolved.environment,
1404
+ ...resolved.release ? { "service.version": resolved.release } : {},
1405
+ "telemetry.sdk.name": SDK_NAME,
1406
+ "telemetry.sdk.version": SDK_VERSION,
1407
+ "telemetry.sdk.language": "nodejs"
1408
+ },
1409
+ scope: { name: SDK_NAME, version: SDK_VERSION }
1410
+ };
1411
+ const exporter = new Exporter({ endpoint: resolved.endpoint, project: resolved.project, resource, log });
1412
+ const sdk = { options: resolved, log, exporter, cold: true, cleanups: [] };
1413
+ setSdk(sdk);
1414
+ exporter.start();
1415
+ sdk.cleanups.push(() => exporter.stop(), instrumentServer(), instrumentClient());
1416
+ if (resolved.capture.outgoing && resolved.capture.db && resolved.captureDbErrors) sdk.cleanups.push(captureFetchDbErrors());
1417
+ if (resolved.capture.uncaught) sdk.cleanups.push(instrumentUncaught());
1418
+ if (resolved.capture.consoleErrors) sdk.cleanups.push(instrumentConsole());
1419
+ if (resolved.capture.db) {
1420
+ const pg = resolved.pg ?? findPg();
1421
+ if (pg) sdk.cleanups.push(wrapPg(pg));
1422
+ }
1423
+ const onBeforeExit = () => {
1424
+ if (exporter.pending > 0) void exporter.flush();
1425
+ };
1426
+ process.on("beforeExit", onBeforeExit);
1427
+ sdk.cleanups.push(() => process.off("beforeExit", onBeforeExit));
1428
+ log.debug(
1429
+ `started ${resolved.project.slice(0, 8)}\u2026 \u2192 ${resolved.endpoint} \xB7 service ${resolved.service} \xB7 ${resolved.environment}${resolved.release ? ` \xB7 ${resolved.release}` : ""}`
1430
+ );
1431
+ } catch {
1432
+ }
1433
+ }
1434
+ function identify(who) {
1435
+ try {
1436
+ const scope = currentScope();
1437
+ if (!scope || !who || scope.request.anonymous) return;
1438
+ const person = who.person ? cutChars(String(who.person.id ?? ""), LIMITS.idChars) : "";
1439
+ if (person) setAttribute(scope.request.server.attributes, "user.id", person);
1440
+ const account = who.account ? cutChars(String(who.account.id ?? ""), LIMITS.idChars) : "";
1441
+ if (account) setAttribute(scope.request.server.attributes, "sypnia.account.id", account);
1442
+ } catch {
1443
+ }
1444
+ }
1445
+ function reportError(error) {
1446
+ try {
1447
+ const sdk = getSdk();
1448
+ if (sdk) reportException(sdk, error, "manual");
1449
+ } catch {
1450
+ }
1451
+ }
1452
+ function span2(name, fn, attrs) {
1453
+ let child = null;
1454
+ const scope = currentScope();
1455
+ try {
1456
+ if (getSdk() && scope) {
1457
+ child = startCall(String(name), SpanKind.internal, scope);
1458
+ if (child) setAttributes(child.attributes, attrs);
1459
+ }
1460
+ } catch {
1461
+ child = null;
1462
+ }
1463
+ if (!child || !scope) return fn();
1464
+ const active = child;
1465
+ const fail = (error) => {
1466
+ try {
1467
+ failSpan(active, redactMessage(errorParts(error).message), errorParts(error).type);
1468
+ endSpan(active);
1469
+ } catch {
1470
+ }
1471
+ };
1472
+ let result;
1473
+ try {
1474
+ result = runInScope({ request: scope.request, parent: active }, fn);
1475
+ } catch (error) {
1476
+ fail(error);
1477
+ throw error;
1478
+ }
1479
+ if (result && typeof result.then === "function") {
1480
+ result.then(() => endSpan(active), fail);
1481
+ } else {
1482
+ endSpan(active);
1483
+ }
1484
+ return result;
1485
+ }
1486
+ async function flush(timeoutMs = 2e3) {
1487
+ try {
1488
+ await getSdk()?.exporter.flush(timeoutMs);
1489
+ } catch {
1490
+ }
1491
+ }
1492
+ async function shutdown(timeoutMs = 2e3) {
1493
+ const sdk = getSdk();
1494
+ if (!sdk) return;
1495
+ await flush(timeoutMs);
1496
+ for (const cleanup of sdk.cleanups.splice(0)) {
1497
+ try {
1498
+ cleanup();
1499
+ } catch {
1500
+ }
1501
+ }
1502
+ setSdk(null);
1503
+ }
1504
+ function captureRequestError(error, request, extra = {}) {
1505
+ try {
1506
+ const sdk = getSdk();
1507
+ if (!sdk) return;
1508
+ const parts = errorParts(error);
1509
+ if (extra.digest) parts.digest = extra.digest;
1510
+ const scope = currentScope();
1511
+ if (scope && !scope.request.finished) {
1512
+ reportException(sdk, error, "uncaught", parts);
1513
+ return;
1514
+ }
1515
+ const header = (name) => {
1516
+ const wanted = name.toLowerCase();
1517
+ for (const [key, value] of Object.entries(request.headers ?? {})) {
1518
+ if (key.toLowerCase() !== wanted) continue;
1519
+ const first = Array.isArray(value) ? value[0] : value;
1520
+ return typeof first === "string" && first ? first : null;
1521
+ }
1522
+ return null;
1523
+ };
1524
+ const path = request.path.split("?")[0] || "/";
1525
+ const trace = startRequest(sdk, { method: request.method || "GET", path, header });
1526
+ runInScope({ request: trace, parent: trace.server }, () => reportException(sdk, error, "uncaught", parts));
1527
+ void finishRequest(sdk, trace, 500, extra.route || routeOf(path));
1528
+ } catch {
1529
+ }
1530
+ }
1531
+
1532
+ // ../node/src/wait-until.ts
1533
+ var CONTEXTS = [/* @__PURE__ */ Symbol.for("@vercel/request-context"), /* @__PURE__ */ Symbol.for("@next/request-context")];
1534
+ var provider = null;
1535
+ function setWaitUntil(source) {
1536
+ provider = source;
1537
+ }
1538
+ function currentWaitUntil() {
1539
+ try {
1540
+ const own = provider?.();
1541
+ if (own) return own;
1542
+ const holder = globalThis;
1543
+ for (const key of CONTEXTS) {
1544
+ const waitUntil = holder[key]?.get?.()?.waitUntil;
1545
+ if (typeof waitUntil === "function") return waitUntil;
1546
+ }
1547
+ return null;
1548
+ } catch {
1549
+ return null;
1550
+ }
1551
+ }
1552
+
1553
+ // ../node/src/fetch-handler.ts
1554
+ async function sendAfter(sdk, waitUntil) {
1555
+ const work = sdk.exporter.flush(Math.max(sdk.options.flushBudgetMs, 2e3));
1556
+ const keepAlive = waitUntil ?? currentWaitUntil();
1557
+ if (keepAlive) {
1558
+ keepAlive(work);
1559
+ return;
1560
+ }
1561
+ let timer;
1562
+ await Promise.race([work, new Promise((resolve) => timer = setTimeout(resolve, sdk.options.flushBudgetMs))]);
1563
+ if (timer) clearTimeout(timer);
1564
+ }
1565
+ function pathOf(raw) {
1566
+ let path = raw;
1567
+ try {
1568
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) path = new URL(raw).pathname;
1569
+ } catch {
1570
+ }
1571
+ return cutChars(pathnameOf(path), LIMITS.urlPathChars);
1572
+ }
1573
+ async function traceRequest(request, handle, options) {
1574
+ const sdk = getSdk();
1575
+ const path = pathOf(request.path || "/");
1576
+ if (!sdk || currentScope() || isIgnoredRequest(sdk.options, request.method, path)) {
1577
+ try {
1578
+ return await handle();
1579
+ } finally {
1580
+ if (sdk && currentScope()) await sendAfter(sdk, options.waitUntil).catch(() => void 0);
1581
+ }
1582
+ }
1583
+ const trace = startRequest(sdk, { method: request.method, path, header: (name) => request.header(name) ?? null });
1584
+ const scope = { request: trace, parent: trace.server };
1585
+ let status = null;
1586
+ try {
1587
+ const result = await runInScope(scope, handle);
1588
+ status = options.statusOf(result);
1589
+ return result;
1590
+ } catch (error) {
1591
+ status = 500;
1592
+ runInScope(scope, () => reportException(sdk, error, "uncaught"));
1593
+ throw error;
1594
+ } finally {
1595
+ try {
1596
+ await finishRequest(sdk, trace, status, routeFor(sdk, path, null));
1597
+ await sendAfter(sdk, options.waitUntil);
1598
+ } catch {
1599
+ }
1600
+ }
1601
+ }
1602
+ function wrapFetchHandler(handler) {
1603
+ return function traced(request, ...rest) {
1604
+ return traceRequest(
1605
+ { method: request.method, path: request.url, header: (name) => request.headers.get(name) },
1606
+ async () => handler(request, ...rest),
1607
+ { statusOf: (response) => response.status }
1608
+ );
1609
+ };
1610
+ }
1611
+
1612
+ // ../node/src/propagation.ts
1613
+ var SQS_MAX_ATTRIBUTES = 10;
1614
+ var KEY2 = "traceparent";
1615
+ function currentTraceparent() {
1616
+ try {
1617
+ const scope = currentScope();
1618
+ if (!getSdk() || !scope || scope.request.finished) return null;
1619
+ return formatTraceparent(scope.parent.traceId, scope.parent.spanId);
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ }
1624
+ function injectTraceContext(payload) {
1625
+ try {
1626
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
1627
+ if (KEY2 in payload) return payload;
1628
+ const traceparent = currentTraceparent();
1629
+ return traceparent ? { ...payload, [KEY2]: traceparent } : payload;
1630
+ } catch {
1631
+ return payload;
1632
+ }
1633
+ }
1634
+ function sqsTraceAttributes(attributes) {
1635
+ try {
1636
+ const existing = attributes ?? {};
1637
+ const names = Object.keys(existing);
1638
+ const traceparent = currentTraceparent();
1639
+ if (!traceparent || names.some((name) => name.toLowerCase() === KEY2) || names.length >= SQS_MAX_ATTRIBUTES) return attributes;
1640
+ return { ...existing, [KEY2]: { DataType: "String", StringValue: traceparent } };
1641
+ } catch {
1642
+ return attributes;
1643
+ }
1644
+ }
1645
+ function stringIn(value) {
1646
+ if (typeof value === "string") return value;
1647
+ if (!value || typeof value !== "object") return null;
1648
+ const record = value;
1649
+ const inner = record.stringValue ?? record.StringValue;
1650
+ return typeof inner === "string" ? inner : null;
1651
+ }
1652
+ function keyed(record) {
1653
+ for (const [name, value] of Object.entries(record)) {
1654
+ if (name.toLowerCase() === KEY2) return stringIn(value);
1655
+ }
1656
+ return null;
1657
+ }
1658
+ function traceparentOf2(carrier) {
1659
+ try {
1660
+ if (typeof carrier === "string") return parseTraceparent(carrier) ? carrier : null;
1661
+ if (!carrier || typeof carrier !== "object") return null;
1662
+ const record = carrier;
1663
+ const candidates = [record, record.messageAttributes, record.MessageAttributes, record.headers];
1664
+ for (const candidate of candidates) {
1665
+ if (!candidate || typeof candidate !== "object") continue;
1666
+ const found = keyed(candidate);
1667
+ if (found && parseTraceparent(found)) return found;
1668
+ }
1669
+ return null;
1670
+ } catch {
1671
+ return null;
1672
+ }
1673
+ }
1674
+
1675
+ // ../node/src/jobs.ts
1676
+ var FLUSH_TIMEOUT_MS = 2e3;
1677
+ var FLUSH_MARGIN_MS = 100;
1678
+ function startJob(sdk, job) {
1679
+ const parent = parseTraceparent(job.traceparent);
1680
+ const server = startSpan({ traceId: parent?.traceId ?? newTraceId(), parentSpanId: parent?.spanId ?? null, name: job.name, kind: SpanKind.server });
1681
+ setAttribute(server.attributes, "http.route", job.name);
1682
+ setAttribute(server.attributes, "sypnia.job", job.name);
1683
+ setAttributes(server.attributes, job.attributes);
1684
+ return startTrace(sdk, server);
1685
+ }
1686
+ async function runJob(sdk, job, fn) {
1687
+ const trace = startJob(sdk, job);
1688
+ const scope = { request: trace, parent: trace.server };
1689
+ try {
1690
+ return await runInScope(scope, fn);
1691
+ } catch (error) {
1692
+ try {
1693
+ runInScope(scope, () => reportException(sdk, error, "uncaught"));
1694
+ const parts = errorParts(error);
1695
+ failSpan(trace.server, redactMessage(parts.message), parts.type);
1696
+ } catch {
1697
+ }
1698
+ throw error;
1699
+ } finally {
1700
+ await finishRequest(sdk, trace, null, job.name).catch(() => void 0);
1701
+ }
1702
+ }
1703
+ async function flushWithin(sdk, context, timeoutMs) {
1704
+ try {
1705
+ let budget = timeoutMs ?? FLUSH_TIMEOUT_MS;
1706
+ const remaining = typeof context?.getRemainingTimeInMillis === "function" ? context.getRemainingTimeInMillis() : null;
1707
+ if (typeof remaining === "number" && Number.isFinite(remaining)) budget = Math.min(budget, remaining - FLUSH_MARGIN_MS);
1708
+ if (budget > 0) await sdk.exporter.flush(budget);
1709
+ } catch {
1710
+ }
1711
+ }
1712
+ function attributesOf(read, input) {
1713
+ try {
1714
+ return read?.(input) ?? {};
1715
+ } catch {
1716
+ return {};
1717
+ }
1718
+ }
1719
+ function queueOf(arn) {
1720
+ const name = typeof arn === "string" ? arn.split(":").pop() : "";
1721
+ return name ? name : null;
1722
+ }
1723
+ async function continueTrace(carrier, name, fn, attributes) {
1724
+ const sdk = getSdk();
1725
+ if (!sdk) return fn();
1726
+ return runJob(sdk, { name: String(name || "job"), traceparent: traceparentOf2(carrier), attributes: attributes ?? {} }, fn);
1727
+ }
1728
+ async function traceSqsRecord(record, fn, options = {}) {
1729
+ const sdk = getSdk();
1730
+ if (!sdk) return fn();
1731
+ let name;
1732
+ try {
1733
+ name = (typeof options.name === "function" ? options.name(record) : options.name) || queueOf(record?.eventSourceARN) || "sqs";
1734
+ } catch {
1735
+ name = queueOf(record?.eventSourceARN) || "sqs";
1736
+ }
1737
+ const attempt = Number(record?.attributes?.ApproximateReceiveCount);
1738
+ const attributes = {
1739
+ "faas.trigger": "pubsub",
1740
+ "faas.invocation_id": options.context?.awsRequestId,
1741
+ "messaging.system": "aws_sqs",
1742
+ "messaging.operation.type": "process",
1743
+ "messaging.destination.name": queueOf(record?.eventSourceARN),
1744
+ "messaging.message.id": record?.messageId,
1745
+ "sypnia.job.attempt": Number.isFinite(attempt) ? attempt : void 0,
1746
+ ...attributesOf(options.attributes, record)
1747
+ };
1748
+ return runJob(sdk, { name, traceparent: traceparentOf2(record), attributes }, fn);
1749
+ }
1750
+ function wrapSqsHandler(handle, options = {}) {
1751
+ const partialBatch = options.partialBatch !== false;
1752
+ return async function traced(event, context) {
1753
+ const failures = [];
1754
+ let stopped = null;
1755
+ for (const record of event?.Records ?? []) {
1756
+ try {
1757
+ await traceSqsRecord(record, () => handle(record, context), { name: options.name, attributes: options.attributes, context: context ?? void 0 });
1758
+ } catch (error) {
1759
+ if (!partialBatch) {
1760
+ stopped = { error };
1761
+ break;
1762
+ }
1763
+ failures.push({ itemIdentifier: record.messageId });
1764
+ }
1765
+ }
1766
+ const sdk = getSdk();
1767
+ if (sdk) await flushWithin(sdk, context ?? void 0, options.flushTimeoutMs);
1768
+ if (stopped) throw stopped.error;
1769
+ return { batchItemFailures: failures };
1770
+ };
1771
+ }
1772
+ function httpOf(event) {
1773
+ if (!event || typeof event !== "object") return null;
1774
+ const e = event;
1775
+ const method = e.requestContext?.http?.method ?? e.httpMethod;
1776
+ const path = e.rawPath ?? e.requestContext?.http?.path ?? e.path;
1777
+ if (typeof method !== "string" || typeof path !== "string" || !e.requestContext) return null;
1778
+ const pattern = typeof e.routeKey === "string" ? e.routeKey.replace(/^[A-Z]+ /, "") : e.resource;
1779
+ const route = typeof pattern === "string" && pattern.startsWith("/") && !pattern.includes("{proxy+}") ? pattern : null;
1780
+ return { method, path: path.split("?")[0] || "/", route, headers: e.headers ?? {} };
1781
+ }
1782
+ function isScheduled(event) {
1783
+ if (!event || typeof event !== "object") return false;
1784
+ const e = event;
1785
+ return e.source === "aws.events" || e["detail-type"] === "Scheduled Event" || e.source === "aws.scheduler";
1786
+ }
1787
+ function sqsRecordsOf(event) {
1788
+ if (!event || typeof event !== "object") return null;
1789
+ const records = event.Records;
1790
+ if (!Array.isArray(records) || records.length === 0) return null;
1791
+ return records.every((r) => r && typeof r === "object" && r.eventSource === "aws:sqs") ? records : null;
1792
+ }
1793
+ function statusOf(result) {
1794
+ const status = result && typeof result === "object" ? result.statusCode : void 0;
1795
+ return typeof status === "number" && Number.isInteger(status) ? status : 200;
1796
+ }
1797
+ function wrapLambdaHandler(handler, options = {}) {
1798
+ return async function traced(event, context) {
1799
+ const sdk = getSdk();
1800
+ if (!sdk) return handler(event, context);
1801
+ try {
1802
+ const http = httpOf(event);
1803
+ if (http) return await traceHttp(sdk, http, () => handler(event, context), context ?? void 0);
1804
+ let name;
1805
+ try {
1806
+ name = (typeof options.name === "function" ? options.name(event) : options.name) || "";
1807
+ } catch {
1808
+ name = "";
1809
+ }
1810
+ name ||= context?.functionName || process.env.AWS_LAMBDA_FUNCTION_NAME || "lambda";
1811
+ const records = sqsRecordsOf(event);
1812
+ const scheduled = isScheduled(event);
1813
+ const traceparent = scheduled ? null : records ? records.length === 1 ? traceparentOf2(records[0]) : null : traceparentOf2(event);
1814
+ const attributes = {
1815
+ "faas.trigger": scheduled ? "timer" : records ? "pubsub" : "other",
1816
+ "faas.invocation_id": context?.awsRequestId,
1817
+ ...attributesOf(options.attributes, event)
1818
+ };
1819
+ return await runJob(sdk, { name, traceparent, attributes }, () => handler(event, context));
1820
+ } finally {
1821
+ await flushWithin(sdk, context ?? void 0, options.flushTimeoutMs);
1822
+ }
1823
+ };
1824
+ }
1825
+ async function traceHttp(sdk, http, fn, context) {
1826
+ const lower = {};
1827
+ for (const [key, value] of Object.entries(http.headers)) if (typeof value === "string") lower[key.toLowerCase()] = value;
1828
+ const trace = startRequest(sdk, { method: http.method, path: http.path, header: (name) => lower[name.toLowerCase()] ?? null });
1829
+ setAttribute(trace.server.attributes, "faas.trigger", "http");
1830
+ setAttribute(trace.server.attributes, "faas.invocation_id", context?.awsRequestId);
1831
+ const scope = { request: trace, parent: trace.server };
1832
+ let status = null;
1833
+ try {
1834
+ const result = await runInScope(scope, fn);
1835
+ status = statusOf(result);
1836
+ return result;
1837
+ } catch (error) {
1838
+ status = 500;
1839
+ try {
1840
+ runInScope(scope, () => reportException(sdk, error, "uncaught"));
1841
+ } catch {
1842
+ }
1843
+ throw error;
1844
+ } finally {
1845
+ await finishRequest(sdk, trace, status, routeFor(sdk, http.path, http.route)).catch(() => void 0);
1846
+ }
1847
+ }
1848
+
1849
+ export { BRIDGE_MARKER, captureRequestError, continueTrace, currentTraceparent, flush, identify, init, injectTraceContext, reportError, setWaitUntil, shutdown, span2 as span, sqsTraceAttributes, traceRequest, traceSqsRecord, traceparentOf2 as traceparentOf, wrapFetchHandler, wrapLambdaHandler, wrapSqsHandler };